Академический Документы
Профессиональный Документы
Культура Документы
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").
#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
#include <stdio.h>
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.
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.
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
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.
int main()
{
int a,b,sum;
float avg;
sum=a+b;
avg= (float)(a+b)/2;
return 0;
}
Output
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).
#include <stdio.h>
int main()
{
int a,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.
#include <stdio.h>
#include <math.h>
int main()
{
int a,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.
#include <stdio.h>
int main()
{
int a,b;
int diff;
Output
First Run:
Enter first number: 120
Enter second number: 30
Second Run:
Enter first number: 30
Enter second number: 120
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b;
int diff;
diff=abs(a-b);
Output
First Run:
Enter first number: 120
Enter second number: 30
Second Run:
Enter first number: 30
Enter second number: 120
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.
int main()
{
int dividend, divisor;
int quotient, remainder;
quotient= dividend/divisor;
remainder= dividend%divisor;
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.
int main()
{
float amount,rate,time,si;
si=(amount*rate*time)/100;
return 0;
}
Output
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.
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.
int main()
{
int a,b,c;
int largest;
return 0;
}
int main()
{
int a,b,c;
int largest;
printf("Enter three numbers (separated by space):");
scanf("%d%d%d",&a,&b,&c);
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.
#include<stdio.h>
int main()
{
int a ;
//input age
printf("Enter the age of the person: ");
scanf("%d",&a);
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
#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;
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.
int main()
{
char name[30];
float basic, hra, da, pf, gross;
gross=basic+da+hra+pf;
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.
int main()
{
float fh,cl;
int 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
Second Run:
1: Convert temperature from Fahrenheit to Celsius.
2: Convert temperature from Celsius to Fahrenheit.
Enter your choice (1, 2): 2
Third Run:
1: Convert temperature from Fahrenheit to Celsius.
2: Convert temperature from Celsius to Fahrenheit.
Enter your choice (1, 2): 3
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
#include <stdio.h>
int main()
{
int a,b;
int diff;
Output
First Run:
Enter first number: 120
Enter second number: 30
Second Run:
Enter first number: 30
Enter second number: 120
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b;
int diff;
diff=abs(a-b);
Output
First Run:
Enter first number: 120
Enter second number: 30
Second Run:
Enter first number: 30
Enter second number: 120
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.
#include <stdio.h>
int main()
{
printf("Hello\nWorld!"); //use of \n
printf("\nHello\tWorld!"); // use of \t
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.
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.
#include <stdio.h>
#define PI 3.14f
int main()
{
float rad,area, perm;
area=PI*rad*rad;
perm=2*PI*rad;
Output
#include <stdio.h>
int main()
{
float l,b,area;
area=l*b;
return 0;
}
Output
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
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
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 fun() a= 10
In fun() b= 40
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
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
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.
#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?
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.
#include<stdio.h>
int main()
{
int feet,inches;
Output
Enter the value of feet: 15
Total inches will be: 180
#include<stdio.h>
//function feet2Inches
int feet2Inches(int f)
{
return (f*12);
}
int main()
{
int feet,inches;
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.
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
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.
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
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
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.
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
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.
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.
#include <stdio.h>
//main program
int main()
{
//variable to store values
float basic, da, hra, ta, others;
float pf,it;
float 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:
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
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);
//swapping numbers
a = a+b; //step 1
b = a-b; //step 2
a = a-b; //step 3
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).