Вы находитесь на странице: 1из 44

LIST OF C PROGRAMMING

BASIC INPUT, OUTPUT, IF ELSE,


TERNARY OPERATOR BASED
PROGRAMS.

Asmatullah Khan
CL/CP, GIOE, Secunderabad.
C program to print Hello World! - First C program in C
In this program we will print Hello World, this is the first program in C programming language. We
will print Hello World using user define function’s too.

This is the very first program in c programming language, you have to include only single header file that
is stdio.h, this header file contains the declaration printf() function. printf() is used to display message as
well as value on the standard output device (monitor), use of printf function is very easy, you have to just
pass the string (message) that you want to print on the screen within inverted commas ("message").

Hello world/first program in C


/* C program to print Hello World! */

#include <stdio.h>
int main()
{
printf("Hello World!");

return 0;
}

Using function
Here, we are creating a user define function to print the text (“Hello World”) on the screen, read more
about user define functions: C Library and User Define Functions (UDF), C user define functions programs

/* C program to print Hello World! */

#include <stdio.h>

// function to print Hello World!


void printMessage(void)
{
printf("Hello World!");
}

int main()
{
//calling function
printMessage();

return 0;
}

Output

Hello World!
Explanation
There is no other way to learn programming except writing programs. In every programming language we
start programming by printing "Hello World" on the output device.
"Print Hello World in C" is the first program which we are writing here.

About the statements

1) #include <stdio.h>
stdio.h is a header file which contains declarations of standard input, output related functions, this
statement tells to the compiler to include (add) the declarations of all standard input, output related
functions which are declared inside stdio.h

2) int main()
main is a pre-declared function which is defined by the programmer i.e. the declaration of the main is
predefine we can define its body.

main is the entry point from where program’s execution starts. While int is the return type of the main.

3) printf("Hello World!");
"Hello World!" is the sequence of characters it is called character array, string or constant string.

printf is a library function which is declared in stdio.h; this function is responsible to print the text on the
output screen.

4) return 0;
This statement is returning the control of this program to the calling function (operating system’s thread
which called this function) with value 0.

Return value 0 represents that the program’s execution completed successfully.


How to compile and run this program under various operating systems
(or compilers)?
Write program in any text editor and save it with extension .c

Let’s consider the file name is "helloworld.c"

Under TurboC complier (Windows)


Open your saved program (or write program in the editor - use F2 to save it), to compile the program
press ALT+F9, compiler will show all errors and warnings, if there is any error or/and warning correct it
and compile again. If program is error and warning free you can run it by pressing CTRL+F9, after
executing the program, press ALT+F5 to see the output of your program.

Under GCC Compiler (Linux)


To compile the program under GCC run the following command

gcc helloworld.c -o helloworld

Make sure you are in the current directory where program is saved (Learn Linux terminal commands)

If there is no errors or warnings object (binary) file helloworld will be created in the same directory now
you can run program by using following command

./helloworld
C program to find subtraction of two integer number
In this C program, we are going to read two integers numbers and find subtraction of given numbers.
Submitted by Manju Tomar, on November 07, 2017

Given two integer number and find the subtraction of them using C program.

In this program, we are reading two integer numbers in variable a and b and assigning the subtraction
of a and b in the variable sub.

Example 1:
Example 2:
Input number 1: 40
Input number 2: 45 Input number 1: 45
Output: -5 Input number 2: 40
Output: 5

Program to find subtraction of two numbers in C


#include<stdio.h>

int main()
{
int a,b,sub;

//Read value of a
printf("Enter the first no.: ");
scanf("%d",&a);

//Read value of b
printf("Enter the second no.: ");
scanf("%d",&b);

//formula of subtraction
sub= a-b;
printf("subtract is = %d\n", sub);

return 0;
}

Output

First run:
Enter the first no.: 40
Enter the second no.: 45
subtract is = -5

Second run:
Enter the first no.: 45
Enter the second no.: 40
subtract is = 5
C program to find SUM and AVERAGE of two numbers.
In this C program, we are going to learn how to find sum and average of two integer numbers? Here,
we are taking input from the user of two integer number, first number will be stored in the variable a and
second number will be stored in the variable b.

Sum of the numbers is calculating by a+b and assigning into variable sum and average of numbers in
calculating by (float)(a+b)/2 and assigning to variable avg. Here, float is using to cast type.

Sum and Average of two numbers


/* c program find sum and average of two numbers*/
#include <stdio.h>

int main()
{
int a,b,sum;
float avg;

printf("Enter first number :");


scanf("%d",&a);
printf("Enter second number :");
scanf("%d",&b);

sum=a+b;
avg= (float)(a+b)/2;

printf("\nSum of %d and %d is = %d",a,b,sum);


printf("\nAverage of %d and %d is = %f",a,b,avg);

return 0;
}

Output

Enter first number :10


Enter second number :15

Sum of 10 and 15 is = 25
Average of 10 and 15 is = 12.500000
C program to find cube of an integer number using two
different methods
In this C program, we are going to find cube of an integer number. Here, we will implement the
program by using two methods 1) without using pow() function and 2) using pow() function.

A cube can be found by calculating the power of 3 of any number. For example, the cube of 2 will be 23 (2
to the power of 3).

Here, we are implementing this program by using two methods:

1. Without using pow() function


2. With using pow() function

1) Without using pow() function


In this method, we will just read an integer number and multiply it 3 times.

Consider the program:

#include <stdio.h>

int main()
{

int a,cube;

printf("Enter any integer number: ");


scanf("%d",&a);
//calculating cube
cube = (a*a*a);
printf("CUBE is: %d\n",cube);

return 0;
}

Output
Enter any integer number: 8
CUBE is: 512
2) Using pow() function
pow() is a library function of math.h header file, it is used to calculate power of any number. Here, we
will use this function to find the cube of a given number.

Consider the program:

#include <stdio.h>
#include <math.h>

int main()
{

int a,cube;

printf("Enter any integer number: ");


scanf("%d",&a);
//calculating cube
cube = pow(a,3);
printf("CUBE is: %d\n",cube);

return 0;
}

Output
Enter any integer number: 8
CUBE is: 512
C program to find the difference of two numbers
This program will find the difference of two integer numbers. Difference is quite different from
subtraction, in subtraction we just subtract second number from first number and here to get difference
we will subtract smallest number from largest number, so that we can get correct difference of them.

Difference of two integer numbers program


/*C program to find difference of two numbers.*/

#include <stdio.h>

int main()
{

int a,b;
int diff;

printf("Enter first number: ");


scanf("%d",&a);
printf("Enter second number: ");
scanf("%d",&b);

// check condition to identify which is largest number


if( a>b )
diff=a-b;
else
diff=b-a;

printf("\nDifference between %d and %d is = %d",a,b,diff);


return 0;
}

Output

First Run:
Enter first number: 120
Enter second number: 30

Difference between 120 and 30 is = 90

Second Run:
Enter first number: 30
Enter second number: 120

Difference between 30 and 120 is = 90


Using abs() – A Shortest way to find difference of two numbers
By using abs() function we can get the difference of two integer numbers without comparing
them, abs() is a library function which is declared in stdlib.h – This function returns the absolute value of
given integer.

Consider the example

/*C program to find difference of two numbers using abs().*/

#include <stdio.h>
#include <stdlib.h>

int main()
{

int a,b;
int diff;

printf("Enter first number: ");


scanf("%d",&a);
printf("Enter second number: ");
scanf("%d",&b);

diff=abs(a-b);

printf("\nDifference between %d and %d is = %d",a,b,diff);


return 0;
}

Output

First Run:
Enter first number: 120
Enter second number: 30

Difference between 120 and 30 is = 90

Second Run:
Enter first number: 30
Enter second number: 120

Difference between 30 and 120 is = 90


C program to find quotient and remainder
This program will read dividend and divisor and find the quotient and remainder of two numbers in c
language.

How to get quotient and remainder?


Binary operator divide (/) returns the quotient, let suppose if dividend is 10 and divisor is 3, then quotient
will be 3.

Binary operator modulus (%) returns the remainder, let suppose if dividend is 10 and divisor is 3, then
remainder will be 1.

In this c program, we will read dividend and divisor and find the quotient, remainder.

Program to find quotient and remainder in C


#include <stdio.h>

int main()
{
int dividend, divisor;
int quotient, remainder;

printf("Enter dividend: ");


scanf("%d",&dividend);
printf("Enter divisor: ");
scanf("%d",&divisor);

quotient= dividend/divisor;
remainder= dividend%divisor;

printf("quotient: %d, remainder: %d\n",quotient,remainder);

return 0;
}

Output
First run:
Enter dividend: 10
Enter divisor: 3
quotient: 3, remainder: 1

Second run:
Enter dividend: 10
Enter divisor: 2
quotient: 5, remainder: 0

Third run:
Enter dividend: 10
Enter divisor: 100
quotient: 0, remainder: 10
C program to calculate Simple Interest
In this C program, we are going to learn how to calculate simple interest, when principle, rate and
time are given?

Given principal (amount), time and interest rate and we have to calculate simple interest based on
given rate of given time period.

In this program, variable amount is going to be used to store principal amount, rate is going to used to
store interest rate and time is going to be used to store time and si is going to be used to store simple
interest.

Formula to calculate simple interest: (principal x rate x time )/100

C program for Simple Interest


/* c program to calculate simple interest*/
#include <stdio.h>

int main()
{
float amount,rate,time,si;

printf("Enter principal (Amount) :");


scanf("%f",&amount);

printf("Enter rate :");


scanf("%f",&rate);

printf("Enter time (in years) :");


scanf("%f",&time);

si=(amount*rate*time)/100;

printf("\nSimple Interest is = %f",si);

return 0;
}

Output

Enter principal (Amount) :15000


Enter rate :2.8
Enter time (in years) :2

Simple Interest is = 840.000000


C program to check whether a given number is EVEN or
ODD
C program for EVEN or ODD: Here, we are reading an integer number from the user and checking
whether it is EVEN or ODD.

Given an integer number and we have to check it is EVEN or ODD using C program.

The numbers which are divisible by 2 are EVEN numbers and which are not divisible by 0 are not as ODD
numbers.

To check whether given number is EVEN or ODD, we are checking modulus by dividing number by 2, if the
modulus is 0, then it will be completely divisible by 2 hence number will be EVEN or its will be ODD.

Example 1:
Example 2:
Input:
Enter number: 12 Input:
Output: Enter number: 19
12 is an EVEN number. Output:
19 is an ODD number.

C program to check EVEN or ODD


/* c program to check whether number is even or odd*/
#include <stdio.h>
int main()
{
int num;

printf("Enter an integer number: ");


scanf("%d",&num);

/*If number is divisible by 2 then number


is EVEN otherwise number is ODD*/

if(num%2==0)
printf("%d is an EVEN number.",num);
else
printf("%d is an ODD number.",num);

return 0;
}

Output
First Run:
Enter an integer number: 123
123 is an ODD number.

Second Run:
Enter an integer number: 110
110 an EVEN number.
C program to find Largest Number among three
numbers
This program will take three integer numbers from user and find largest number among them; we will
find largest number using two methods - if else and conditional operators.

Program for Largest Number among three numbers


/* c program to find largest number among 3 numbers*/
#include <stdio.h>

int main()
{
int a,b,c;
int largest;

printf("Enter three numbers (separated by space):");


scanf("%d%d%d",&a,&b,&c);

if(a>b && a>c)


largest=a;
else if(b>a && b>c)
largest=b;
else
largest=c;

printf("Largest number is = %d",largest);

return 0;
}

Using Ternary Operator (? : Operator)


Instead of using if else we can also get the largest number among three number by using Ternary
Operator (? :) Operator in C.

Consider the code snippet


largest = ((a>b && a>c)? a : ((b>a && b>c)? b : c));

Consider the example,

/*using ternary operator (? :) */


#include <stdio.h>

int main()
{
int a,b,c;
int largest;
printf("Enter three numbers (separated by space):");
scanf("%d%d%d",&a,&b,&c);

largest =((a>b && a>c)?a:((b>a && b>c)?b:c));

printf("Largest number is = %d",largest);

printf("Largest number is = %d",largest);


return 0;
}

Output

First Run:
Enter three numbers (separated by space): 10 20 30
Largest number is = 30

Second Run:
Enter three numbers (separated by space):10 30 20
Largest number is = 30

Third Run:
Enter three numbers (separated by space):30 10 20
Largest number is = 30

Fourth Run:
Enter three numbers (separated by space):30 30 30
Largest number is = 30
C program to check whether a person is eligible for
voting or not?
In this program, we are going to learn how to check that, a person is eligible for voting or not, when
age is given or input through the user?

Given age of a person and we have to check whether person is eligible for voting or not.

To check that a person is eligible for voting or not, we need to check whether person’s age is greater
than or equal to 18. For this we are reading age in a variable a and checking the condition a>=18, if the
condition is true, "person will be eligible for voting" else not.

Consider the program:

#include<stdio.h>

int main()
{
int a ;

//input age
printf("Enter the age of the person: ");
scanf("%d",&a);

//check voting eligibility


if (a>=18)
{
printf("Eigibal for voting");
}
else
{
printf("Not eligibal for voting\n");
}

return 0;
}

Output
First run:
Enter the age of the person: 21
Eigibal for voting

Second run:
Enter the age of the person: 15
Not eligibal for voting
C program to read marks and print percentage and
division
In this C program, we are going to read marks in 3 subjects, we will find the total, percentage and
print the division based on the percentage.

Given (or input from the user) marks in 3 subjects and we have to calculate parentage and print the
division.

Formula to get percentage: Total obtained marks *100/Grand total (total of maximum marks)

Division

Based on the percentage, we will print the division, if percentage is:

1. Greater than or equal to 60, division will be "First"


2. Greater than or equal to 50, division will be "Second"
3. Greater than or equal to 40, division will be "Third"
4. Less than it (we will not check any condition, it will be written in else), the result will be fail

Consider the program:

#include<stdio.h>
int main()
{
int science;
int math;
int english;

int total;
float per;

science = 50;
math = 90;
english = 40;
//you can take input from user instead of these values

//calculating total
total= science + math + english;

//calculating percentage
per= (float) total*100/300;

printf("Total Marks: %d\n",total);


printf("Percentage is: %.2f\n",per);

//checking division and printing


if(per>=60)
{
printf("First division\n");
}
else if(per>=50)
{
printf("Second division");
}
else if(per>=40)
{
printf("Third division");
}
else
{
printf("Fail\n");
}

return 0;
}

Output
Total Marks: 180
Percentage is: 60.00
First division
C program to calculate Gross Salary of an employee
This program will read Basic Salary of an employee, calculate other part of the salary on percent basic and
finally print the Gross Salary of the employee.

Here, we are reading basic salary of the employee, and calculating HRA, DA, PF and then Gross salary of
the employee.

C program for Gross Salary


/* c program to calculate salary of an employee with name */
#include <stdio.h>

int main()
{
char name[30];
float basic, hra, da, pf, gross;

printf("Enter name: ");


gets(name);

printf("Enter Basic Salary: ");


scanf("%f",&basic);
printf("Enter HRA: ");
scanf("%f",&hra);
printf("Enter D.A.: ");
scanf("%f",&da);

/*pf automatic calculated 12%*/


pf= (basic*12)/100;

gross=basic+da+hra+pf;

printf("\nName: %s \nBASIC: %f \nHRA: %f \nDA: %f \nPF: %f \n***GROSS


SALARY: %f ***",name,basic,hra,da,pf,gross);

return 0;
}

Output
Enter name: Mike
Enter Basic Salary: 23000
Enter HRA: 9500
Enter D.A.: 9500

Name: Mike
BASIC: 23000.000000
HRA: 9500.000000
DA: 9500.000000
PF: 2760.000000
***GROSS SALARY: 44760.000000 ***
C program to convert temperature from Fahrenheit to
Celsius and Celsius to Fahrenheit.
In this C program, we are going to learn how to convert Fahrenheit to Celsius and Celsius to
Fahrenheit? Here, we are implementing both of the conversations in single program only. Program will
ask for the user to choose which operation, he wants?

In this choice 1 - Program will convert temperature from Fahrenheit to Celsius and choice 2 - program
will convert temperature from Celsius to Fahrenheit.

Temperature conversion program - Fahrenheit to Celsius and


Celsius to Fahrenheit
/* C Program to convert temperature from Fahrenheit to Celsius and vice
versa.*/
#include <stdio.h>

int main()
{

float fh,cl;
int choice;

printf("\n1: Convert temperature from Fahrenheit to Celsius.");


printf("\n2: Convert temperature from Celsius to Fahrenheit.");
printf("\nEnter your choice (1, 2): ");
scanf("%d",&choice);

if(choice ==1){
printf("\nEnter temperature in Fahrenheit: ");
scanf("%f",&fh);
cl= (fh - 32) / 1.8;
printf("Temperature in Celsius: %.2f",cl);
}
else if(choice==2){
printf("\nEnter temperature in Celsius: ");
scanf("%f",&cl);
fh= (cl*1.8)+32;
printf("Temperature in Fahrenheit: %.2f",fh);
}
else{
printf("\nInvalid Choice !!!");
}
return 0;
}

Output
First Run:
1: Convert temperature from Fahrenheit to Celsius.
2: Convert temperature from Celsius to Fahrenheit.
Enter your choice (1, 2): 1

Enter temperature in Fahrenheit: 98.6


Temperature in Celsius: 37.00

Second Run:
1: Convert temperature from Fahrenheit to Celsius.
2: Convert temperature from Celsius to Fahrenheit.
Enter your choice (1, 2): 2

Enter temperature in Celsius: 37.0


Temperature in Fahrenheit: 98.60

Third Run:
1: Convert temperature from Fahrenheit to Celsius.
2: Convert temperature from Celsius to Fahrenheit.
Enter your choice (1, 2): 3

Invalid Choice !!!


C program to calculate X^N (X to the power of N) using pow function.
pow() is used to calculate the power of any base, this library function is defined in math.h header file. In this
program we will read X as the base and N as the power and will calculate the result (X^N - X to the power of
N).

pow() function example/program to calculate X^N in c program

1
2
/*
3 C program to calculate X^N (X to the power of N) using
4 pow function.
5 */
6
7 #include <stdio.h>
8 #include <math.h>
9
int main()
10 {
11 int x,n;
12 int result;
13
14 printf("Enter the value of base: ");
scanf("%d",&x);
15
16 printf("Enter the value of power: ");
17 scanf("%d",&n);
18
19 result =pow((double)x,n);
20
21 printf("%d to the power of %d is= %d", x,n, result);
getch();
22 return 0;
23 }
24
25

Enter the value of base: 3

Enter the value of power: 7

3 to the power of 7 is= 2187


C program to find the difference of two numbers
This program will find the difference of two integer numbers. Difference is quite different from
subtraction, in subtraction we just subtract second number from first number and here to get difference
we will subtract smallest number from largest number, so that we can get correct difference of them.

Difference of two integer numbers program


/*C program to find difference of two numbers.*/

#include <stdio.h>

int main()
{

int a,b;
int diff;

printf("Enter first number: ");


scanf("%d",&a);
printf("Enter second number: ");
scanf("%d",&b);

// check condition to identify which is largest number


if( a>b )
diff=a-b;
else
diff=b-a;

printf("\nDifference between %d and %d is = %d",a,b,diff);


return 0;
}

Output

First Run:
Enter first number: 120
Enter second number: 30

Difference between 120 and 30 is = 90

Second Run:
Enter first number: 30
Enter second number: 120

Difference between 30 and 120 is = 90


Using abs() – A Shortest way to find difference of two numbers
By using abs() function we can get the difference of two integer numbers without comparing
them, abs() is a library function which is declared in stdlib.h – This function returns the absolute value of
given integer.

Consider the example

/*C program to find difference of two numbers using abs().*/

#include <stdio.h>
#include <stdlib.h>

int main()
{

int a,b;
int diff;

printf("Enter first number: ");


scanf("%d",&a);
printf("Enter second number: ");
scanf("%d",&b);

diff=abs(a-b);

printf("\nDifference between %d and %d is = %d",a,b,diff);


return 0;
}

Output

First Run:
Enter first number: 120
Enter second number: 30

Difference between 120 and 30 is = 90

Second Run:
Enter first number: 30
Enter second number: 120

Difference between 30 and 120 is = 90


C program to print size of variables using sizeof() operator.
sizeof() is an operator in c programming language, which is used to get the occupied size by the variable or
value. This program demonstrate the example of sizeof() operator by printing size of different type of
variables.

sizeof() operator example program

1
2 /*C program to print size of variables using sizeof() operator.*/
3
#include <stdio.h>
4
5 int main()
6 {
7
8 char a ='A';
9 int b =120;
10 float c =123.0f;
11 double d =1222.90;
12 char str[] ="Hello";
13
14 printf("\nSize of a: %d",sizeof(a));
15 printf("\nSize of b: %d",sizeof(b));
16 printf("\nSize of c: %d",sizeof(c));
printf("\nSize of d: %d",sizeof(d));
17 printf("\nSize of str: %d",sizeof(str));
18
19 return 0;
20 }
21

Size of a: 1

Size of b: 4

Size of c: 4

Size of d: 8

Size of str: 6
C program to demonstrate example of escape
sequences
This program will demonstrate example of escape sequences, here you will learn how to use escape
sequences to print special characters like new line, tab space, inverted commas etc
in printfstatements.

Most popular Escape Sequences


\\ \
\" "
\' '
\? ?
\a Alert
\b Back space
\n New Line
\t Horizontal tab
\v Vertical tab
\r Carriage return

Escape sequences example program in c


/*C program to demonstrate examples of escape sequences.*/

#include <stdio.h>
int main()
{

printf("Hello\nWorld!"); //use of \n

printf("\nHello\tWorld!"); // use of \t

printf("\n\"Hello World!\""); //use of \"

printf("\nHello\bWorld!"); //use of \b
return 0;
}

Output

Hello
World!
Hello World!
"Hello World!"
HellWorld!
C program to find area and perimeter of circle
This program will read radius of the circle and find the area and perimeter of the circle.

Area of circle is calculated by PI*R2

Perimeter of the circle is calculated by 2*PI*R

Here, "R" is the radius of the circle, in this program we have a macro defined as PI with the value
of PIand variable rad holds the radius entered by the user.

Area and Perimeter of circle program in c


/*C program to find area and perimeter of circle.*/

#include <stdio.h>

#define PI 3.14f

int main()
{
float rad,area, perm;

printf("Enter radius of circle: ");


scanf("%f",&rad);

area=PI*rad*rad;
perm=2*PI*rad;

printf("Area of circle: %f \nPerimeter of circle: %f\n",area,perm);


return 0;
}

Output

Enter radius of circle: 2.34


Area of circle: 17.193384
Perimeter of circle: 14.695200
C program to find area of rectangle
This program will read length and breadth of the rectangle and find area of the rectangle.

Area of rectangle program in c


/*C program to find area of a rectangle.*/

#include <stdio.h>

int main()
{
float l,b,area;

printf("Enter the value of length: ");


scanf("%f",&l);

printf("Enter the value of breadth: ");


scanf("%f",&b);

area=l*b;

printf("Area of rectangle: %f\n",area);

return 0;
}

Output

Enter the value of length: 1.25


Enter the value of breadth: 3.15
Area of rectangle: 3.937500
C program to find HCF (Highest Common Factor) of two numbers.
This program will read two integer numbers and print Highest Common Factor (HCF).

Find HCF (Highest Common Factor) program in c

1
2
3
/*C program to find HCF of two numbers.*/
4 #include <stdio.h>
5
6 //function to find HCF of two numbers
7 int findHcf(int a,int b)
8 {
int temp;
9
10 if(a==0 || b==0)
11 return 0;
12 while(b!=0)
13 {
temp = a%b;
14 a = b;
15 b = temp;
16 }
17 return a;
}
18 int main()
19 {
20 int a,b;
21 int hcf;
22
printf("Enter first number: ");
23 scanf("%d",&a);
24 printf("Enter second number: ");
25 scanf("%d",&b);
26
27 hcf=findHcf(a,b);
28 printf("HCF (Highest Common Factor) of %d,%d is: %d\n",a,b,hcf);
29
return 0;
30 }
31
32
33

Enter first number: 100

Enter second number: 40

HCF (Highest Common Factor) of 100,40 is: 20


C program to multiply two numbers using plus operator.
This program will read two integer numbers and find the multiplication of them using arithmetic plus (+)
operator. We will not use multiplication operator here to multiply the numbers.

Multiplication of two numbers using plus (+) operator

1
2 /*C program to multiply two numbers using plus operator.*/
3
4 #include <stdio.h>
5
6 int main()
7 {
int a,b;
8
int mul,loop;
9
10 printf("Enter first number: ");
11 scanf("%d",&a);
12 printf("Enter second number: ");
13 scanf("%d",&b);
14
mul=0;
15 for(loop=1;loop<=b;loop++){
16 mul += a;
17 }
18 printf("Multiplication of %d and %d is: %d\n",a,b,mul);
return 0;
19 }
20
21

Enter first number: 10

Enter second number: 4

Multiplication of 10 and 4 is: 40


C program to demonstrate example of global and local scope.
This program will demonstrate the example of global and local scope in c programming language. These
scopes are used according to the requirement. Variable and function which are declared in the global scope
can be accessed anywhere in the program, while variable and functions which are declared within the
local scope can be accessed in the same block (scope).

Use of Global and Local Scope (Blocks) in c

1
2
/*C program to demonstrate example global and local scope. */
3
4 #include <stdio.h>
5
6 int a=10; //global variable
7
8 void fun(void);
9
10 int main()
11 {
int a=20; /*local to main*/
12 int b=30; /*local to main*/
13
14 printf("In main() a=%d, b=%d\n",a,b);
15 fun();
16 printf("In main() after calling fun() ~ b=%d\n",b);
return 0;
17 }
18
19 void fun(void)
20 {
21 int b=40; /*local to fun*/
22
printf("In fun() a= %d\n", a);
23 printf("In fun() b= %d\n", b);
24 }
25
26

In main() a=20, b=30

In fun() a= 10

In fun() b= 40

In main() after calling fun() ~ b=30


C program to demonstrate example of floor() and ceil() functions.
This program will demonstrate the example of floor() an ceil() function in c programming language. Both
functions are library functions and declare in math.h header file.

Example of floor() and ceil() functions in c

1
2 /* C program to demonstrate example of floor and ceil functions.*/
3
4 #include <stdio.h>
5 #include <math.h>
6
int main()
7 {
8 float val;
9 float fVal,cVal;
10
11 printf("Enter a float value: ");
scanf("%f",&val);
12
13 fVal=floor(val);
14 cVal =ceil(val);
15 printf("floor value:%f \nceil value:%f\n",fVal,cVal);
16 return 0;
}
17
18

Enter a float value: 123.45

floor value:123.000000

ceil value:124.000000
C - Read Formatted Time Once through Scanf in C Language.

In this code snippet we are going to learn how can we read formatted values through scanf() in c, this example
will demonstrate you to read formatted time in HH:MM:SS format using scanf().

C Code Snippet - Read Formatted Time (in HH:MM:SS format) through Scanf()

1
/*C - Read Formatted Time Once through Scanf in C Language.*/
2
3 #include <stdio.h>
4
5 int main(){
6 int hour,minute,second;
7
8 printf("Enter time (in HH:MM:SS) ");
9 scanf("%02d:%02d:%02d",&hour,&minute,&second);
10
printf("Entered time is %02d:%02d:%02d\n",hour, minute, second);
11
12 return 0;
13 }
14

Enter time (in HH:MM:SS) 12:50:59

Entered time is 12:50:59


C program to define, modify and access a global
variable.
In this c program we are going to tell you how to declare, define, modify and access a global variable
inside main and other functions?

A global function can be accessed and modified anywhere including main() and other user defined
functions. In this program we are declaring a global variable x which is an integer type, initially we are
assigning the variable with the value 100.

Value will be printed into main() then we are modifying the value of x with 200, printing the value and
again modifying the value of x with 300 through the function modify_x() and printing the final value.
Here modify_x() is a user defined function that will modify the value of x (global variable), this function
will take an integer argument and assign the value into x.

C program (Code Snippet) - Define, Modify and Access a Global


Variable
Let’s consider the following example:

#include <stdio.h>
//declaration with initialization
int x=100;
//function to modify value of global variable
void modify_x(int val)
{
x=val;
}
int main()
{
printf("1) Value of x: %d\n",x);
//modifying the value of x
x=200;
printf("2) Value of x: %d\n",x);
//modifying value from function
modify_x(300);
printf("3) Value of x: %d\n",x);
return 0;
}

Output
1) Value of x: 100
2) Value of x: 200
3) Value of x: 300

The values of global variable x are 100, 200 and 300 after each steps, first from initialization, second from
modifying in main() function and third from modifying in modify_x() function.
C program to convert feet to inches.
In this c program we are going to learn how to convert given feet into inches?

Let’s understand what are feet and inches first...

Word Feet is a plural of foot which is a measurement unit of length and inch is also a measurement of unit
length. A foot contains 12 inches.

So the logic to convert feet to inches is quite very simple, we have to just multiply 12 into the given feet
(entered through the user) to get the measurement in inches.

In this example, we will read value of feet from the user and displays converted inches to the standard
output device.

C program (Code Snippet) - Convert Feet to Inches


Let’s consider the following example:

#include<stdio.h>

int main()
{
int feet,inches;

printf("Enter the value of feet: ");


scanf("%d",&feet);

//converting into inches


inches=feet*12;

printf("Total inches will be: %d\n",inches);


return 0;
}

Output
Enter the value of feet: 15
Total inches will be: 180

Using user define function


Here we are going to declare an user define function feet2Inches() this function will take feet as
arguments and returns inches value.

#include<stdio.h>

//function feet2Inches
int feet2Inches(int f)
{
return (f*12);
}

int main()
{
int feet,inches;

printf("Enter the value of feet: ");


scanf("%d",&feet);

//converting into inches


inches=feet2Inches(feet);

printf("Total inches will be: %d\n",inches);


return 0;
}

Output
Enter the value of feet: 15
Total inches will be: 180
C program to Print value in Decimal, Octal, Hexadecimal using printf in C.

This code snippet will print an entered value in Decimal, Octal and Hexadecimal format using printf() function in
C programming language. By using different format specifier we can print the value in specified format.

C Code Snippet - Print value in Decimal, Octal ad Hex using printf()

1
2 /*Printing value in Decimal, Octal, Hexadecimal using printf in C.*/
3
#include <stdio.h>
4
5
int main()
6 {
7 int value=2567;
8
9 printf("Decimal value is: %d\n",value);
10 printf("Octal value is: %o\n",value);
printf("Hexadecimal value is (Alphabet in small letters): %x\n",value);
11 printf("Hexadecimal value is (Alphabet in capital letters): %X\n",value);
12
13 return 0;
14 }
15

Decimal value is: 2567

Octal value is: 5007

Hexadecimal value is (Alphabet in small letters): a07

Hexadecimal value is (Alphabet in capital letters): A07


C program to Print ASCII value of entered character.
IncludeHelp 03 July 2016

In this code snippet we will read a character value and print their ASCII value, ASCII value will be assigned in a
separate integer variable.

C Code Snippet - Print ASCII value of entered character

1
2 /*C - Print ASCII value of entered character.*/
3
#include <stdio.h>
4
5 int main(){
6 char ch;
7 int asciiValue;
8
9 printf("Enter any character: ");
scanf("%c",&ch);
10
11 asciiValue=(int)ch;
12
13 printf("ASCII value of character: %c is: %d\n",ch,asciiValue);
14
15 }
16

Enter any character: x

ASCII value of character: x is: 120


C program to Print How Many Inputs are taken from Keyboard using Scanf
in C Program.

In this code snippet, we will learn how to get total number of inputs taken from scanf() in c program.

Since we know that scanf() returns total number of input using the return value of scanf(), we can count the total
number of inputs. In this program, we are reading multiple numbers and storing them into an integer array, at
every input scanf() is returning the number of inputs and we are adding them into count.

C Code Snippet - Print Number of Inputs taken from Keyboard using Scanf in C
Program

1
2
3 /*C - Print How Many Inputs are Taken from
Keyboard using Scanf in C Progra.*/
4
5 #include <stdio.h>
6
7 int main(){
8 int count=0;
9 int num;
int arr[100],i=0;
10
11 while(num!=-1){
12 printf("Enter an integer number (-1 to exit): ");
13 count+=scanf("%d",&num);
14 arr[i++]=num;
}
15
16 printf("\nTotal Inputs (including 0) are: %d\n",count);
17 printf("Entered numbers are:\n");
18 for(i=0;i<count;i++){
19 printf("%d ",arr[i]);
}
20
21
printf("\n");
22 return 0;
23 }
24
25

Enter an integer number (-1 to exit): 10

Enter an integer number (-1 to exit): 20

Enter an integer number (-1 to exit): 30

Enter an integer number (-1 to exit): 40

Enter an integer number (-1 to exit): -1

Total Inputs (including 0) are: 5

Entered numbers are:

10 20 30 40 -1
C - Calculate Employee and Employer Provident Fund using C Program.
In this code snippet, we will learn how to calculate employee and employer contribution in provident fund (pf)
based on basic pay using c program.

In this program, we define two macros for employee and employee fund contribution percentage and taking
basic pay as input, based on this percentage, program is calculating provident fund (pf) which is deducting from
your salary and employer is contributing.

C Code Snippet - Calculate Employee and Employee Provident Fund Contribution


using C Program

1
2 /*C - Calculate Employee and Employer
3 Provident Fund using C Program.*/
4
5 #include <stdio.h>
6
7 #define EMPLOYEE_PERCENTAGE 12.5f
#define EMPLOYER_PERCENTAGE 12.0f
8
9 int main(){
10 float basicPay;
11 float employeeFund,employerFund;
12
13 printf("Enter basic pay: ");
14 scanf("%f",&basicPay);
15
employeeFund=(basicPay/100)*EMPLOYEE_PERCENTAGE;
16 employerFund=(basicPay/100)*EMPLOYER_PERCENTAGE;
17
18 printf("Basic Pay: %f\n",basicPay);
19 printf("Employee contribution: %f\n",employeeFund);
20 printf("Employer Contribution: %f\n",employerFund);
21
return 0;
22 }
23
24

Enter basic pay: 35000

Basic Pay: 35000.000000

Employee contribution: 4375.000000

Employer Contribution: 4200.000000


C program to Set buffer with specific value using memset in C - Example of
memset().

This code snippet will demonstrate use of memset(), in this code snippet we will learn how to set specific value
using memset() to the buffer.

C Code Snippet – Example of memset()

1
2
3
/*Set buffer with specific value using memset in C - Example of memset()*/
4
5 #include <stdio.h>
6 #include <string.h>
7
8 int main()
9 {
unsigned char buffer[10]={0};
10 int i;
11
12 printf("buffer: %s\n",buffer);
13
14 //set value with space
15 memset(buffer,' ', 9); //last byte should be null
16 printf("buffer (memset with space): %s",buffer); printf(".\n");
17
//set value with 'x'
18 memset(buffer,'x', 9); //last byte should be null
19 printf("buffer (memset with x): %s",buffer); printf(".\n");
20
21 //set value with value 15
22 memset(buffer,15, 9); //last byte should be null
printf("buffer (memset with value 15): %s",buffer); printf(".\n");
23 printf("buffer (memset with value 15 printing integer values:\n*** LAST VALUE WILL BE NULL ***):\
24 for(i=0;i<10;i++){
25 printf("%02d ",buffer[i]);
26 }
printf(".\n");
27
28 return 0;
29 }
30
31
32
buffer:
buffer (memset with space): .
buffer (memset with x): xxxxxxxxx.
buffer (memset with value 15): .
buffer (memset with value 15 printing integer values:
*** LAST VALUE WILL BE NULL ***):
15 15 15 15 15 15 15 15 15 00 .
Write a C program to evaluate the net salary of an
employee given the following constraints
Given the following constrains and we have to calculate net salary of an employee.

Basic salary : $ 12000 Others : $450


DA : 12% of Basic salary Tax cuts – a) PF :14% of Basic salary and b) IT: 15% of Basic salary
HRA : $150 Net Salary = Basic Salary + DA + HRA + TA + Others – (PF + IT)
TA : $120

Consider the program:

#include <stdio.h>

//main program
int main()
{
//variable to store values
float basic, da, hra, ta, others;
float pf,it;
float net_salary;

//input required fields


printf("Enter Basic Salary ($): ");
scanf("%f",&basic);
printf("Enter HRA ($): ");
scanf("%f",&hra);
printf("Enter TA ($): ");
scanf("%f",&ta);
printf("Enter others ($): ");
scanf("%f",&others);

//calculate DA 12% of Basic Salary


da = (basic*12)/100;
//calculate PF 14% of Basic salary
pf = (basic*14)/100;
//calculate IT, 15% of Basic salary
it = (basic*15)/100;

//calculate net salary


net_salary = basic + da + hra + ta + others - (pf+it);

//printing Net salary


printf("Net Salary is: $ %.02f\n",net_salary);

return 0;
}

Output
Enter Basic Salary ($): 12000
Enter HRA ($): 150
Enter TA ($): 120
Enter others ($): 450
Net Salary is: $ 10680.00
How to swap two numbers without using a temporary
variable using C program?
Given two integer numbers "a" and "b" and we have to swap their values without using any
temporary variable.

Example:

Input: a=10, b=20


Output: a=20, b=10

Logic to swap number using temporary variable:


In this program, we are writing code that will swap numbers without using other variable.

To swap numbers:
Step 1) Add the value of a and b and assign the result in a.
a = a+b;
Step 2) To get the swapped value of b: Subtract the value of b from a (which was the sum of a and b).
b = a-b;
Step 3) To get the swapped value of a: Subtract the value of b from a.
a = a-b;

These are the above written three statements to swap two numbers:

//swapping numbers

a = a+b; //step 1

b = a-b; //step 2

a = a-b; //step 3

Let’s understand with the values:

Input: a=10 and b=20

Step1: a = a+b → a= 10+20 → a=30


Now: a=30 and b=20

Step2: b = a-b → a= 30-20 → b=10


Now: a=30 and b=10

Step3: a = a-b → a= 30-10 → a=20


Now: a=20 and b=10

Values are swapped now,


Output: a=20 and b=10
Program to swap numbers without using temporary variable in C
#include <stdio.h>

int main()
{
//variable declarations
int a,b;

//Input values
printf("Enter the value of a: ");
scanf("%d",&a);
printf("Enter the value of b: ");
scanf("%d",&b);

//Numbers before swapping


printf("Before swapping... a: %d, b: %d\n",a,b);

//swapping numbers
a = a+b; //step 1
b = a-b; //step 2
a = a-b; //step 3

//Numbers after swapping


printf("After swapping... a: %d, b: %d\n",a,b);

return 0;
}

Output
First run:
Enter the value of a: 10
Enter the value of b: 20
Before swapping... a: 10, b: 20
After swapping... a: 20, b: 10

Second run:
Enter the value of a: -100
Enter the value of b: -200
Before swapping... a: -100, b: -200
After swapping... a: -200, b: -100

In first run, the input values of a and b are 10 and 20 respectively, after swapping values
of a and b are 20 and 10 (swapped values).

Same as second run, the input values of a and b are -100 and -200 respectively, after swapping values
of a and b are -200 and -100 (swapped values).

Вам также может понравиться