Sunteți pe pagina 1din 212

KKR & KSR INSTITUTE OF TECHNOLOGY & SCIENCES

(Accredited ‘A’ Grade by NAAC, Approved by AICTE, New Delhi, Affiliated to JNTU Kakinada)

IV YEAR Technical Classes- C Language

SAMPLE PROGRAMS
1. Program to read an integer from User

#include <stdio.h>

Void main()

int number;

printf("Enter an integer: ");

scanf("%d", &number);

printf("You entered: %d", number);

return 0;

Enter a integer: 25

You entered: 25

Explanation : In this program, an integer variable number is declared. The printf() function displays
Enter an integer: on the screen. Then, the scanf() function reads an integer data from the user and stores in
variable number. Finally, the value stored in the variable number is displayed on the screen using printf()
function.

2. Program to Add Two Integers

#include <stdio.h>

Void main()

int firstNumber, secondNumber, sumOfTwoNumbers;

printf("Enter two integers: ");

scanf("%d %d", &firstNumber, &secondNumber);

sumOfTwoNumbers = firstNumber + secondNumber;

printf("%d + %d = %d", firstNumber, secondNumber, sumOfTwoNumbers);


return 0;

Enter two integers: 12

11

12 + 11 = 23

In this program, user is asked to enter two integers. Two integers entered by the user is stored in
variables firstNumber and secondNumber respectively. This is done using scanf()function.

Then, variables firstNumber and secondNumber are added using + operator and the result is stored
in sumOfTwoNumbers.

Finally, the sumofTwoNumbers is displayed on the screen using printf() function.

3. C Program to Multiply two Floating Point Numbers

#include <stdio.h>

int main()

double firstNumber, secondNumber, product;

printf("Enter two numbers: ");

scanf("%lf %lf", &firstNumber, &secondNumber);

product = firstNumber * secondNumber;

printf("Product = %.2lf", product);

return 0;
}

Output :Enter two numbers: 2.4

1.12

Product = 2.69

4. C Program to Swap Two Numbers

#include <stdio.h>

int main()

double firstNumber, secondNumber, temporaryVariable;

printf("Enter first number: ");

scanf("%lf", &firstNumber);

printf("Enter second number: ");

scanf("%lf",&secondNumber);

// Value of firstNumber is assigned to temporaryVariable

temporaryVariable = firstNumber;

// Value of secondNumber is assigned to firstNumber

firstNumber = secondNumber;

// Value of temporaryVariable (which contains the initial value of firstNumber) is assigned to


secondNumber

secondNumber = temporaryVariable;
printf("\nAfter swapping, firstNumber = %.2lf\n", firstNumber);

printf("After swapping, secondNumber = %.2lf", secondNumber);

return 0;

Output

Enter first number: 1.20

Enter second number: 2.45

After swapping, firstNumber = 2.45

After swapping, secondNumber = 1.20

5. C Program to find area and circumference of circle

#include<stdio.h>

int main() {

int rad;

float PI = 3.14, area, ci;

printf("\nEnter radius of circle: ");

scanf("%d", &rad);

area = PI * rad * rad;

printf("\nArea of circle : %f ", area);

ci = 2 * PI * rad;

printf("\nCircumference : %f ", ci);

return (0);

Output :
Enter radius of a circle : 1
Area of circle : 3.14
Circumference : 6.28
1
2
3
Enter radius of a circle : 1
Area of circle : 3.14
Circumference : 6.28

6. C Program to Find Area of Scalene Triangle


#include<stdio.h>
#include<math.h>
int main() {
int s1, s2, angle;
float area;
printf("\nEnter Side1 : ");
scanf("%d", &s1);
printf("\nEnter Side2 : ");
scanf("%d", &s2);
printf("\nEnter included angle : ");
scanf("%d", &angle);
area = (s1 * s2 * sin((M_PI / 180) * angle)) / 2;
printf("\nArea of Scalene Triangle : %f", area);
return (0);
}
1
2
3
4
Enter Side1 : 3
Enter Side2 : 4
Enter included angle : 30
Area of Scalene Triangle : 3.000000
C Program for Beginners : Area of Scalene Triangle

Properties of Scalene Triangle :


1. Scalene Triangle does not have sides having equal length.
2. No angles of Scalene Triangle are equal.
3. To calculate area we need at least two sides and the angle included by them.
Formula to Find Area of Scalene Triangle :

Explanation and Program Logic :


1 sin((M_PI/180)*angle)
• It is Constant defined in math.h Header File
• It contain value = 3.14 in short instead of writing 3.14 write directly M_PI.
Part 2 : ( M_PI / 180 ) * angle
• We are accepting angle in degree.
• C function sin takes argument in radian , so to convert angle into radian we are purposefully
writing above statement.
Part 3 : sin function
• It computes sine of an angle
• #include<stdio.h>
• #include<math.h>
• int main() {
• int side;
• float area, r_4;
• r_4 = sqrt(3) / 4;
• printf("\nEnter the Length of Side : ");
• scanf("%d", &side);
• area = r_4 * side * side;
• printf("\nArea of Equilateral Triangle : %f", area);
• return (0);
• }
Enter the Length of Side : 5
Area of Equilateral Triangle : 10.82
1. Equilateral triangle is a triangle in which all three sides are equal .
2. All angles are of measure 60 degree
3. A three-sided regular polygon
7. Area of Right angle Triangle
include<stdio.h>
int main() {
int base, height;
float area;
printf("\nEnter the base of Right Angle Triangle : ");
scanf("%d", &base);
printf("\nEnter the height of Right Angle Triangle : ");
scanf("%d", &height);
area = 0.5 * base * height;
printf("\nArea of Right Angle Triangle : %f", area);
return (0);
}
Output :
Enter the base of Right Angle Triangle : 4
Enter the height of Right Angle Triangle : 8
Area of Right Angle Triangle : 16.0
8. Program to find the Area of Circle
#include<stdio.h>
int main() {
float radius, area;
printf("\nEnter the radius of Circle : ");
scanf("%d", &radius);
area = 3.14 * radius * radius;
printf("\nArea of Circle : %f", area);
return (0);
}
output
Enter the radius of Circle : 2.0
Area of Circle : 6.14
9. Program to find the Area of Rectangle
#include<stdio.h>
#include<conio.h>
int main() {
int length, breadth, area;
printf("\nEnter the Length of Rectangle : ");
scanf("%d", &length);
printf("\nEnter the Breadth of Rectangle : ");
scanf("%d", &breadth);
area = length * breadth;
printf("\nArea of Rectangle : %d", area);
return (0);
}
Output :
Enter the Length of Rectangle : 5
Enter the Breadth of Rectangle : 4
Area of Rectangle : 20

10. Program to find the Area of Square


#include<stdio.h>
int main() {
int side, area;
printf("\nEnter the Length of Side : ");
scanf("%d", &side);
area = side * side;
printf("\nArea of Square : %d", area);
return (0);
}
Enter the Length of Side : 5
Area of Square : 25

11. Area and Circumference of A Circle


#include<stdio.h>
int main() {
int rad;
float PI = 3.14, area, ci;
printf("\nEnter radius of circle: ");
scanf("%d", &rad);
area = PI * rad * rad;
printf("\nArea of circle : %f ", area);
ci = 2 * PI * rad;
printf("\nCircumference : %f ", ci);
return (0);
}
Output :
Enter radius of a circle : 1
Area of circle : 3.14
Circumference : 6.28

12. 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
switch case Examples/Programs
13. Print weekday name program according to given weekday number using switch

/*C program to read weekday number and print weekday name using switch.*/

#include <stdio.h>

int main()
{
int wDay;

printf("Enter weekday number (0-6): ");


scanf("%d",&wDay);

switch(wDay)
{
case 0:
printf("Sunday");
break;
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
default:
printf("Invalid weekday number.");
}
printf("\n");
return 0;
}

Output

First Run:
Enter weekday number (0-6): 3
Wednesday

Second run:
Enter weekday number (0-6): 9
Invalid weekday number.
14.Print gender (Male/Female) program according to given M/F using switch

/*C program to read gender (M/F) and print corresponding gender using switch.*/
#include <stdio.h>

int main()
{
char gender;

printf("Enter gender (M/m or F/f): ");


scanf("%c",&gender);

switch(gender)
{
case 'M':
case 'm':
printf("Male.");
break;
case 'F':
case 'f':
printf("Female.");
break;
default:
printf("Unspecified Gender.");
}
printf("\n");
return 0;
}

Output

First Run:
Enter gender (M/m or F/f): M
Male.

Second Run:
Enter gender (M/m or F/f): x
Unspecified Gender.

15. Check VOWEL or CONSONANT program using switch

/*C program to check whether a character is VOWEL or CONSONANT using switch.*/

#include <stdio.h>

int main()
{
char ch;

printf("Enter a character: ");


scanf("%c",&ch);
//condition to check character is alphabet or not
if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z'))
{
//check for VOWEL or CONSONANT
switch(ch)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("%c is a VOWEL.\n",ch);
break;
default:
printf("%c is a CONSONANT.\n",ch);
}
}
else
{
printf("%c is not an alphabet.\n",ch);
}

return 0;
}

Output

First Run:
Enter a character: E
E is a VOWEL.

Second Run:
Enter a character: X
X is a CONSONANT.

Third Run:
Enter a character: +
+ is not an alphabet.

16.Calculator program with Basic operations using switch

/*C program to design calculator with basic operations using switch.*/


#include <stdio.h>

int main()
{
int num1,num2;
float result;
char ch; //to store operator choice

printf("Enter first number: ");


scanf("%d",&num1);
printf("Enter second number: ");
scanf("%d",&num2);

printf("Choose operation to perform (+,-,*,/,%): ");


scanf(" %c",&ch);

result=0;
switch(ch)
{
case '+':
result=num1+num2;
break;

case '-':
result=num1-num2;
break;

case '*':
result=num1*num2;
break;

case '/':
result=(float)num1/(float)num2;
break;

case '%':
result=num1%num2;
break;
default:
printf("Invalid operation.\n");
}

printf("Result: %d %c %d = %f\n",num1,ch,num2,result);
return 0;
}

Output

First run:
Enter first number: 10
Enter second number: 20
Choose operation to perform (+,-,*,/,%): +
Result: 10 + 20 = 30.000000

Second run:
Enter first number: 10
Enter second number: 3
Choose operation to perform (+,-,*,/,%): /
Result: 10 / 3 = 3.333333

Third run:
Enter first number: 10
Enter second number: 3
Choose operation to perform (+,-,*,/,%): >
Invalid operation.
Result: 10 > 3 = 0.000000
17.Check EVEN or ODD program using switch

/*C program to check whether number is EVEN or ODD using switch.*/

#include <stdio.h>

int main()
{
int number;

printf("Enter a positive integer number: ");


scanf("%d",&number);

switch(number%2) //this will return either 0 or 1


{
case 0:
printf("%d is an EVEN number.\n",number);
break;
case 1:
printf("%d is an ODD number.\n",number);
break;
}

return 0;
}

Output

First run:
Enter a positive integer number: 10
10 is an EVEN number.

Second run:
Enter a positive integer number: 11
11 is an ODD number.

18.Program to find number of days in a month using C

#include <stdio.h>

int main()
{
int month;
int days;

printf("Enter month: ");


scanf("%d",&month);

switch(month)
{
case 4:
case 6:
case 9:
case 11:
days=30;
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days=31;
break;

case 2:
days=28;
break;

default:
days=0;
break;
}

if(days)
printf("Number of days in %d month is: %d\n",month,days);
else
printf("You have entered an invalid month!!!\n");

return 0;
}

Output

First run:
Enter month: 3
Number of days in 3 month is: 31

Second run:
Enter month: 2
Number of days in 2 month is: 28

Third run:
Enter month: 11
Number of days in 11 month is: 30

Fourth run:
Enter month: 13
You have entered an invalid month!!!

‘goto’ statement solved programs


19.C program to print ASCII values of all digits using goto statement

#include<stdio.h>

int main()
{
//counter, it can also be declared as 'char'
int count;
//initializing counter by 'a'
count= '0';
//definig label
start:
printf("%c [%d] ",count,count);
count++;
//jumping back to 'stat' if condition is true
if(count <= '9')
goto start;
return 0;
}

Output

0 [48] 1 [49] 2 [50] 3 [51] 4 [52] 5 [53] 6 [54] 7 [55] 8 [56] 9 [57]
20.print ASCII values of all lowercase alphabets

Program

#include<stdio.h>

int main()
{
//counter, it can also be declared as 'char'
int count;
//initializing counter by 'a'
count= 'a';
//definig label
start:
printf("%c [%d] ",count,count);
count++;
//jumping back to 'stat' if condition is true
if(count <= 'z')
goto start;
return 0;
}

Output

a [97] b [98] c [99] d [100] e [101] f [102] g [103] h [104]


i [105] j [106] k [107] l [108] m [109] n [110] o [111] p [112]
q [113] r [114] s [115] t [116] u [117] v [118] w [119] x [120]
y [121] z [122]

21.print ASCII values of all uppercase alphabets using goto statement

Program

#include<stdio.h>

int main()
{
//counter, it can also be declared as 'char'
int count;
//initializing counter by 'A'
count= 'A';
//definig label
start:
printf("%c [%d] ",count,count);
count++;
//jumping back to 'stat' if condition is true
if(count <= 'Z')
goto start;
return 0;
}

Output

A [65] B [66] C [67] D [68] E [69] F [70] G [71] H [72]


I [73] J [74] K [75] L [76] M [77] N [78] O [79] P [80]
Q [81] R [82] S [83] T [84] U [85] V [86] W [87] X [88]
Y [89] Z [90]

22. C program to print 1, 11, 31, 61, ... 10 times using goto statement

#include<stdio.h>

int main()
{
int count,a,diff;

count=1; //loop counter


a=1; //series starting number
diff=10;//difference variable initialization

start: //label
printf(" %d ",a);
a=a+diff;
diff=diff+10;
count++;
if(count<=10)
goto start;

return 0;
}

Output

1 11 31 61 101 151 211 281 361 451

23.Program to print Square and Cube of all numbers from 1 to N using goto in C

#include<stdio.h>

int main()
{
int count,n;

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


scanf("%d",&n);

count=1;

start:
printf("num: %4d, Square: %4d, Cube: %4d\n",count,(count*count),(count*count*count));
count++;

if(count<=n)
goto start;

return 0;
}

Output

Enter the value of N: 10


num: 1, Square: 1, Cube: 1
num: 2, Square: 4, Cube: 8
num: 3, Square: 9, Cube: 27
num: 4, Square: 16, Cube: 64
num: 5, Square: 25, Cube: 125
num: 6, Square: 36, Cube: 216
num: 7, Square: 49, Cube: 343
num: 8, Square: 64, Cube: 512
num: 9, Square: 81, Cube: 729
num: 10, Square: 100, Cube: 1000

24. C program to print table of a given number using goto statement

#include<stdio.h>

int main()
{
//declare variable
int count,t,r;

//Read value of t
printf("Enter number: ");
scanf("%d",&t);

count=1;

start:
if(count<=10)
{
//Formula of table
r=t*count;
printf("%d*%d=%d\n",t,count,r);
count++;
goto start;
}

return 0;
}

Output

Enter number: 10
10*1=10
10*2=20
10*3=30
10*4=40
10*5=50
10*6=60
10*7=70
10*8=80
10*9=90
10*10=100

25. C program to print all numbers from N to 1 using goto statement

#include <stdio.h>

int main()
{

int count,n;

//read value of N
printf("Enter value of n: ");
scanf("%d",&n);

//initialize count with N


count =n;

start: //label
printf("%d ",count);
count--;

if(count>=1)
goto start;

return 0;
}
Output

First run:
Enter value of n: 10
10 9 8 7 6 5 4 3 2 1

Second run:
Enter value of n: 100
100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85
84 83 82 81 80 79 78 77 76 75 74 73 72 71 70 69
68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53
52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37
36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20
19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

C programming Looping (while, do while, for) programs


26. C program to read an integer and print its multiplication table

#include <stdio.h>
int main()
{
int num; /*to store number*/
int i; /*loop counter*/

/*Reading the number*/


printf("Enter an integer number: ");
scanf("%d",&num);

/*Initialising loop counter*/


i=1;

/*loop from 1 to 10*/


while(i<=10){
printf("%d\n",(num*i));
i++; /*Increase loop counter*/
}

return 0;
}

Output

Enter an integer number: 12


12
24
36
48
60
72
84
96
108
120
Code using do while loop

/*Initialising loop counter*/


i=1;

/*loop from 1 to 10*/


do{
printf("%d\n",(num*i));
i++; /*Increase loop counter*/
}while(i<=10);

Code using for loop

for(i=1;i<=10;i++){
printf("%d\n",(num*i));
}

27. C program to print table of numbers from 1 to 20

/*C program to print table of numbers from 1 to 20*/

#include <stdio.h>

int main()
{
int i,j; /*Here, we will use i for outer loop counter
and j for inner loop counter*/
int num;

for(i=1; i<=20; i++) /*to print table 1 to 20*/


{
/*each number has 10 multiples*/
num= i; /*to initialize number with i ( 1 to 20)*/
for(j=1; j<=10; j++)
{
/*values will be padded with 3 spaces*/
printf("%3d\t",(num*j));
}

printf("\n"); /*after printing table of each number*/


}
return 0;
}

Output
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
11 22 33 44 55 66 77 88 99 110
12 24 36 48 60 72 84 96 108 120
13 26 39 52 65 78 91 104 117 130
14 28 42 56 70 84 98 112 126 140
15 30 45 60 75 90 105 120 135 150
16 32 48 64 80 96 112 128 144 160
17 34 51 68 85 102 119 136 153 170
18 36 54 72 90 108 126 144 162 180
19 38 57 76 95 114 133 152 171 190
20 40 60 80 100 120 140 160 180 200

28.Check number is Positive, Negative or Zero using C program

1 /* C program to check whether number is


2 POSITIVE, NEGATIVE or ZERO until user doesn’t want to exit.*/
3
4 #include <stdio.h>
5
6 int main()
7 {
8 int num;
9 char choice;
10 do
11 {
12 printf("Enter an integer number :");
13 scanf("%d",&num);
14
15 if(num==0)
16 printf("Number is ZERO.");
17 else if(num>0)
18 printf("Number is POSITIVE.");
19 else
20 printf("Number is NEGATIVE.");
21
22 printf("\n\nWant to check again (press Y/y for 'yes') :");
23 fflush(stdin); /*to clear input buffer*/
24 scanf(" %c",&choice); /*Here is a space before %c*/
25 }while(choice=='Y' || choice=='y');
26
27 printf("\nBye Bye!!!");
28
29 return 0;
30 }

Enter an integer number :0

Number is ZERO.

Want to check again (press Y/y for 'yes') :Y

Enter an integer number :1234

Number is POSITIVE.

Want to check again (press Y/y for 'yes') :Y

Enter an integer number :-345

Number is NEGATIVE.

Want to check again (press Y/y for 'yes') :y

Enter an integer number :45

Number is POSITIVE.

Want to check again (press Y/y for 'yes') :N

Bye Bye!!!
29.Factorial program in C
Simple program - without using User Define Function

/*C program to find factorial of a number.*/

#include <stdio.h>

int main()
{
int num,i;
long int fact;

printf("Enter an integer number: ");


scanf("%d",&num);

/*product of numbers from num to 1*/


fact=1;
for(i=num; i>=1; i--)
fact=fact*i;

printf("\nFactorial of %d is = %ld",num,fact);

return 0;
}

Output

Enter an integer number: 7

Factorial of 7 is = 5040
User Define Function

/*Using Function: C program to find factorial of a number.*/

#include <stdio.h>

/* function : factorial, to find factorial of a given number*/

long int factorial(int n)


{
int i;
long int fact=1;

if(n==1) return fact;

for(i=n;i>=1;i--)
fact= fact * i;

return fact;
}

int main()
{
int num;

printf("Enter an integer number :");


scanf("%d",&num);
printf("\nFactorial of %d is = %ld",num,factorial(num));

return 0;
}

Output

Enter an integer number: 7

Factorial of 7 is = 5040
Using Recursion

//function for factorial


long int factorial(int n)
{
if(n==1) return 1;
return n*factorial(n-1);
}

30. C program to calculate sum of first N natural numbers.

This program will read the value of N and calculate sum from 1 to N, first N natural numbers means
numbers from 1 to N and N will be read through user.

Sum of first N natural numbers using C program


1 /*C program to calculate sum of first N natural numbers.*/

2 #include <stdio.h>

3 int main()

4 {

5 int n,i;

6 int sum;

7 printf("Enter the value of N :");

8 scanf("%d",&n);

9 sum=0;

10 for(i=1;i< n;i++)
11
sum+=i;
12
printf("\nSum is = %d",sum);
13
return 0;
14
}

Enter the value of N :100

Sum is = 4950

31. C program to print all prime numbers from 1 to N.

This program will read the value of N and print all prime numbers from 1 to N. The logic behind
implement this program - Run loop from 1 to N and check each value in another loop, if the value is
divisible by any number between 2 to num-1 (or less than equal to num/2) - Here num is the value to
check it is prime of not.

Print all PRIME numbers from 1 to N using C program


1 /*C program to print all prime numbers from 1 to N.*/

2 #include <stdio.h>

3 int checkPrime(int num){

4 int i;

5 int flg=0;

6 /*if number (num) is divisble by any number from 2 to num/2

7 number will not be prime.*/

8 for(i=2;i<(num-1);i++)

9 {

10 if(num%i==0){
11
flg=1;
12
break;
13
}
14
}
15
if(flg) return 0;
16
else return 1;
17
}
18
Another Code:
19
int main()
20
{
21
int i,n;
22
printf("Enter the value of N: ");
23
scanf("%d",&n);
24
printf("All prime numbers are from 1 to %d:\n",n);
25
for(i=1;i<=n;i++)
26
{
27
if(checkPrime(i))
28
printf("%d,",i);
29
}
30
return 0;
31
}

Enter the value of N: 100

All prime numbers are from 1 to 100:

1,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,
32. C program to check numbers are EVEN or ODD from 1 to N.

This program will read value of N and print all numbers from 1 to N with EVEN and ODD after checking
the numbers whether they are EVEN or ODD.

Print number from 1 to N with EVEN and ODD message


using C program
1 /*C program to check numbers are EVEN or ODD from 1 to N.*/

2 #include <stdio.h>

3 int checkEven(int num){

4 /*if number (num) is divisible by 2, number is even*/

5 if(num%2 == 0)

6 return 1;

7 else

8 return 0;

9 }

10 Another Code:

11 int main()

12 {

13 int i,n;

14 printf("Enter the value of N: ");

15 scanf("%d",&n);

16 for(i=1;i<=n;i++)

17 {

18 if(checkEven(i))

19 printf("%4d [EVEN]\t",i);

20 else

21 printf("%4d [ODD]\t",i);
22
}
23
return 0;
24
}

Enter the value of N: 100

1 [ODD] 2 [EVEN] 3 [ODD] 4 [EVEN] 5 [ODD]

6 [EVEN] 7 [ODD] 8 [EVEN] 9 [ODD] 10 [EVEN]

11 [ODD] 12 [EVEN] 13 [ODD] 14 [EVEN] 15 [ODD]

16 [EVEN] 17 [ODD] 18 [EVEN] 19 [ODD] 20 [EVEN]

21 [ODD] 22 [EVEN] 23 [ODD] 24 [EVEN] 25 [ODD]

26 [EVEN] 27 [ODD] 28 [EVEN] 29 [ODD] 30 [EVEN]

31 [ODD] 32 [EVEN] 33 [ODD] 34 [EVEN] 35 [ODD]

36 [EVEN] 37 [ODD] 38 [EVEN] 39 [ODD] 40 [EVEN]

41 [ODD] 42 [EVEN] 43 [ODD] 44 [EVEN] 45 [ODD]

46 [EVEN] 47 [ODD] 48 [EVEN] 49 [ODD] 50 [EVEN]

51 [ODD] 52 [EVEN] 53 [ODD] 54 [EVEN] 55 [ODD]

56 [EVEN] 57 [ODD] 58 [EVEN] 59 [ODD] 60 [EVEN]

61 [ODD] 62 [EVEN] 63 [ODD] 64 [EVEN] 65 [ODD]

66 [EVEN] 67 [ODD] 68 [EVEN] 69 [ODD] 70 [EVEN]

71 [ODD] 72 [EVEN] 73 [ODD] 74 [EVEN] 75 [ODD]

76 [EVEN] 77 [ODD] 78 [EVEN] 79 [ODD] 80 [EVEN]

81 [ODD] 82 [EVEN] 83 [ODD] 84 [EVEN] 85 [ODD]

86 [EVEN] 87 [ODD] 88 [EVEN] 89 [ODD] 90 [EVEN]

91 [ODD] 92 [EVEN] 93 [ODD] 94 [EVEN] 95 [ODD]


96 [EVEN] 97 [ODD] 98 [EVEN] 99 [ODD] 100 [EVEN]

33. Print all Armstrong Numbers from 1 to N using C program

1 /*C program to print all Armstrong Numbers from 1 to N. */


2
3 #include <stdio.h>
4
5 /*function to check Armstrong Number */
6 int checkArmstrong(int num){
7 int tempNumber,rem,sum;
8 tempNumber=num;
9
10 sum=0;
11 while(tempNumber!=0)
12 {
13 rem=tempNumber%10;
14 sum=sum + (rem*rem*rem);
15 tempNumber/=10;
16 }
17 /* checking number is Armstrong or not */
18 if(sum==num)
19 return 1;
20 else
21 return 0;
22 }
23
24 int main()
25 {
26 int i,n;
27
28 printf("Enter the value of N: ");
29 scanf("%d",&n);
30
31 printf("All Armstrong numbers from 1 to %d:\n",n);
32 for(i=1;i<=n;i++)
33 {
34 if(checkArmstrong(i))
35 printf("%d,",i);
36 }
37
38 return 0;
39 }

Enter the value of N: 1000

All Armstrong numbers from 1 to 1000:

1,153,370,371,407,
34. Print Square, Cube and Square Root using C program

/*C program to print square, cube and square root of all numbers from 1 to N.*/

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

int main()
{
int i,n;

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


scanf("%d",&n);

printf("No Square Cube Square Root\n",n);


for(i=1;i<=n;i++)
{
printf("%d \t %ld \t %ld \t %.2f\n",i,(i*i),(i*i*i),sqrt((double)i));
}

return 0;
}

Output

No Square Cube Square Root


1 1 1 1.00
2 4 8 1.41
3 9 27 1.73
4 16 64 2.00
5 25 125 2.24
6 36 216 2.45
7 49 343 2.65
8 64 512 2.83
9 81 729 3.00
10 100 1000 3.16
35. Print all Leap Years from 1 to N using C program

/*C program to print all leap years from 1 to N.*/

#include <stdio.h>

//function to check leap year


int checkLeapYear(int year)
{
if( (year % 400==0)||(year%4==0 && year%100!=0) )
return 1;
else
return 0;
}

int main()
{
int i,n;

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


scanf("%d",&n);

printf("Leap years from 1 to %d:\n",n);


for(i=1;i<=n;i++)
{
if(checkLeapYear(i))
printf("%d\t",i);
}

return 0;
}

Output

Enter the value of N: 2000


Leap years from 1 to 2000:
4 8 12 16 20 24 28 32 36 40
44 48 52 56 60 64 68 72 76 80
84 88 92 96 104 108 112 116 120 124
128 132 136 140 144 148 152 156 160 164
168 172 176 180 184 188 192 196 204 208
...
1532 1536 1540 1544 1548 1552 1556 1560 1564 1568
1572 1576 1580 1584 1588 1592 1596 1600 1604 1608
1612 1616 1620 1624 1628 1632 1636 1640 1644 1648
1652 1656 1660 1664 1668 1672 1676 1680 1684 1688
1692 1696 1704 1708 1712 1716 1720 1724 1728 1732
1736 1740 1744 1748 1752 1756 1760 1764 1768 1772
1776 1780 1784 1788 1792 1796 1804 1808 1812 1816
1820 1824 1828 1832 1836 1840 1844 1848 1852 1856
1860 1864 1868 1872 1876 1880 1884 1888 1892 1896
1904 1908 1912 1916 1920 1924 1928 1932 1936 1940
1944 1948 1952 1956 1960 1964 1968 1972 1976 1980
1984 1988 1992 1996 2000
36. Print Alphabets in Upper and Lower case using C program

/*C program to print all upper case and lower case alphabets.*/

#include <stdio.h>

int main()
{
char i;

printf("Capital (upper) case characters:\n");


for(i='A'; i<='Z'; i++)
printf("%c ",i);

printf("\n\nLower case characters:\n");


for(i='a'; i<='z'; i++)
printf("%c ",i);

return 0;
}

Output

Capital (upper) case characters:


ABCDEFGHIJKLMNOPQRSTUVWXYZ

Lower case characters:


abcdefghijklmnopqrstuvwxyz
37. C program to read age of 15 person and count total Baby age, School age and Adult age

#include <stdio.h>
int main()
{
int age;
int cnt_baby=0,cnt_school=0,cnt_adult=0;
int count=0;

while(count<15)
{
printf("Enter age of person [%d]: ",count+1);
scanf("%d",&age);

if(age>=0 && age<=5)


cnt_baby++;
else if(age>=6 && age<=17)
cnt_school++;
else
cnt_adult++;

//increase counter
count++;
}

printf("Baby age: %d\n",cnt_baby);


printf("School age: %d\n",cnt_school);
printf("Adult age: %d\n",cnt_adult);
return 0;
}

Output

Enter age of person [1]: 0


Enter age of person [2]: 1
Enter age of person [3]: 2
Enter age of person [4]: 3
Enter age of person [5]: 44
Enter age of person [6]: 55
Enter age of person [7]: 66
Enter age of person [8]: 44
Enter age of person [9]: 12
Enter age of person [10]: 13
Enter age of person [11]: 14
Enter age of person [12]: 55
Enter age of person [13]: 66
Enter age of person [14]: 18
Enter age of person [15]: 19
Baby age: 4
School age: 3
Adult age: 8

C string manipulation programs/examples without using Library Functions

38. C program to print string one by one characters using loop.

As we know a string can be printed using printf("%s",string_variable) but in this program we will print
string one by one character using loop. Here loop is running from 0 (access first character from character
array) to Null (Null is the last character from character array - to terminate the string.)

1 /*C program to print string one by one characters using loop.*/


2
3 #include<stdio.h>
4
5 int main()
6 {
7 char text[100];
8 int i;
9
10 printf("Enter any string: ");
11 gets(text);
12
13 printf("Entered string is: ");
14 for(i=0;text[i]!='\0';i++)
15 {
16 printf("%c",text[i]);
17 }
18 printf("\n");
19 return 0;
20 }
Enter any string: www.includehelp.com
Entered string is: www.includehelp.com

39. C program to print all VOWEL and CONSONANT characters separately.

In this program we will print all VOWEL and CONSONANT characters from entered string separately,
logic behind to implement this program too easy, you have to just check if characters are vowels print
them as vowels and not print them as consonants.

1 /*C program to print all VOWEL and CONSONANT characters separately.*/


2
3 #include<stdio.h>
4
5 int main()
6 {
7 char text[100];
8 int i;
9
10 printf("Enter any string: ");
11 gets(text);
12
13 printf("String is: ");
14 for(i=0;text[i]!='\0';i++)
15 {
16 printf("%c",text[i]);
17 }
18 printf("\n");
19
20 printf("VOWEL Characters are: ");
21 for(i=0;text[i]!='\0';i++)
22 {
23 if(text[i]=='A' || text[i]=='a' || text[i]=='E' || text[i]=='e' || text[i]=='I' || text[i]=='i' || text[i]=='O' || text[i]=='o' || tex
24 printf("%c",text[i]);
25 }
26 printf("\n");
27
28 printf("CONSONANT Characters are: ");
29 for(i=0;text[i]!='\0';i++)
30 {
31 if(!(text[i]=='A' || text[i]=='a' || text[i]=='E' || text[i]=='e' || text[i]=='I' || text[i]=='i' || text[i]=='O' || text[i]=='o' || te
32 printf("%c",text[i]);
33 }
34 printf("\n");
35
36 return 0;
37 }
Enter any string: www.includehelp.com
String is: www.includehelp.com
VOWEL Characters are: iueeo
CONSONANT Characters are: www.ncldhlp.cm

40. C program to count upper case, lower case and special characters in a string.

In this program, we will count upper case, lower case and special characters. Logic behind to implement
this program is too easy, just check characters is alphabet or not, if it is alphabet check for lower and
upper case characters, if characters are not alphabets count them as special characters.

1 /*C program to count upper case, lower case and special characters in a string.*/
2
3 #include<stdio.h>
4
5 int main()
6 {
7 char text[100];
8 int i;
9 int countL,countU,countS;
10
11 printf("Enter any string: ");
12 gets(text);
13
14 //here, we are printing string using printf
15 //without using loop
16 printf("Entered string is: %s\n",text);
17
18 //count lower case, upper case and special characters
19 //assign 0 to counter variables
20 countL=countU=countS=0;
21
22 for(i=0;text[i]!='\0';i++)
23 {
24 //check for alphabet
25 if((text[i]>='A' && text[i]<='Z') || (text[i]>='a' && text[i]<='z'))
26 {
27 if((text[i]>='A' && text[i]<='Z'))
28 {
29 //it is upper case alphabet
30 countU++;
31 }
32 else
33 {
34 //it is lower case character
35 countL++;
36 }
37 }
38 else
39 {
40 //character is not an alphabet
41 countS++; //it is special character
42 }
43 }
44
45 //print values
46 printf("Upper case characters: %d\n",countU);
47 printf("Lower case characters: %d\n",countL);
48 printf("Special characters: %d\n",countS);
49
50 return 0;
51 }
Enter any string: Hello Friends, I am Mike.
Entered string is: Hello Friends, I am Mike.
Upper case characters: 4
Lower case characters: 15
Special characters: 6

41. C program to convert string in upper case and lower case.

In this program, we will convert string in upper case and lower case. First we will read a string and then
convert string in upper case and after printing the string that is converted into upper case, we will convert
it in lower case and print the lower case. Logic behind to implement this program - Just check the
alphabets if they are in upper case add the value 32 [0x20 - hex value] to convert the character into lower
case otherwise subtract 32 [0x20 - hex value] to convert the character into upper case.
Because difference between in the ascii codes of upper case and lower case characters are 32 [0x20 - hex
value].

1 /*C program to convert string in upper case and lower case.*/


2
3 #include<stdio.h>
4
5 int main()
6 {
7 char text[100];
8 int i;
9
10 printf("Enter any string: ");
11 gets(text);
12
13 printf("Entered string is: %s\n",text);
14
15 //convert into upper case
16 for(i=0;text[i]!='\0';i++)
17 {
18 if(text[i]>='a' && text[i]<='z')
19 text[i]=text[i]-0x20;
20 }
21 printf("String in Upper case is: %s\n",text);
22
23 //convert into lower case
24 for(i=0;text[i]!='\0';i++)
25 {
26 if(text[i]>='A' && text[i]<='Z')
27 text[i]=text[i]+0x20;
28 }
29 printf("String in Lower case is: %s\n",text);
30
31 return 0;
32 }
Enter any string: www.IncludeHelp.com
Entered string is: www.IncludeHelp.com
String in Upper case is: WWW.INCLUDEHELP.COM
String in Lower case is: www.includehelp.com

42. C program to toggle case of all characters of string.

In this program, we will toggle all character’s case of string. Logic behind to implement this program is -
Just convert lower case character in upper case and upper case character in lower case but first check that
character is alphabet or not, if it is alphabet then do it.

1 /*C program to toggle case of all characters of string.*/


2
3 #include<stdio.h>
4
5 int main()
6 {
7 char text[100];
8 int i;
9
10 printf("Enter any string: ");
11 gets(text);
12 printf("Entered string is: %s\n",text);
13
14
//convert into upper case
15
for(i=0;text[i]!='\0';i++)
16
{
17
//check character is alphabet or not
18
if((text[i]>='A' && text[i]<='Z')||(text[i]>='a' && text[i]<='z'))
19
{
20
//check for upper case character
21
if(text[i]>='A' && text[i]<='Z')
22
text[i]=text[i]+0x20;
23
else
24
text[i]=text[i]-0x20;
25
}
26
}
27
28
printf("String after toggle case: %s\n",text);
29
30
return 0;
31
}
32
Enter any string: www.IncludeHelp.com
Entered string is: www.IncludeHelp.com
String after toggle case: WWW.iNCLUDEhELP.COM

C solved programs/examples on strings


43.Read N strings and print them with the length program in C language

#include <stdio.h>
#include <string.h>

int main()
{
//Declare Variables
char string[10][30]; //2D array for storing strings
int i, n;

//Get the maximum number of strings


printf("Enter number of strings to input\n");
scanf("%d", &n);

//Read the string from user


printf("Enter Strings one by one: \n");
for(i=0; i< n ; i++) {
scanf("%s",string[i]);
}

//Print the length of each string


printf("The length of each string: \n");
for(i=0; i< n ; i++) {
//Print the string at current index
printf("%s ", string[i]);

//Print the length using `strlen` function


printf("%d\n", strlen(string[i]));
}

//Return to the system


return 0;
}

Output

Enter number of strings to input


3
Enter Strings one by one:
www.google.com
www.includehelp.com
www.duggu.org

The length of each string:


www.google.com 14
www.includehelp.com 19

44. Program to eliminate first character of each word of a string in C

#include <stdio.h>
#define MAX 100

int main()
{
char text[MAX]={0};
int loop,j;

printf("Please input string: ");


scanf("%[^\n]s",text); //read string with spaces

printf("Input string is...\n");


printf("%s\n",text);

for(loop=0; text[loop]!='\0'; loop++)


{
if(loop==0 || (text[loop]==' ' && text[loop+1]!=' '))
{
//shift next characters to the left
for(j=((loop==0)?loop:loop+1); text[j]!='\0'; j++)
text[j]=text[j+1];
}
}

printf("Value of \'text\' after eliminating first character of each word...\n");


printf("%s\n",text);

return 0;
}

Output

Please input string: Hello friends, how are you?


Input string is...
Hello friends, how are you?
Value of 'text' after eliminating first character of each word...
ello riends, ow re ou?
45. Program to eliminate/remove all vowels from an input string in C

#include <stdio.h>
#define MAX 100

//function prototypes

/*
This function will return o if 'ch' is vowel
else it will return 1
*/
char isVowel(char ch);

/*
This function will eliminate/remove all vowels
from a string 'buf'
*/
void eliminateVowels(char *buf);

/*main function definition*/


int main()
{
char str[MAX]={0};

//read string
printf("Enter string: ");
scanf("%[^\n]s",str); //to read string with spaces

//print Original string


printf("Original string: %s\n",str);

//eliminate vowles
eliminateVowels(str);
printf("After eliminating vowels string: %s\n",str);

return 0;
}

//function definitions

char isVowel(char ch)


{
if( ch=='A' || ch=='a' ||
ch=='E' || ch=='e' ||
ch=='I' || ch=='i' ||
ch=='O' || ch=='o' ||
ch=='U' || ch=='u')
return 0;
else
return 1;
}

void eliminateVowels(char *buf)


{
int i=0,j=0;

while(buf[i]!='\0')
{
if(isVowel(buf[i])==0)
{
//shift other character to the left
for(j=i; buf[j]!='\0'; j++)
buf[j]=buf[j+1];
}
else
i++;
}

Output

Enter string: Hi there, how are you?


Original string: Hi there, how are you?
After eliminating vowels string: H thr, hw r y?
46. Program to count length of each word in a string in C

#include <stdio.h>
#define MAX_WORDS 10

int main()
{
char text[100]={0}; // to store string
int cnt[MAX_WORDS]={0}; //to store length of the words
int len=0,i=0,j=0;

//read string
printf("Enter a string: ");
scanf("%[^\n]s",text); //to read string with spaces

while(1)
{
if(text[i]==' ' || text[i]=='\0')
{
//check NULL
if(text[i]=='\0')
{
if(len>0)
{
cnt[j++]=len;
len=0;
}
break; //terminate the loop
}
cnt[j++]=len;
len=0;
}
else
{
len++;
}
i++;
}

printf("Words length:\n");
for(i=0;i<j;i++)
{
printf("%d, ",cnt[i]);
}
printf("\b\b \n"); //to remove last comma

return 0;
}

Output

Enter a string: Hi there how are you?


Words length:
2, 5, 3, 3, 4
47.Program to count length of each word in a string in C
#include <stdio.h>
#define MAX_WORDS 10

int main()
{

char text[100]={0}; // to store string


int cnt[MAX_WORDS]={0}; //to store length of the words
int len=0,i=0,j=0;

//read string
printf("Enter a string: ");
scanf("%[^\n]s",text); //to read string with spaces

while(1)
{
if(text[i]==' ' || text[i]=='\0')
{
//check NULL
if(text[i]=='\0')
{
if(len>0)
{
cnt[j++]=len;
len=0;
}
break; //terminate the loop
}
cnt[j++]=len;
len=0;
}
else
{
len++;
}
i++;
}

printf("Words length:\n");
for(i=0;i<j;i++)
{
printf("%d, ",cnt[i]);
}
printf("\b\b \n"); //to remove last comma

return 0;
}

Output
Enter a string: Hi there how are you?
Words length:
2, 5, 3, 3, 4
48.Program to find occurrence of a character in an input string in C

#include <stdio.h>
#define MAX 100

int main()
{
char str[MAX]={0};
char ch;
int count,i;

//input a string
printf("Enter a string: ");
scanf("%[^\n]s",str); //read string with spaces

getchar(); // get extra character (enter/return key)

//input character to check frequency


printf("Enter a character: ");
ch=getchar();

//calculate frequency of character


count=0;
for(i=0; str[i]!='\0'; i++)
{
if(str[i]==ch)
count++;
}

printf("\'%c\' found %d times in \"%s\"\n",ch,count,str);

return 0;
}

Output

First run
Enter a string: Hello world!
Enter a character: l
'l' found 3 times in "Hello world!"

Second run
Enter a string: Hello world!
Enter a character: x
'x' found 0 times in "Hello world!"
49.Program to capitalize first character of each word in a string in C

#include <stdio.h>
#define MAX 100

int main()
{
char str[MAX]={0};
int i;

//input string
printf("Enter a string: ");
scanf("%[^\n]s",str); //read string with spaces

//capitalize first character of words


for(i=0; str[i]!='\0'; i++)
{
//check first character is lowercase alphabet
if(i==0)
{
if((str[i]>='a' && str[i]<='z'))
str[i]=str[i]-32; //subtract 32 to make it capital
continue; //continue to the loop
}
if(str[i]==' ')//check space
{
//if space is found, check next character
++i;
//check next character is lowercase alphabet
if(str[i]>='a' && str[i]<='z')
{
str[i]=str[i]-32; //subtract 32 to make it capital
continue; //continue to the loop
}
}
else
{
//all other uppercase characters should be in lowercase
if(str[i]>='A' && str[i]<='Z')
str[i]=str[i]+32; //subtract 32 to make it small/lowercase
}
}

printf("Capitalize string is: %s\n",str);

return 0;
}

Output
First run:
Enter a string: HELLO FRIENDS HOW ARE YOU?
Capitalize string is: Hello Friends How Are You?

Second run:
Enter a string: hello friends how are you?
Capitalize string is: Hello Friends How Are You?

Third run:
Enter a string: 10 ways to learn programming.
Capitalize string is: 10 Ways To Learn Programming.
50.Program to create, read and print an array of strings in C

#include <stdio.h>

#define MAX_STRINGS 10
#define STRING_LENGTH 50

int main()
{
//declaration
char strings[MAX_STRINGS][STRING_LENGTH];
int loop,n;

printf("Enter total number of strings: ");


scanf("%d",&n);

printf("Enter strings...\n");
for(loop=0; loop<n; loop++)
{
printf("String [%d] ? ",loop+1);

getchar(); //read & ignore extra character (NULL)


//read string with spaces
scanf("%[^\n]s",strings[loop]);
}

printf("\nStrings are...\n");
for(loop=0; loop<n; loop++)
{
printf("[%2d]: %s\n",loop+1,strings[loop]);
}

return 0;
}

Output

Enter total number of strings: 5


Enter strings...
String [1] ? Hello friends, How are you?
String [2] ? I hope, you all are fine!
String [3] ? By the way, what are you doing?
String [4] ? I hope you're doing good.
String [5] ? Bye Bye!!!

Strings are...
[ 1]: Hello friends, How are you?
[ 2]: I hope, you all are fine!
[ 3]: By the way, what are you doing?
[ 4]: I hope you're doing good.
[ 5]: Bye Bye!!!
51.Program to compare two strings using pointers in C

#include <stdio.h>

//Macro for maximum number of characters in a string


#define MAX 100

int main()
{
//declare string variables
char str1[MAX]={0};
char str2[MAX]={0};

int loop; //loop counter


int flag=1;

//declare & initialize pointer variables


char *pStr1=str1;
char *pStr2=str2;

//read strings
printf("Enter string 1: ");
scanf("%[^\n]s",pStr1);
printf("Enter string 2: ");
getchar(); //read & ignore extra character
scanf("%[^\n]s",pStr2);

//print strings
printf("string1: %s\nstring2: %s\n",pStr1,pStr2);

//comparing strings
for(loop=0; (*(pStr1+loop))!='\0'; loop++)
{
if(*(pStr1+loop) != *(pStr2+loop))
{
flag=0;
break;
}
}

if(flag)
printf("Strings are same.\n");
else
printf("Strings are not same.\n");

return 0;
}

Output

First run:
Enter string 1: IncludeHelp.com
Enter string 2: Include.com
string1: IncludeHelp.com
string2: Include.com
Strings are not same.

Second run:
Enter string 1: includehelp.com
Enter string 2: includehelp.com
string1: includehelp.com
string2: includehelp.com
Strings are same.

52.Program to get the indexes of a particular characters in C

#include <stdio.h>

int main()
{
char str[30],ch;
int ind[10],loop,j;

printf("Enter string: ");


scanf("%[^\n]s",str);

printf("Enter character: ");


getchar();
ch=getchar();

j=0;
for(loop=0; str[loop]!='\0'; loop++)
{
if(str[loop]==ch)
ind[j++]=loop;
}
printf("Input string is: %s\n",str);
printf("Indexes: ");
for(loop=0; loop<j; loop++)
printf("%d \t",ind[loop]);

return 0;
}

Output

Enter string: Hi there, how are you?


Enter character: o
Input string is: Hi there, how are you?
Indexes: 11 19

Bitwise Operators

53.Binary from Decimal (Integer) number using C program

#include <stdio.h>

/*function declaration
* name : getBinary
* Desc : to get binary value of decimal number
* Parameter : int -integer number
* return : void
*/
void getBinary(int);

int main()
{
int num=0;
printf("Enter an integer number :");
scanf("%d",&num);
printf("\nBinary value of %d is =",num);
getBinary(num);
return 0;
}

/*Function definition : getBinary()*/


void getBinary(int n)
{
int loop;
/*loop=15 , for 16 bits value, 15th bit to 0th bit*/
for(loop=15; loop>=0; loop--)
{
if( (1 << loop) & n)
printf("1");
else
printf("0");
}
}

Output

Enter an integer number :13


Binary value of 13 is =0000000000001101
54.Swapping two bits of a byte using C program

/*C program to swap two bits of a byte.*/

#include <stdio.h>

int main()
{
unsigned char data=0x0A;

// swaping 1st bit to 2nd bit (bit counting 7-0).


// binary of 0x0A is : 0000 1010

data^=(1<<1);
data^=(1<<2);

// data will be : 0000 1100 (0x0C)


printf("\ndata after swap bits : %02X",data);

return 0;
}

Output

data after swap bits : 0C

55. Example of Left Shift (<<) Operator in C program

1 /* C Program to demonstrate example of left shift (<<) operator.*/


2 #include <stdio.h>
3
4 int main()
5 {
6
7 unsigned int num= 0xff;
8
9 printf("\nValue of num = %04X before left shift.",num);
10
11 /*shifting 2 bytes left*/
12 num = (num<<2);
13 printf("\nValue of num = %04X after left shift.",num);
14
15 return 0;
16 }

Value of num = 00FF before left shift.

Value of num = 03FC after left shift.

56. Example of Right Shift (>>) Operator in C program

1
/* C Program to demonstrate example right shift (>>) operator.*/
2
#include <stdio.h>
3
4
int main()
5
{
6
7
unsigned int num= 0xff;
8
9
printf("\nValue of num = %04X before right shift.",num);
10
11
/*shifting 2 bytes right*/
12
num = (num>>2);
13
printf("\nValue of num = %04X after right shift.",num);
14
return 0;
15
}
16

Value of num = 00FF before right shift.

Value of num = 003F after right shift.

57. Swap two numbers using Bitwise XOR Operator in C

1 /*C program to swap two numbers using bitwise operator.*/


2
3 #include <stdio.h>
4 void swap(int *a, int *b); //function declaration
5
6 int main()
7 {
8 int a,b;
9
10 printf("Enter first number: ");
11 scanf("%d",&a);
12 printf("Enter second number: ");
13 scanf("%d",&b);
14
15 printf("Before swapping: a=%d, b=%d\n",a,b);
16 swap(&a,&b);
17 printf("After swapping: a=%d, b=%d\n",a,b);
18
19 return 0;
20 }
21
22 //function definition
23 void swap(int *a,int *b)
24 {
25 *a = *a ^ *b;
26 *b = *a ^ *b;
27 *a = *a ^ *b;
28 }

Enter first number: 10

Enter second number: 20

Before swapping: a=10, b=20

After swapping: a=20, b=10


58. C example to calculate string length

#include <stdio.h>

/*function to return length of the string*/


int stringLength(char*);

int main()
{
char str[100]={0};
int length;

printf("Enter any string: ");


scanf("%s",str);

/*call the function*/


length=stringLength(str);

printf("String length is : %d\n",length);

return 0;
}

/*function definition...*/
int stringLength(char* txt)
{
int i=0,count=0;
while(txt[i++]!='\0'){
count+=1;
}

return count;
}

Output

Enter any string: IncludeHelp


String length is : 11
59. C program to get substring from a string

#include <stdio.h>

/*Function declaration*/
int getSubString(char *source, char *target,int from, int to);

int main()
{
char text [100]={0};
char text1[50] ={0};
int from,to;

printf("Enter a string: ");


fgets(text,100,stdin);

printf("Enter from index: ");


scanf("%d",&from);
printf("Enter to index: ");
scanf("%d",&to);

printf("String is: %s\n",text);

if(getSubString(text,text1,from,to)==0)
printf("Substring is: %s\n",text1);
else
printf("Function execution failed!!!\n");

return 0;
}

/*Function definition*/
int getSubString(char *source, char *target,int from, int to)
{
int length=0;
int i=0,j=0;

//get length
while(source[i++]!='\0')
length++;

if(from<0 || from>length){
printf("Invalid \'from\' index\n");
return 1;
}
if(to>length){
printf("Invalid \'to\' index\n");
return 1;
}

for(i=from,j=0;i<=to;i++,j++){
target[j]=source[i];
}

//assign NULL at the end of string


target[j]='\0';

return 0;
}

Output

First run:

Enter a string: This is IncludeHelp


Enter from index: 5
Enter to index: 12
String is: This is IncludeHelp
Substring is: is Inclu

Second run:
Enter a string: This is IncludeHelp
Enter from index: 5
Enter to index: 50
String is: This is IncludeHelp
Invalid 'to' index
Function execution failed!!!
60. program to copy one string to another (implementation of strcpy) in C

#include <stdio.h>

/********************************************************
* function name :stringCpy
* Parameter :s1,s2 : string
* Description : copies string s2 into s1
********************************************************/
void stringCpy(char* s1,char* s2);
int main()
{
char str1[100],str2[100];

printf("Enter string 1: ");


scanf("%[^\n]s",str1);//read string with spaces

stringCpy(str2,str1);

printf("String 1: %s \nString 2: %s\n",str1,str2);


return 0;
}

/******** function definition *******/


void stringCpy(char* s1,char* s2)
{
int i=0;
while(s2[i]!='\0')
{
s1[i]=s2[i];
i++;
}
s1[i]='\0'; /*string terminates by NULL*/
}

Output

Enter string 1: Help in Programming


String 1: Help in Programming
String 2: Help in Programming
61. Program to convert string into lowercase and uppercase without using library function in C

#include <stdio.h>

/********************************************************
* function name :stringLwr, stringUpr
* Parameter :character pointer s
* Description
stringLwr - converts string into lower case
stringUpr - converts string into upper case
********************************************************/
void stringLwr(char *s);
void stringUpr(char *s);

int main()
{
char str[100];
printf("Enter any string : ");
scanf("%[^\n]s",str);//read string with spaces

stringLwr(str);
printf("String after stringLwr : %s\n",str);

stringUpr(str);
printf("String after stringUpr : %s\n",str);
return 0;
}

/******** function definition *******/


void stringLwr(char *s)
{
int i=0;
while(s[i]!='\0')
{
if(s[i]>='A' && s[i]<='Z'){
s[i]=s[i]+32;
}
++i;
}
}

void stringUpr(char *s)


{
int i=0;
while(s[i]!='\0')
{
if(s[i]>='a' && s[i]<='z'){
s[i]=s[i]-32;
}
++i;
}
}

Output

Enter any string : Hello friends, How are you?


String after stringLwr : hello friends, how are you?
String after stringUpr : HELLO FRIENDS, HOW ARE YOU?
62. Program to check substring in a string in C

#include <stdio.h>
#include <string.h>

//function declaration
int myStrStr(char * str, char * sub);
int main()
{
char str[100] ={0};
char strTocheck[10] ={0};

printf("Enter complete string: ");


scanf("%[^\n]s",str);
getchar();

printf("Enter string to check: ");


scanf("%[^\n]s",strTocheck);

if(myStrStr(str,strTocheck))
printf("String \"%s\" found in \"%s\"\n",strTocheck,str);
else
printf("String \"%s\" not found in \"%s\"\n",strTocheck,str);

return 0;
}

//function definition
int myStrStr(char * str, char * sub)
{
int flag = 0;

int i=0,len1=0,len2=0;

len1 = strlen(str);
len2 = strlen(sub);

while(str[i] != '\0')
{
if(str[i] == sub[0])
{
if((i+len2)>len1)
break;

if(strncmp(str+i,sub,len2)==0)
{
flag = 1;
break;
}
}
i++;
}

return flag;
}
Output

First run:
Enter complete string: Hello how are you?
Enter string to check: how
String "how" found in "Hello how are you?"

Second run:
Enter complete string: Hello how are you?
Enter string to check: we
String "we" not found in "Hello how are you?"

Third run:
Enter complete string: Hello how are you?
Enter string to check: how are you?
String "how are you?" found in "Hello how are you?"
63. Program to compare two strings without using library function in C

#include <stdio.h>
#include <ctype.h>

/********************************************************
* function name :stringCmp, stringCmpi
* Parameter :char* s1,char* s2
* Return :0- success, 1- fail
* Description
stringCmp - compares two strings
stringCmpi - compares two string (ignoring case)
********************************************************/
int stringCmp (char *s1,char *s2);
int stringCmpi(char *s1,char *s2);

int main()
{
char str1[100],str2[100];

printf("Enter string 1 : ");


scanf("%[^\n]s",str1);//read string with spaces

getchar(); //to read enter after first string

printf("Enter string 2 : ");


scanf("%[^\n]s",str2);//read string with spaces

if(!stringCmp(str1,str2))
printf("\n stringCmp :String are same.");
else
printf("\n stringCmp :String are not same.");
if(!stringCmpi(str1,str2))
printf("\n stringCmpi :String are same.");
else
printf("\n stringCmpi :String are not same.");

printf("\n");
return 0;
}

/******** function definition *******/


int stringCmp (char *s1,char *s2)
{
int i=0;
for(i=0; s1[i]!='\0'; i++)
{
if(s1[i]!=s2[i])
return 1;
}
return 0;
}

/******** function definition *******/


int stringCmpi (char *s1,char *s2)
{
int i=0,diff=0;
for(i=0; s1[i]!='\0'; i++)
{
if( toupper(s1[i])!=toupper(s2[i]) )
return 1;
}
return 0;
}

Output

Enter string 1 : includehelp


Enter string 2 : IncludeHelp

stringCmp :String are not same.


stringCmpi :String are same.
64. Program to concatenate/add two strings without using library function in C

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100

/********************************************************
* function name :stringCat
* Parameter :char* s1,char* s2
* Return :void
* Description :Concatenate two strings
********************************************************/
void stringCat (char *s1,char *s2);

int main()
{
char str1[MAX_SIZE],str2[MAX_SIZE];

printf("Enter string 1 : ");


scanf("%[^\n]s",str1);//read string with spaces

getchar();//read enter after entering first string

printf("Enter string 2 : ");


scanf("%[^\n]s",str2);//read string with spaces

stringCat(str1,str2);
printf("\nAfter concatenate strings are :\n");
printf("String 1: %s \nString 2: %s",str1,str2);

printf("\n");
return 0;
}

/******** function definition *******/


void stringCat (char *s1,char *s2)
{
int len,i;
len=strlen(s1)+strlen(s2);
if(len>MAX_SIZE)
{
printf("\nCan not Concatenate !!!");
return;
}

len=strlen(s1);
for(i=0;i< strlen(s2); i++)
{
s1[len+i]=s2[i];
}
s1[len+i]='\0'; /* terminates by NULL*/
}

Output

Enter string 1 : Hello


Enter string 2 : Friends

After concatenate strings are :


String 1: HelloFriends
String 2: Friends
65. C program to reverse a string without using library function

In this program, we will learn how to reverse a string without using library function?

Here, we are declaring two strings (character arrays), first string will store the input string and other will
store the reversed string.

#include <stdio.h>
#include <string.h>

int main()
{
char str[100],revStr[100];
int i,j;

printf("Enter a string: ");


scanf("%[^\n]s",str);//read string with spaces

/*copy characters from last index of str and


store it from starting in revStr*/
j=0;
for(i=(strlen(str)-1); i>=0;i--)
revStr[j++]=str[i];

//assign NULL in the revStr


revStr[j]='\0';

printf("\nOriginal String is: %s",str);


printf("\nReversed String is: %s",revStr);

return 0;
}

Output

Enter a string: This is a test string


Original String is: This is a test string
Reversed String is: gnirts tset a si sihT

66. C program to split string by space into words.


1 /*C program to split string by space into words.*/
2 #include <stdio.h>
3 #include <string.h>
4
5 int main()
6 {
7 char str[100];
8 char splitStrings[10][10]; //can store 10 words of 10 characters
9 int i,j,cnt;
10
11 printf("Enter a string: ");
12 gets(str);
13
14 j=0; cnt=0;
15 for(i=0;i<=(strlen(str));i++)
16 {
17 // if space or NULL found, assign NULL into splitStrings[cnt]
18 if(str[i]==' '||str[i]=='\0')
19 {
20 splitStrings[cnt][j]='\0';
21 cnt++; //for next word
22 j=0; //for next word, init index to 0
23 }
24 else
25 {
26 splitStrings[cnt][j]=str[i];
27 j++;
28 }
29 }
30 printf("\nOriginal String is: %s",str);
31 printf("\nStrings (words) after split by space:\n");
32 for(i=0;i < cnt;i++)
33 printf("%s\n",splitStrings[i]);
34 return 0;
35 }

Enter a string: Hello Guys This is a test string.

Original String is: Hello Guys This is a test string.

Strings (words) after split by space:

Hello

Guys

This

is

test
string.

67. C program to toggle each character in a string.


1 /*C program to toggle each character in a string.*/
2 #include <stdio.h>
3
4 int main()
5 {
6 char str[100];
7 int counter;
8
9 printf("Enter a string: ");
10 gets(str);
11
12 // toggle each string characters
13 for(counter=0;str[counter]!=NULL;counter++)
14 {
15 if(str[counter]>='A' && str[counter]<='Z')
16 str[counter]=str[counter]+32; //convert into lower case
17 else if(str[counter]>='a' && str[counter]<='z')
18 str[counter]=str[counter]-32; //convert into upper case
19 }
20
21 printf("String after toggle each characters: %s",str);
22 return 0;
23 }

Enter a string: This is a Test String.

String after toggle each characters: tHIS IS A tEST sTRING.

68. C program to count upper case and lower case characters in a string.
1 /*C program to count upper case and lower case characters in a string.*/
2 #include <stdio.h>
3
4 int main()
5 {
6 char str[100];
7 int countL,countU;
8 int counter;
9
10 //assign all counters to zero
11 countL=countU=0;
12
13 printf("Enter a string: ");
14 gets(str);
15
16 for(counter=0;str[counter]!=NULL;counter++){
17
18 if(str[counter]>='A' && str[counter]<='Z')
19 countU++;
20 else if(str[counter]>='a' && str[counter]<='z')
21 countL++;
22 }
23
24 printf("Total Upper case characters: %d, Lower Case characters: %d",countU,countL);
25
26 return 0;
27 }

Enter a string: This is a Test String.

Total Upper case characters: 3, Lower Case characters: 14

69. C program to count digits, spaces, special characters, alphabets in a string

In this C program, we are going to learn how to count digits, spaces, special characters and alphabets?.

Given a string and we have to count digits, spaces, special characters and alphabets using C program.

/*C program to count digits, spaces, special characters, alphabets in a string.*/


#include <stdio.h>

int main()
{
char str[100];
int countDigits,countAlphabet,countSpecialChar,countSpaces;
int counter;

//assign all counters to zero


countDigits=countAlphabet=countSpecialChar=countSpaces=0;

printf("Enter a string: ");


gets(str);

for(counter=0;str[counter]!=NULL;counter++)
{

if(str[counter]>='0' && str[counter]<='9')


countDigits++;
else if((str[counter]>='A' && str[counter]<='Z')||(str[counter]>='a' && str[counter]<='z'))
countAlphabet++;
else if(str[counter]==' ')
countSpaces++;
else
countSpecialChar++;
}
printf("\nDigits: %d \nAlphabets: %d \nSpaces: %d \nSpecial Characters:
%d",countDigits,countAlphabet,countSpaces,countSpecialChar);

return 0;
}

Output

Enter a string: This is test string, 123 @#% 98.

Digits: 5
Alphabets: 16
Spaces: 6
Special Characters: 5
70. Decimal to Binary Conversion using C program

/*C program to convert number from decimal to binary*/

#include <stdio.h>

int main()
{
int number,cnt,i;
int bin[32];

printf("Enter decimal number: ");


scanf("%d",&number);

cnt=0; /*initialize index to zero*/


while(number>0)
{
bin[cnt]=number%2;
number=number/2;
cnt++;
}

/*print value in reverse order*/


printf("Binary value is: ");
for(i=(cnt-1); i>=0;i--)
printf("%d",bin[i]);

return 0;
}

Output

Enter decimal number: 545


Binary value is: 1000100001
71. Decimal to Octal Conversion using C program

1 /*C program to convert number from decimal to octal*/


2
3 #include <stdio.h>
4
5 int main()
6 {
7 int number,cnt,i;
8 int oct[32];
9
10 printf("Enter decimal number: ");
11 scanf("%d",&number);
12
13
14 cnt=0; /*initialize index to zero*/
15 while(number>0)
16 {
17 oct[cnt]=number%8;
18 number=number/8;
19 cnt++;
20 }
21
22 /*print value in reverse order*/
23 printf("Octal value is: ");
24 for(i=(cnt-1); i>=0;i--)
25 printf("%d",oct[i]);
26
27 return 0;
28 }

Enter decimal number: 545

Octal value is: 1041

72.Decimal to Hexadecimal Conversion using C program

1 /*C program to convert number from decimal to hexadecimal*/


2
3 #include <stdio.h>
4
5 int main()
6 {
7 int number,cnt,i;
8 char hex[32]; /*bcoz it contains characters A to F*/
9
10 printf("Enter decimal number: ");
11 scanf("%d",&number);
12
13
14 cnt=0; /*initialize index to zero*/
15 while(number>0)
16 {
17 switch(number%16)
18 {
19 case 10:
20 hex[cnt]='A'; break;
21 case 11:
22 hex[cnt]='B'; break;
23 case 12:
24 hex[cnt]='C'; break;
25 case 13:
26 hex[cnt]='D'; break;
27 case 14:
28 hex[cnt]='E'; break;
29 case 15:
30 hex[cnt]='F'; break;
31 default:
32 hex[cnt]=(number%16)+0x30; /*converted into char value*/
33 }
34 number=number/16;
35 cnt++;
36 }
37
38 /*print value in reverse order*/
39 printf("Hexadecimal value is: ");
40 for(i=(cnt-1); i>=0;i--)
41 printf("%c",hex[i]);
42
43 return 0;
44 }

First Run:

Enter decimal number: 545

Octal value is: 221

Second Run:

Enter decimal number: 2806

Hexadecimal value is: AF6

73. Binary to Decimal Conversion using C program


1 /*C program to convert number from binary to decimal*/
2
3 #include <stdio.h>
4 #include <string.h>
5 #include <math.h>
6
7 int main()
8 {
9 char bin[32]={0};
10 int dec,i;
11 int cnt; /*for power index*/
12
13 printf("Enter binary value: ");
14 gets(bin);
15
16 cnt=0;
17 dec=0;
18 for(i=(strlen(bin)-1);i>=0;i--)
19 {
20 dec=dec+(bin[i]-0x30)*pow((double)2,(double)cnt);
21 cnt++;
22 }
23
24 printf("DECIMAL value is: %d",dec);
25
26 return 0;
27 }

Enter binary value: 1000100001

DECIMAL value is: 545

74. Octal to Decimal Conversion using C program

1 /*C program to convert number from octal to decimal*/


2
3 #include <stdio.h>
4 #include <string.h>
5 #include <math.h>
6
7 int main()
8 {
9 char oct[32]={0};
10 int dec,i;
11 int cnt; /*for power index*/
12
13 printf("Enter octal value: ");
14 gets(oct);
15
16 cnt=0;
17 dec=0;
18 for(i=(strlen(oct)-1);i>=0;i--)
19 {
20 dec= dec+ (oct[i]-0x30)*pow((double)8,(double)cnt);
21 cnt++;
22 }
23
24 printf("DECIMAL value is: %d",dec);
25
26 return 0;
27 }

Enter octal value: 1041

DECIMAL value is: 545

75.Hexadecimal to Decimal Conversion using C program

1 /*program to convert number from hexadecimal to decimal*/


2
3 #include <stdio.h>
4 #include <string.h>
5 #include <math.h>
6
7 int main()
8 {
9 char hex[32]={0};
10 int dec,i;
11 int cnt; /*for power index*/
12 int dig; /*to store digit*/
13
14 printf("Enter hex value: ");
15 gets(hex);
16
17 cnt=0;
18 dec=0;
19 for(i=(strlen(hex)-1);i>=0;i--)
20 {
21 switch(hex[i])
22 {
23 case 'A':
24 dig=10; break;
25 case 'B':
26 dig=11; break;
27 case 'C':
28 dig=12; break;
29 case 'D':
30 dig=13; break;
31 case 'E':
32 dig=14; break;
33 case 'F':
34 dig=15; break;
35 default:
36 dig=hex[i]-0x30;
37 }
38 dec= dec+ (dig)*pow((double)16,(double)cnt);
39 cnt++;
40 }
41
42 printf("DECIMAL value is: %d",dec);
43 return 0;
44 }

Enter hex value: AF6

DECIMAL value is: 2806

76. Reverse Number program in C


1 /* program to reverse an integer number.*/

2 #include <stdio.h>

3 int main()

4 {

5 int n;

6 int dig, revNumber;

7 printf("\nEnter an integer number :");

8 scanf("%d",&n);

9 /*Reversing Number*/

10 revNumber=0;

11 while(n>0)

12 {
13

14 dig=n%10; /*get digit*/

15 revNumber=(revNumber*10)+dig;

16 n=n/10;

17 }

18 printf("\nReverse Number is : %d\n",revNumber);

19 return 0;

20 }

Using User Define Function


1 /* program to reverse an integer number.*/

3 #include <stdio.h>

5 /* function: reverseNum

6 to reverse an integer number.

7 */

9 int reverseNum(int num)

10 {

11 int sum=0,rem;

12 while(num > 0)

13 {

14 rem=num%10;

15 sum=(sum*10)+rem;

16 num=num/10;
17 }

18

19 return sum;

20 }

21

22 int main()

23 {

24 int n;

25 printf("\nEnter an integer number :");

26 scanf("%d",&n);

27

28 printf("\nReverse Number is : %d\n",reverseNum(n));

29 return 0;

30 }

Enter an integer number :1234

Reverse Number is : 4321

77. Sum and Product of all digits of a Number using C program

/* program to find sum and product of all digits of a number.*/

#include <stdio.h>

int main()
{
int n;
int dig, sum,pro;

printf("\nEnter an integer number :");


scanf("%d",&n);

/*Calculating Sum and Product*/


sum=0;
pro=1;

while(n>0)
{
dig=n%10; /*get digit*/
sum+=dig;
pro*=dig;
n=n/10;
}

printf("\nSUM of all Digits is : %d",sum);


printf("\nPRODUCT of all digits: %d",pro);

return 0;
}

Using User Define Function

/* program to find sum and product of all digits of a number.*/

#include <stdio.h>

/* function: sumDigits
to calculate sum of all digits.
*/

int sumDigits(int num)


{
int sum=0,rem;
while(num > 0)
{
rem=num%10;
sum+=rem;
num=num/10;
}

return sum;
}

/* function: proDigits
to calculate product of all digits.
*/

int proDigits(int num)


{
int pro=1,rem;
while(num > 0)
{
rem=num%10;
pro*=rem;
num=num/10;
}

return pro;

}
int main()
{
int n;
printf("\nEnter an integer number :");
scanf("%d",&n);

printf("\nSUM of all Digits is : %d",sumDigits(n));


printf("\nPRODUCT of all digits: %d",proDigits(n));
return 0;
}

Output

Enter an integer number :1234


SUM of all Digits is : 10
PRODUCT of all digits: 24

78. Check Prime Number using C program


1 /*Program to check entered number is whether prime or not.*/

2 #include <stdio.h>

3 int main()

4 {

5 int tally;

6 int number;

7 unsigned char flag=0;

8 printf("Enter an integer number : ");

9 scanf("%d",&number);

10 for(tally=2; tally<(number/2); tally++)

11 {

12 if(number%tally ==0)
13
{
14
flag=1;
15
break;
16
}
17
}
18
if(flag==0)
19
printf("\n %d is a prime number.",number);
20
else
21
printf("\n %d is not a prime number.",number);
22

23
return 0;
24
}

Using User Define Function


1 /*Program to check entered number is whether prime or not.*/

3 #include <stdio.h>

5 /*function to check number is Prime or Not*/

6 int isPrime(int num)

7 {

8 unsigned char flag=0;

9 int tally;

10

11 for(tally=2; tally<(num/2); tally++)

12 {
13 if(num%tally ==0)

14 {

15 flag=1;

16 break;

17 }

18 }

19

20 if(flag==0)

21 return 1; /*prime number*/

22 else

23 return 0; /*not a prime number*/

24 }

25

26 int main()

27 {

28 int number;

29

30 printf("Enter an integer number : ");

31 scanf("%d",&number);

32

33

34 if(isPrime(number))

35 printf("\n %d is a prime number.",number);

36 else

37 printf("\n %d is not a prime number.",number);

38
39 return 0;

40 }

First run:

Enter an integer number: 117

117 is not a prime number.

Second run:

Enter an integer number: 112

112 is not a prime number.

79. Check Palindrome Number using C program


1 /* C program to check whether a number is palindrome or not */

2 #include <stdio.h>

3 int main()

4 {

5 int number, revNumber=0, rem=0,tempNumber;

6 printf("Enter an integer number: ");

7 scanf("%d", &number);

8 tempNumber=number;

9 while(tempNumber!=0)

10 {

11 rem=tempNumber%10;
12
revNumber=revNumber*10+rem;
13
tempNumber/=10;
14
}
15
/* checking if number is equal to reverse number */
16
if(revNumber==number)
17
printf("%d is a palindrome.", number);
18
else
19
printf("%d is not a palindrome.", number);
20

21
return 0;
22
}

Using User Define Function


1 /* C program to check whether a number is palindrome or not */

3 #include <stdio.h>

5 /*function to check Palindrome Number*/

6 int isPalindrome(int num)

7 {

8 int tempNumber=num;

9 int dig,revNumber;

10

11 /*getting reverse number*/

12 revNumber=0;

13 while(num>0)
14 {

15 dig=num%10;

16 revNumber=(revNumber*10)+dig;

17 num/=10;

18 }

19

20 if(revNumber==tempNumber)

21 return 1; /*Palindrome Number*/

22 else

23 return 0; /*Not a Palindrome Number*/

24 }

25

26 int main()

27 {

28 int number;

29

30 printf("Enter an integer number: ");

31 scanf("%d", &number);

32

33 if(isPalindrome(number))

34 printf("%d is a palindrome.", number);

35 else

36 printf("%d is not a palindrome.", number);

37

38 return 0;

39 }
First run:

Enter an integer number: 12321

12321 is a palindrome.

Second run:

Enter an integer number: 1234

1234 is not a palindrome.


80. Check Armstrong Number using C program

/* C program to check whether a number is armstrong or not */

#include <stdio.h>

int main()
{
int number, sum=0, rem=0,tempNumber;

printf("Enter an integer number: ");


scanf("%d", &number);

tempNumber=number;

while(tempNumber!=0)
{
rem=tempNumber%10;
sum=sum + (rem*rem*rem);
tempNumber/=10;
}

/* checking number is armstrong or not */


if(sum==number)
printf("%d is an Armstrong number.",number);
else
printf("%d is not an Armstrong number.",number);

return 0;
}

Using User Define Function

/* C program to check whether a number is armstrong or not */

#include <stdio.h>
/*function to check Armstrong Number*/
int isArmstrong(int num)
{
int tempNumber=num;
int rem,sum;

/*sum of digit's cube*/


sum=0;
while(tempNumber!=0)
{
rem=tempNumber%10;
sum=sum + (rem*rem*rem);
tempNumber/=10;
}

if(sum==num)
return 1; /*Armstrong Number*/
else
return 0; /*Not an Armstrong Number*/
}

int main()
{
int number;

printf("Enter an integer number: ");


scanf("%d", &number);

if(isArmstrong(number))
printf("%d is an Armstrong number.",number);
else
printf("%d is not an Armstrong number.",number);

return 0;
}

Output

First run:
Enter an integer number: 153
153 is an Armstrong number.

Second run:
Enter an integer number: 167
167 is not an Armstrong number.

81. Count Digits of a Number using C program


1
/* C program to count digits in a number.*/
2
#include <stdio.h>
3
int main()
4
{
5
int num,tNum,cnt;
6
printf("Enter a number: ");
7
scanf("%d",&num);
8
cnt=0;
9
tNum=num;
10
while(tNum>0){
11
cnt++;
12
tNum/=10;
13
}
14
printf("Total numbers of digits are: %d in number: %d.",cnt,num);
15
return 0;
16
}

Using User Define Function


1 /* C program to count digits in a number.*/

2 #include <stdio.h>

3 /*function to count digits*/

4 int countDigits(int num)

5 {

6 int count=0;

7 while(num>0)

8 {
9

10 count++;

11 num/=10;

12 }

13 return count;

14 }

15

16 int main()

17 {

18 int num,tNum,cnt;

19

20 printf("Enter a number: ");

21 scanf("%d",&num);

22

23 cnt=countDigits(num);

24

25 printf("Total numbers of digits are: %d in number: %d.",cnt,num);

26

27 return 0;

28 }

29

Enter a number: 28765

Total numbers of digits are: 5 in number: 28765.

82. Count Occurrence of a Digit in a Number using C program


/*C program to print occurrence of a particular digit in a number.*/

#include <stdio.h>

int main()
{
int num,tNum,digit,cnt;
int rem;

printf("Enter a number: ");


scanf("%d",&num);
printf("Enter digit to search: ");
scanf("%d",&digit);

cnt=0;
tNum=num;

while(tNum>0)
{
rem=tNum%10;
if(rem==digit)
cnt++;
tNum/=10;
}

printf("Total occurrence of digit is: %d in number: %d.",cnt,num);

return 0;
}

Using User Define Function

/*C program to print occurrence of a particular digit in a number.*/

#include <stdio.h>

/*function to get occurrence of a digit in a number*/


int findOccurrence(int num,int dig)
{
int rem, cnt;

cnt=0;
while(num>0)
{
rem=num%10;
if(rem==dig)
cnt++;
num/=10;
}
return cnt;
}

int main()
{
int num, digit, cnt;

printf("Enter a number: ");


scanf("%d",&num);
printf("Enter digit to search: ");
scanf("%d",&digit);

cnt=findOccurrence(num,digit);

printf("Total occurrence of digit is: %d in number: %d.",cnt,num);

return 0;
}

Output

Enter a number: 23111


Enter digit to search: 1
Total occurrence of digit is: 3 in number: 23111.

83. Check Perfect Number using C program


1 /*C program to check nunber is perfect or not.*/

2 #include <stdio.h>

3 int main()

4 {

5 int num,loop;

6 int sum;

7 printf("Enter an integer number: ");

8 scanf("%d",&num);

9 sum=0;

10 for(loop=1; loop<num;loop++)

11 {

12 if(num%loop==0)
13

14

15

16
sum+=loop;
17
}
18
if(sum==num)
19
printf("%d is a perfect number.",num);
20
else
21
printf("%d is not a perfect number.",num);
22

23
return 0;
24
}
25

26

27

28

Using User Define Function


1 /*C program to check nunber is perfect or not.*/

3 #include <stdio.h>

5 /*function to check perfect number or not*/

6 int isPerfect(int num)

7 {

8 int loop,sum=0;

9
10 for(loop=1; loop<num; loop++)

11 {

12 if(num%loop==0)

13 sum+=loop;

14 }

15

16 if(sum==num)

17 return 1; /*Perfect Number*/

18 else

19 return 0; /*Not Perfect Number*/

20 }

21

22

23 int main()

24 {

25 int num,loop;

26 int sum;

27

28 printf("Enter an integer number: ");

29 scanf("%d",&num);

30

31 if(isPerfect(num))

32 printf("%d is a perfect number.",num);

33 else

34 printf("%d is not a perfect number.",num);

35
36 return 0;

37 }

First Run:

Enter an integer number: 6

6 is a perfect number.

Second Run:

Enter an integer number: 496

496 is a perfect number.

Third Run:

Enter an integer number: 695

695 is not a perfect numbe


84. Check Power of Two (2) using C program

/*C program to check number is power or 2 or not.*/

#include <stdio.h>

int main()
{
int num;
int tempNum,flag;

printf("Enter an integer number: ");


scanf("%d",&num);

tempNum=num;
flag=0;
/*check power of two*/
while(tempNum!=1)
{
if(tempNum%2!=0){
flag=1;
break;
}
tempNum=tempNum/2;
}

if(flag==0)
printf("%d is a number that is the power of 2.",num);
else
printf("%d is not the power of 2.",num);

return 0;
}

Using User Define Function

/*C program to check number is power or 2 or not.*/

#include <stdio.h>

/*function definition*/
int isPowerOf2(int number)
{
while(number!=1)
{
if(number%2!=0)
return 0;
number=number/2;
}
return 1;
}

int main()
{
int num;
printf("Enter an integer number: ");
scanf("%d",&num);

if(isPowerOf2(num))
printf("%d is a number that is the power of 2.",num);
else
printf("%d is not the power of 2.",num);

return 0;
}

Output

First Run:
Enter an integer number: 32
32 is a number that is the power of 2.

Second Run:
Enter an integer number: 36
36 is not the power of 2.

85. Check Perfect Square using C program


1 /*C program to check number is perfect square or not.*/

2 #include <stdio.h>

3 #include <math.h>

5 int main()

6 {

7 int num;

8 int iVar;

9 float fVar;

10

11 printf("Enter an integer number: ");

12 scanf("%d",&num);

13

14 fVar=sqrt((double)num);

15 iVar=fVar;

16

17 if(iVar==fVar)

18 printf("%d is a perfect square.",num);

19 else

20 printf("%d is not a perfect square.",num);

21

22 return 0;

23 }
24

Using User Define Function


1 /*C program to check number is perfect square or not.*/

2 #include <stdio.h>

3 #include <math.h>

4 /*function definition*/

5 int isPerfectSquare(int number)

6 {

7 int iVar;

8 float fVar;

9 fVar=sqrt((double)number);

10 iVar=fVar;

11 if(iVar==fVar)

12 return 1;

13 else

14 return 0;

15 }

16

17 int main()

18 {

19 int num;

20 printf("Enter an integer number: ");

21 scanf("%d",&num);

22

23 if(isPerfectSquare(num))

24 printf("%d is a perfect square.",num);


25

26

27 else

28 printf("%d is not a perfect square.",num);

29

30 return 0;

31 }

32

33

First Run:

Enter an integer number: 16

16 is a perfect square.

Second Run:

Enter an integer number: 26

26 is not a perfect square.


86. Pyramid, Star Series and Patterns Programs in C language

Half, Full, Incremented and Decrement Stars Series, Pyramid Pattern programs

Program - 1

1 /*C program to print following Pyramid:


2 *
3 **
4 ***
5 ****
6 *****
7 */
8
9 #include<stdio.h>
10
11 #define MAX 5
12
13 int main()
14 {
15 int i,j;
16
17 for(i=0; i< MAX; i++)
18 {
19 for(j=0;j<=i;j++)
20 {
21 printf("*");
22 }
23 printf("\n");
24 }
25 return 0;
26 }
*
**
***
****
*****

Program - 2

1 /*C program to print following Pyramid:


2 *****
3 ****
4 ***
5 **
6 *
7 */
8
9 #include<stdio.h>
10
11 #define MAX 5
12
13 int main()
14 {
15 int i,j;
16
17 for(i=MAX; i>=0; i--)
18 {
19 for(j=0;j<=i;j++)
20 {
21 printf("*");
22 }
23 printf("\n");
24 }
25 return 0;
26 }
*****
****
***
**
*

Program - 3

1 /*C program to print following Pyramid:


2 *
3 **
4 ***
5 ****
6 *****
7 */
8
9 #include<stdio.h>
10
11 #define MAX 5
12
13 int main()
14 {
15 int i,j;
16 int space=4;
17 /*run loop (parent loop) till number of rows*/
18 for(i=0;i< MAX;i++)
19 {
20 /*loop for initially space, before star printing*/
21 for(j=0;j< space;j++)
22 {
23 printf(" ");
24 }
25 for(j=0;j<=i;j++)
26 {
27 printf("* ");
28 }
29
30 printf("\n");
31 space--; /* decrement one space after one row*/
32 }
33 return 0;
34 }
*
**
***
****
*****
Program - 4

1 /*C program to print following Pyramid:


2 *
3 **
4 ***
5 ****
6 *****
7 *****
8 ****
9 ***
10 **
11 *
12 */
13
14 #include<stdio.h>
15
16 #define MAX 5
17
18 int main()
19 {
20 int i,j;
21 int space=4;
22 /*run loop (parent loop) till number of rows*/
23 for(i=0;i< MAX;i++)
24 {
25 /*loop for initially space, before star printing*/
26 for(j=0;j< space;j++)
27 {
28 printf(" ");
29 }
30 for(j=0;j<=i;j++)
31 {
32 printf("* ");
33 }
34
35 printf("\n");
36 space--;
37 }
38 /*repeat it again*/
39 space=0;
40 /*run loop (parent loop) till number of rows*/
41 for(i=MAX;i>0;i--)
42 {
43 /*loop for initially space, before star printing*/
44 for(j=0;j< space;j++)
45 {
46 printf(" ");
47 }
48 for(j=0;j< i;j++)
49 {
50 printf("* ");
51 }
52
53 printf("\n");
54 space++;
55 }
56 return 0;
57 }
*
**
***
****
*****
*****
****
***
**
*

Program - 5

1 /*C program to print following Pyramid:


2 **********
3 **** ****
4 *** ***
5 ** **
6 * *
7 */
8
9 #include<stdio.h>
10
11 #define MAX 5
12
13 int main()
14 {
15 int i,j;
16 int space=0;
17 /*run loop (parent loop) till number of rows*/
18 for(i=MAX;i>0;i--)
19 {
20 /*print first set of stars*/
21 for(j=0;j< i;j++)
22 {
23 printf("*");
24 }
25 for(j=0;j< space;j++)
26 {
27 printf(" ");
28 }
29 /*print second set of stars*/
30 for(j=0;j< i;j++)
31 {
32 printf("*");
33 }
34
35 printf("\n");
36 space+=2;
37 }
38 return 0;
39 }
**********
**** ****
*** ***
** **
* *

Number Pyramid Programs - Half, Full Incremented and Decrement Series programs

Program - 6

1 /*C program to print following Pyramid:


2 0
3 01
4 010
5 0101
6 01010
7 */
8
9 #include<stdio.h>
10
11 int main()
12 {
13 int i,j,k;
14
15 for(i=0 ; i<=4 ; i++)
16 {
17 for(j=4 ; j>i ; j--)
18 printf(" ");
19
20 for(k=0 ; k<=i; k++)
21 {
22 if(k%2==0)
23 printf("0");
24 else
25 printf("1");
26 }
27 printf("\n");
28 }
29
30 return 0;
31 }
0
01
010
0101
01010

Program - 7

1 /*C program to print following Pyramid:


2 0 0
3 01 01
4 010 010
5 0101 0101
6 0101001010
7 */
8
9 #include<stdio.h>
10
11 int main()
12 {
13 int i,j,k,l=8,m,n,o,p;
14 for(i=0; i<=4; i++)
15 {
16 for(j=0; j<=i; j++)
17 {
18 if(j%2==0)
19 printf("0");
20 else
21 printf("1");
22 }
23 for(k=1; k<=l; k++)
24 {
25 printf(" ");
26 }
27 l = l-2;
28 for(m=0; m<=i; m++)
29 {
30 if(m%2==0)
31 printf("0");
32 else
33 printf("1");
34 }
35
36 printf("\n");
37 }
38 return 0;
39 }
0 0
01 01
010 010
0101 0101
0101001010

Program - 8

1 /*C program to print following Pyramid:


2 12345
3 1234
4 123
5 12
6 1
7 */
8
9 #include<stdio.h>
10
11 int main()
12 {
13 int i,j;
14 for(i=5; i>=1; i--)
15 {
16 for(j=1; j<=i; j++)
17 {
18 printf("%d", j);
19 }
20 printf("\n");
21 }
22 return 0;
23 }
12345
1234
123
12
1
Program - 9

1 /*C program to print following Pyramid:


2 1
3 123
4 12345
5 1234567
6 123456789
7 */
8
9 #include<stdio.h>
10
11 int main()
12 {
13 int i,j,k,l=1;
14 for(i=1; i<=5; i++)
15 {
16 for(j=4; j>=i; j--)
17 {
18 printf(" ");
19 }
20
21 for(k=1; k<=l; k++)
22 {
23 printf("%d",k);
24 }
25 l = l+2;
26 printf("\n");
27 }
28 return 0;
29 }
1
123
12345
1234567
123456789

Program - 10

1 /*C program to print following Pyramid:


2 1 1
3 12 21
4 123 321
5 1234 4321
6 1234554321
7 */
8
9 #include<stdio.h>
10
11 int main()
12 {
13 int i,j,k,l,m=8,n=1;
14 for(i=1; i<=5; i++)
15 {
16 for(j=1; j<=i; j++)
17 {
18 printf("%d",j);
19 }
20 for(k=m; k>=1; k--)
21 {
22 printf(" ");
23 }
24 m = m-2;
25 for(l=n; l>=1; l--)
26 {
27 printf("%d",l);
28 }
29 n = n+1;
30 printf("\n");
31 }
32
33 return 0;
34 }
1 1
12 21
123 321
1234 4321
1234554321

Program - 11

1 /*
2 C program to print following pyramid
3 123454321
4 1234321
5 12321
6 121
7 1
8 */
9
10 #include <stdio.h>
11
12 int main()
13 {
14 int i,j;
15 int space=0;
16
17 /*Run parent loop*/
18 for(i=5; i>=1; i--)
19 {
20 /*Print space*/
21 for(j=1; j<=space; j++)
22 printf(" ");
23
24
25 /*Run loop to print first part of row*/
26 for(j=1; j<=i; j++)
27 printf("%d",j);
28
29 /*Run loop to print second part of row*/
30 for(j=i-1; j>=1; j--)
31 printf("%d",j);
32
33 printf("\n");
34 space++;
35 }
36
37 return 0;
38 }
123454321
1234321
12321
121
1

Characters Pyramid Programs

Program - 12

1 /*
2 C program to print character pyramid as given below:
3 A
4 BC
5 DEF
6 GHIJ
7 KLMNO
8 */
9
10 #include <stdio.h>
11
12 int main()
13 {
14 int i,j;
15 char ch='A';
16
17 for(i=1;i<=5;i++)
18 {
19 for(j=1;j<=i;j++)
20 {
21 printf("%c ",ch++);
22 }
23 printf("\n");
24 }
25
26 return 0;
27 }
A
BC
DEF
GHIJ
KLMNO

Program - 13

1 /*
2 C program to print character pyramid as given below:
3 A
4 BC
5 DEF
6 GHIJ
7 KLMNO
8 */
9
10 #include <stdio.h>
11
12 int main()
13 {
14 int i,j;
15 char ch;
16
17 for(i=1;i<=5;i++)
18 {
19 ch='A';
20 for(j=1;j<=i;j++)
21 {
22 printf("%c ",ch++);
23 }
24 printf("\n");
25 }
26
27 return 0;
28 }
A
AB
ABC
ABCD
ABCDE

Program - 14

1 /*
2 C program to print following character pyramid:
3 ABCDEDCBA
4 ABCD DCBA
5 ABC CBA
6 AB BA
7 A A
8 */
9
10 #include <stdio.h>
11
12 int main()
13 {
14 int i,j;
15 char CH='E';
16 int space=1;
17
18 /*loop for row*/
19 for(i=1; i<=5; i++)
20 {
21 /*first part of the row*/
22 for(j='A'; j<=CH; j++)
23 printf("%c",j);
24
25 /*remove last character of first part of first row*/
26 if(i==1)
27 printf("\b");
28
29 /*spaces between first, second part of the row*/
30 for(j=1; j<space; j++)
31 printf(" ");
32
33 /*second part of the row*/
34 for(j=CH; j>='A'; j--)
35 printf("%c",j);
36
37 printf("\n");
38 CH--;
39 space++;
40 }
41
42 return 0;
43 }
ABCDEDCBA
ABCD DCBA
ABC CBA
AB BA
A A

Program - 15

1 /*
2 C program to print following pyramid:
3 A
4 BAB
5 CBABC
6 DCBABCD
7 EDCBABCDE
8 */
9
10 #include <stdio.h>
11
12 int main()
13 {
14 int i,j;
15 char CH='A';
16 int space=4;
17
18 /*loop for row*/
19 for(i=1; i<=5; i++)
20 {
21 /*put space*/
22 for(j=1; j<=space; j++)
23 printf(" ");
24
25 /*first part of the row*/
26 for(j=CH; j>='A'; j--)
27 printf("%c",j);
28
29 /*second part of the row*/
30 for(j='B'; j<=CH; j++)
31 printf("%c",j);
32
33 printf("\n");
34 CH++;
35 space--;
36 }
37
38 return 0;
39 }
A
BAB
CBABC
DCBABCD
EDCBABCDE

Program - 16

1 /*
2 C program to print following pyramid
3 1A2B3C4D5E
4 1A2B3C4D
5 1A2B3C
6 1A2B
7 1A
8 */
9
10 #include <stdio.h>
11
12 int main()
13 {
14 int i,j,k;
15
16 /*Run parent loop*/
17 for(i=5; i>=1; i--)
18 {
19 for(j=1, k='A'; j<=i; j++,k++)
20 {
21 printf("%d%c",j,k);
22 }
23
24 printf("\n");
25 }
26
27 return 0;
28 }
1A2B3C4D5E
1A2B3C4D
1A2B3C
1A2B
1A
Program - 17

1 /*
2 C program to print following pyramid
3 A
4 ABA
5 ABCBA
6 ABCDCBA
7 ABCDEDCBA
8 */
9
10 #include <stdio.h>
11
12 int main()
13 {
14 int i,j;
15 int space=4;
16 char CH='A';
17
18 /*Run parent loop*/
19 for(i=1; i<=5; i++)
20 {
21 /*Print space*/
22 for(j=1; j<=space; j++)
23 printf(" ");
24
25
26 /*Run loop to print first part of row*/
27 for(j=1; j<=i; j++)
28 printf("%c",CH+j-1);
29
30 /*Run loop to print second part of row*/
31 for(j=i-1; j>=1; j--)
32 printf("%c",CH+j-1);
33
34 printf("\n");
35 space--;
36 }
37
38 return 0;
39 }
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
87. Sum of series programs/examples in C programming language

Sum of Series Programs in C - This section contains programs to solve (get sum) of different mathematic
series using C programming.

Solved series are:

1. 1+2+3+4+..N<
2. 1^2+2^2+3^2+4^2+..N^2

3. 1/1! + 2/2! + 3/3! + 4/4! + ... N/N!

4. 1+ 1/2 + 1/3 + 1/4 + 1/5 + .. 1/N

5. 1 + 3^2/3^3 + 5^2/5^3 + 7^2/7^3 + ... till N terms

Sum of Series Programs / Examples using C


1) C program to find sum of all natural numbers.
Series: 1+2+3+4+..N
1 /*This program will print the sum of all natural numbers from 1 to N.*/

3 #include<stdio.h>

5 int main()

6 {

7 int i,N,sum;

9 /*read value of N*/

10 printf("Enter the value of N: ");

11 scanf("%d",&N);

12

13 /*set sum by 0*/

14 sum=0;

15

16 /*calculate sum of the series*/


17 for(i=1;i<=N;i++)

18 sum= sum+ i;

19

20 /*print the sum*/

21

22 printf("Sum of the series is: %d\n",sum);

23

24 return 0;

25 }

Enter the value of N: 100


Sum of the series is: 5050

2) C program to find sum of the square of all natural numbers from 1 to N.


Series: 1^2+2^2+3^2+4^2+..N^2
1 /*This program will print the sum of the square of all natural numbers from 1 to N.*/

3 #include<stdio.h>

5 int main()

6 {

7 int i,N;

8 unsigned long sum;

10 /*read value of N*/

11 printf("Enter the value of N: ");

12 scanf("%d",&N);

13
14 /*set sum by 0*/

15 sum=0;

16

17 /*calculate sum of the series*/

18 for(i=1;i<=N;i++)

19 sum= sum+ (i*i);

20

21 /*print the sum*/

22

23 printf("Sum of the series is: %ld\n",sum);

24

25 return 0;

26 }

Enter the value of N: 100


Sum of the series is: 338350
3) C program to find the sum of Natural Number/Factorial of Number of all natural numbers from 1 to N.
Series: 1/1! + 2/2! + 3/3! + 4/4! + ... N/N!
1 /*

2 This program will find the sum of Natural

3 Number/Factorial of Number of all natural numbers from 1 to N.

4 */

6 #include<stdio.h>

8 /*function to find factorial of the number*/

9 unsigned long factorial(int num)

10 {

11 int i;

12 /*always assign 1, if variable multiplies with values*/

13 unsigned long fact=1;

14

15 /*multiply num*num-1*num-2*..1*/

16 for(i=num; i>=1; i--)

17 fact= fact*i;

18

19 /*return factorial*/

20 return fact;

21 }

22

23 int main()

24 {

25 int i,N;
26 float sum;

27

28 /*read value of N*/

29 printf("Enter the value of N: ");

30 scanf("%d",&N);

31

32 /*set sum by 0*/

33 sum=0.0f;

34

35 /*calculate sum of the series*/

36 for(i=1;i<=N;i++)

37 sum = sum + ( (float)(i) / (float)(factorial(i)) );

38

39 /*print the sum*/

40

41 printf("Sum of the series is: %f\n",sum);

42

43 return 0;

44 }

Enter the value of N: 10


Sum of the series is: 2.718282

4) C program to find sum of following series:


1+ 1/2 + 1/3 + 1/4 + 1/5 + .. 1/N
1 /*
2 C program to find sum of following series

3 1+ 1/2 + 1/3 + 1/4 + 1/5 + .. 1/N

4 */

6 #include<stdio.h>

8 int main()

9 {

10 int i,N;

11 float sum;

12

13 /*read value of N*/

14 printf("Enter the value of N: ");

15 scanf("%d",&N);

16

17 /*set sum by 0*/

18 sum=0.0f;

19

20 /*calculate sum of the series*/

21 for(i=1;i<=N;i++)

22 sum = sum + ((float)1/(float)i);

23

24 /*print the sum*/

25

26 printf("Sum of the series is: %f\n",sum);

27
28 return 0;

29 }

Enter the value of N: 10


Sum of the series is: 5.187378

5) C program to find sum of following series:


1 + 3^2/3^3 + 5^2/5^3 + 7^2/7^3 + ... till N terms
1 /*

2 C program to find sum of following series

3 1 + 3^2/3^3 + 5^2/5^3 + 7^2/7^3 + ... till N terms

4 */

6 #include<stdio.h>

7 #include<math.h>

9 int main()

10 {

11 int i,N;

12 float sum;

13 int count;

14

15

16 /*read value of N*/

17 printf("Enter total number of terms: ");

18 scanf("%d",&N);
19

20 /*set sum by 0*/

21 sum=0.0f;

22

23 /*calculate sum of the series*/

24 count=1;

25 for(i=1;i<=N;i++)

26 {

27 sum = sum + ( (float)(pow(count,2)) / (float)(pow(count,3)) );

28 count+=2;

29 }

30

31 /*print the sum*/

32

33 printf("Sum of the series is: %f\n",sum);

34

35 return 0;

36 }

Enter total number of terms: 10


Sum of the series is: 2.133256
88. User Define Function Programs/Examples in C
1) C program to find SUM and AVERAGE of two integer Numbers using User Define Functions.
1 /*

2 C program to find SUM and AVERAGE of two integer

3 Numbers using User Define Functions.

4 */

5
6 #include<stdio.h>

8 /*function declarations*/

9 int sumTwoNum(int,int); /*to get sum*/

10 float averageTwoNum(int,int); /*to get average*/

11

12 int main()

13 {

14 int number1,number2;

15 int sum;

16 float avg;

17

18 printf("Enter the first integer number: ");

19 scanf("%d",&number1);

20

21 printf("Enter the second integer number: ");

22 scanf("%d",&number2);

23

24 /*function calling*/

25 sum=sumTwoNum(number1,number2);

26 avg=averageTwoNum(number1,number2);

27

28 printf("Number1: %d, Number2: %d\n",number1,number2);

29 printf("Sum: %d, Average: %f\n",sum,avg);

30

31 return 0;
32 }

33

34 /*function definitions*/

35 /*

36 * Function : sumTwoNum

37 * Arguments : int,int - to pass two integer values

38 * return type : int - to return sum of values

39 */

40 int sumTwoNum(int x,int y)

41 {

42 /*x and y are the formal parameters*/

43 int sum;

44 sum=x+y;

45 return sum;

46 }

47 /*

48 * Function : averageTwoNum

49 * Arguments : int,int - to pass two integer values

50 * return type : float - to return average of values

51 */

52 float averageTwoNum(int x,int y)

53 {

54 /*x and y are the formal parameters*/

55 float average;

56 return ((float)(x)+(float)(y))/2;

57 }
Enter the first integer number: 100
Enter the second integer number: 201
Number1: 100, Number2: 201
Sum: 301, Average: 150.500000
2) C program to print Table of an Integer Number using User Define Functions.
1 /*

2 C program to print Table of an Integer Number

3 using User Define Functions.

4 */

6 #include<stdio.h>

8 /*function declaration*/

9 void printTable(int);

10

11 int main()

12 {

13 int number;

14

15 printf("Enter an integer number: ");

16 scanf("%d",&number);

17

18 printf("Table of %d is:\n",number);

19 printTable(number);

20

21 return 0;

22 }

23

24 /* function definition...

25 * Function : printTable
26 * Argumenets : int- to pass number for table

27 * Return Type : void

28 */

29 void printTable(int num)

30 {

31 int i;

32

33 for(i=1; i<=10; i++)

34 printf("%5d\n",(num*i));

35 }

Enter an integer number: 123


Table of 123 is:
123
246
369
492
615
738
861
984
1107
1230

3) C program to find Sum of all Array Elements by passing array as an argument using User Define
Functions.
1 /*

2 C program to find Sum of all Array Elements by passing array

3 as an argument using User Define Functions.

4 */

5
6 #include<stdio.h>

8 #define MAX_ELEMENTS 100

10 /*function declaration*/

11

12 int sumOfElements(int [],int);

13

14 int main()

15 {

16 int N,i,sum;

17 int arr[MAX_ELEMENTS];

18

19 printf("Enter total number of elements(1 to %d): ",MAX_ELEMENTS);

20 scanf("%d",&N);

21

22 if(N>MAX_ELEMENTS)

23 {

24 printf("You can't input larger than MAXIMUM value\n");

25 return 0;

26 }

27 else if(N<0)

28 {

29 printf("You can't input NEGATIVE or ZERO value.\n");

30 return 0;

31 }
32

33 /*Input array elements*/

34 printf("Enter array elements:\n");

35 for(i=0; i<N; i++)

36 {

37 printf("Enter element %4d: ",(i+1));

38 scanf("%d",&arr[i]);

39 }

40

41 /*function calling*/

42 sum=sumOfElements(arr,N);

43

44 printf("\nSUM of all Elements: %d\n",sum);

45

46 return 0;

47 }

48

49 /* function definition...

50 * Function : sumOfElements

51 * Argument(s) : int [], int - An integer array, Total No. of Elements

52 * Return Type : int - to return integer value of sum

53 */

54

55 int sumOfElements(int x[],int n)

56 {

57 int sum,i;
58 sum=0;

59

60 for(i=0; i<n; i++)

61 {

62 sum += x[i];

63 }

64

65 return sum;

66 }

First Run:
Enter total number of elements(1 to 100): 5
Enter array elements:
Enter element 1: 11
Enter element 2: 22
Enter element 3: 33
Enter element 4: 44
Enter element 5: 55

SUM of all Elements: 165

Second Run:
Enter total number of elements(1 to 100): 120
You can't input larger than MAXIMUM value

Third Run:
Enter total number of elements(1 to 100): -10
You can't input NEGATIVE or ZERO value.
4) C program to find Length of the String by passing String/ Character Array as an Argument using User
Define Functions.
1 /*

2 C program to find Length of the String by passing String/ Character Array

3 as an argument using User Define Functions.

4 */

6 #include<stdio.h>

8 /*function declaration*/

9 int stringLength(char *);

10

11 int main()

12 {

13 char text[100];

14 int length;

15

16 printf("Enter text (max- 100 characters): ");

17 scanf("%[^\n]s",text);

18 /*we can also use gets(text) - To read complete text untill '\n'*/

19

20 length=stringLength(text);

21

22 printf("Input text is: %s\n",text);

23 printf("Length is: %d\n",length);

24

25 return 0;
26 }

27

28 /* function definition...

29 * Function : stringLength

30 * Argument(s) : char * - Pointer of character arrar

31 * Return Type : int - Length of the string (integer type)

32 */

33 int stringLength(char *str)

34 {

35 int len=0;

36

37 /*calculate string length*/

38 for(len=0; str[len]!='\0'; len++);

39

40 /*return len*/

41 return len;

42 }

Enter text (max- 100 characters): Hello World.


Input text is: Hello World.
Length is: 12

5) C program to find Total Amount of purchased Items by Passing Structure as an Argument using User
Define Functions.
1 /*

2 C program to find Total Amount of purchased Items by Passing Structure

3 as an argument using User Define Functions.


4 */

6 #include<stdio.h>

8 /*declaration of structure*/

9 struct Item

10 {

11 char itemName[30];

12 int quantity;

13 float price, totalAmount;

14 };

15

16 /*function declaration*/

17 float getTotalAmount(struct Item);

18

19 int main()

20 {

21 /*structure variable declaratio*/

22 struct Item IT;

23 float tAmount; /*total amount*/

24

25 printf("Enter Item Name (max 30 characters): ");

26 scanf("%[^\n]s",IT.itemName);

27 /*we can also use gets(IT.itemName) - To read complete text untill '\n'*/

28

29 printf("Enter price: ");


30 scanf("%f",&IT.price);

31

32 printf("Enter quantity: ");

33 scanf("%d",&IT.quantity);

34

35

36 /*calling function by passing structure Item's variable "IT"*/

37 tAmount=getTotalAmount(IT);

38

39 printf("Item Name: %s\nPrice: %f\nQuantity: %d\n",IT.itemName, IT.price, IT.quantity);

40 printf("\nTotal Price of all quanities: %f\n",tAmount);

41 return 0;

42 }

43

44 /* function definition...

45 * Function : getTotalAmount

46 * Argument(s) : struct Item - Item Structure name

47 * Return Type : float - Total amount

48 */

49 float getTotalAmount(struct Item item)

50 {

51 /* remember Item - Is structure and "item" is structure variable name

52 * which is formal here*/

53

54 item.totalAmount= item.price * (float)item.quantity;

55
56 return (item.totalAmount);

57 }

Enter Item Name (max 30 characters): Pen


Enter price: 12.50
Enter quantity: 11
Item Name: Pen
Price: 12.500000
Quantity: 11

Total Price of all quanities: 137.500000


89. Read and Print One Dimensional Array using C Program

/*Program to read and print one dimensional array. */

#include <stdio.h>

/** funtion : readArray()


input : arr ( array of integer ), size
to read ONE-D integer array from standard input device (keyboard).
**/
void readArray(int arr[], int size)
{
int i =0;

printf("\nEnter elements : \n");

for(i=0; i<size; i++)


{
printf("Enter arr[%d] : ",i);
scanf("%d",&arr[i]);
}
}

/** funtion : printArray()


input : arr ( array of integer ), size
to display ONE-D integer array on standard output device (moniter).
**/
void printArray(int arr[],int size)
{
int i =0;

printf("\nElements are : ");

for(i=0; i<size; i++)


{
printf("\n\tarr[%d] : %d",i,arr[i]);
}
printf("\n");
}

int main()
{
int arr[10];

readArray(arr,10);
printArray(arr,10);

return 0;
}

Output

Enter elements :
Enter arr[0] : 1
Enter arr[1] : 2
Enter arr[2] : 3
Enter arr[3] : 4
Enter arr[4] : 5
Enter arr[5] : 6
Enter arr[6] : 7
Enter arr[7] : 8
Enter arr[8] : 9
Enter arr[9] : 10

Elements are :
arr[0] : 1
arr[1] : 2
arr[2] : 3
arr[3] : 4
arr[4] : 5
arr[5] : 6
arr[6] : 7
arr[7] : 8
arr[8] : 9
arr[9] : 10

90. Sum and Product of all 1D Array Elements using C program

/*Program to calculate Sum, Product of all elements.*/

#include <stdio.h>

int main()
{
int arr[10];
int sum,product,i;

/*Read array elements*/


printf("\nEnter elements : \n");
for(i=0; i<10; i++)
{
printf("Enter arr[%d] : ",i);
scanf("%d",&arr[i]);
}

/*calculate sum and product*/


sum=0;
product=1;
for(i=0; i<10; i++)
{
sum=sum+arr[i];
product=product*arr[i];
}

printf("\nSum of array is : %d" ,sum);


printf("\nProduct of array is : %d\n",product);

return 0;
}

Output

Enter elements :
Enter arr[0] : 11
Enter arr[1] : 22
Enter arr[2] : 3
Enter arr[3] : 4
Enter arr[4] : 5
Enter arr[5] : 66
Enter arr[6] : 7
Enter arr[7] : 8
Enter arr[8] : 9
Enter arr[9] : 10

Sum of array is : 145


Product of array is : 534965504
91.Using User Define Function

/*Program to calculate Sum, Product of all elements.*/

#include <stdio.h>
/** funtion : readArray()
input : arr ( array of integer ), size
to read ONE-D integer array from standard input device (keyboard).
**/
void readArray(int arr[], int size)
{
int i =0;

printf("\nEnter elements : \n");


for(i=0; i<size; i++)
{
printf("Enter arr[%d] : ",i);
scanf("%d",&arr[i]);
}
}

/** funtion : getSum()


input : arr ( array of integer ), size
to get sum of all elements of array.
**/
int getSum(int arr[], int size)
{
int i=0,sum=0;

for(i=0; i<size; i++)


{
sum += arr[i];
}
return sum;
}

/** funtion : getProduct()


input : arr ( array of integer ), size
to get product of all elements of array.
**/
int getProduct(int arr[], int size)
{
int i=0,product=1;

for(i=0;i < size; i++)


{
product *= arr[i];
}

return product;
}

int main()
{
int arr[10];

readArray(arr,10);

printf("\nSum of array is : %d" , getSum (arr,10) );


printf("\nProduct of array is : %d\n", getProduct(arr,10) );

return 0;
}

Output

Enter elements :
Enter arr[0] : 11
Enter arr[1] : 22
Enter arr[2] : 3
Enter arr[3] : 4
Enter arr[4] : 5
Enter arr[5] : 66
Enter arr[6] : 7
Enter arr[7] : 8
Enter arr[8] : 9
Enter arr[9] : 10

Sum of array is : 145


Product of array is : 534965504

92. Find Smallest and Largest elements from One Dimensional Array using C program

1 /*Program to find largest & smallest element among all elements.*/


2
3 #include <stdio.h>
4
5 /** funtion : readArray()
6 input : arr ( array of integer ), size
7 to read ONE-D integer array from standard input device (keyboard).
8 **/
9 void readArray(int arr[], int size)
10 {
11 int i =0;
12
13 printf("\nEnter elements : \n");
14
15 for(i=0; i < size; i++)
16 {
17 printf("Enter arr[%d] : ",i);
18 scanf("%d",&arr[i]);
19 }
20 }
21
22 /** funtion : getLargest()
23 input : arr ( array of integer ), size
24 to get largest element of array.
25 **/
26 int getLargest(int arr[], int size)
27 {
28 int i=0,largest=0;
29
30 largest = arr[0];
31
32 for(i=1;i < size; i++)
33 {
34 if( arr[i] > largest )
35 largest = arr[i];
36 }
37
38 return largest;
39 }
40
41 /** funtion : getSmallest()
42 input : arr ( array of integer ), size
43 to get smallest element of array.
44 **/
45 int getSmallest(int arr[], int size)
46 {
47 int i=0,smallest=0;
48
49 smallest = arr[0];
50
51 for(i=1;i < size; i++)
52 {
53 if( arr[i] < smallest )
54 smallest = arr[i];
55 }
56
57 return smallest;
58 }
59
60 int main()
61 {
62 int arr[10];
63
64 readArray(arr,10);
65
66 printf("\nLargest element of array is : %d" , getLargest (arr,10) );
67 printf("\nSmallest element of array is : %d\n", getSmallest (arr,10) );
68
69 return 0;
70 }
Enter elements :

Enter arr[0] : 11

Enter arr[1] : 22

Enter arr[2] : 33

Enter arr[3] : 44

Enter arr[4] : 55

Enter arr[5] : 66

Enter arr[6] : 77

Enter arr[7] : 66

Enter arr[8] : 56

Enter arr[9] : 56

Largest element of array is : 77

Smallest element of array is : 11


93.Replace EVEN and ODD elements by 0 and 1 using C program

/*Program to replace EVEN elements by 0 and ODD elements by 1.*/


#include <stdio.h>

/** funtion : readArray()


input : arr ( array of integer ), size
to read ONE-D integer array from standard input device (keyboard).
**/
void readArray(int arr[], int size)
{
int i =0;

printf("\nEnter elements : \n");

for(i=0; i < size; i++)


{
printf("Enter arr[%d] : ",i);
scanf("%d",&arr[i]);
}
}
/** funtion : printArray()
input : arr ( array of integer ), size
to display ONE-D integer array on standard output device (moniter).
**/
void printArray(int arr[], int size)
{
int i =0;

printf("\nElements are : ");

for(i=0; i < size; i++)


{
printf("\n\tarr[%d] : %d",i,arr[i]);
}
printf("\n");
}

/** funtion : replaceEvenOdd()


input : arr ( array of integer ), size
to replace EVEN elements by 0 and ODD elements by 1.
**/
void replaceEvenOdd(int arr[], int size)
{
int i=0;

for(i=0; i < size; i++)


{
if( arr[i] % 2 == 0 )
arr[i] = 0 ;
else
arr[i] = 1 ;
}
}

int main()
{
int arr[10];

readArray(arr,10);

printf("\nBefore replacement : ");


printArray(arr,10);

replaceEvenOdd(arr,10);

printf("\nAfter replacement : ");


printArray(arr,10);

return 0;
}
Output

Enter elements :
Enter arr[0] : 1
Enter arr[1] : 2
Enter arr[2] : 3
Enter arr[3] : 4
Enter arr[4] : 4
Enter arr[5] : 3
Enter arr[6] : 4
Enter arr[7] : 5
Enter arr[8] : 6
Enter arr[9] : 7

Before replacement :
Elements are :
arr[0] : 1
arr[1] : 2
arr[2] : 3
arr[3] : 4
arr[4] : 4
arr[5] : 3
arr[6] : 4
arr[7] : 5
arr[8] : 6
arr[9] : 7

After replacement :
Elements are :
arr[0] : 1
arr[1] : 0
arr[2] : 1
arr[3] : 0
arr[4] : 0
arr[5] : 1
arr[6] : 0
arr[7] : 1
arr[8] : 0
arr[9] : 1

94.Merge Two One Dimensional Arrays using C program

1 /*Program to merge two arrays*/


2 #include <stdio.h>
3
4 /** funtion : readArray()
5 input : arr ( array of integer ), size
6 to read ONE-D integer array from standard input device (keyboard).
7 **/
8 void readArray(int arr[], int size)
9 {
10 int i =0;
11
12 printf("\nEnter elements : \n");
13
14 for(i=0; i < size; i++)
15 {
16 printf("Enter arr[%d] : ",i);
17 scanf("%d",&arr[i]);
18 }
19 }
20
21 /** funtion : printArray()
22 input : arr ( array of integer ), size
23 to display ONE-D integer array on standard output device (moniter).
24 **/
25 void printArray(int arr[],int size)
26 {
27 int i =0;
28
29 printf("\nElements are : ");
30
31 for(i=0; i < size; i++)
32 {
33 printf("\n\tarr[%d] : %d",i,arr[i]);
34 }
35 printf("\n");
36 }
37
38 void merge(int arr1[], int size1, int arr2[], int size2, int arr3[])
39 {
40 int i = 0,j=0 ;
41
42 for(i=0; i < size1; i++)
43 arr3[i] = arr1[i];
44
45 for(i=5,j=0;i < size2+5; i++,j++)
46 arr3[i] = arr2[j];
47 }
48
49 int main()
50 {
51 int arr1[5];
52 int arr2[5];
53 int arr3[10];
54
55 readArray(arr1,5);
56 readArray(arr2,5);
57
58 merge(arr1, 5, arr2, 5, arr3);
59
60 printArray(arr3,10);
61
62 return 0;
63 }

Enter elements :

Enter arr[0] : 12

Enter arr[1] : 23

Enter arr[2] : 34

Enter arr[3] : 45

Enter arr[4] : 56

Enter elements :

Enter arr[0] : 11

Enter arr[1] : 22

Enter arr[2] : 33

Enter arr[3] : 44

Enter arr[4] : 55

Elements are :

arr[0] : 12

arr[1] : 23

arr[2] : 34

arr[3] : 45

arr[4] : 56

arr[5] : 11

arr[6] : 22

arr[7] : 33
arr[8] : 44

arr[9] : 55

95.Add and Subtract elements of Two One Dimensional Array using C program

/*program to add and subtract elements of two arrays.*/

#include<stdio.h>
#define MAX 20

/* function : readArray()
to read array elements.
*/

void readArray(int a[],int size)


{
int i;
for(i=0;i< size;i++)
{
printf("Enter %d element :",i+1);
scanf("%d",&a[i]);
}
}

/* function : printArray()
to print array elements.
*/
void printArray(int a[],int size)
{
int i;
for(i=0;i < size; i++)
printf("%5d",a[i]);
}

/* function : addArray(),
to add elements of two arrays.
*/
void addArray(int a[],int b[],int c[],int size)
{
int i;
for(i=0; i< size;i++)
c[i]=a[i]+b[i];
}

/* function : subArray(),
to subtract elements of two arrays.
*/
void subArray(int a[],int b[],int c[],int size)
{
int i;
for(i=0; i< size;i++)
c[i]=a[i]-b[i];
}

int main()
{
int A[MAX],B[MAX],ADD[MAX],SUB[MAX];
int i,n;

printf("\nEnter size of an Array :");


scanf("%d",&n);

printf("\nEnter elements of Array 1:\n");


readArray(A,n);
printf("\nEnter elements of Array 2:\n");
readArray(B,n);

/* add Arrays*/
addArray(A,B,ADD,n);
/* subtract two Arrays*/
subArray(A,B,SUB,n);

printf("\nArray elements after adding :\n");


printArray(ADD,n);

printf("\nArray elements after subtracting :\n");


printArray(SUB,n);

printf("\n\n");
return 0;
}

Output

Enter size of an Array :5

Enter elements of Array 1:


Enter 1 element :12
Enter 2 element :23
Enter 3 element :34
Enter 4 element :45
Enter 5 element :56

Enter elements of Array 2:


Enter 1 element :11
Enter 2 element :22
Enter 3 element :33
Enter 4 element :44
Enter 5 element :55

Array elements after adding :


23 45 67 89 111
Array elements after subtracting :
1 1 1 1 1
program to find a number from array elements.
96. /*program to find a number from array elements.*/
2
3 #include<stdio.h>
4 #define MAX 20
5
6 /* function : readArray()
7 to read array elements.
8 */
9
10 void readArray(int a[],int size)
11 {
12 int i;
13 for(i=0;i< size;i++)
14 {
15 printf("Enter %d element :",i+1);
16 scanf("%d",&a[i]);
17 }
18 }
19
20 /* function : findElement(),
21 to find an item from array elements.
22 return : -1 for fail,
23 position to success.
24 */
25 int findElement(int a[],int size,int item)
26 {
27 int i,pos=-1;
28 for(i=0;i< size;i++)
29 {
30 if(a[i]==item)
31 {
32 pos=i;
33 break;
34 }
35 }
36 return pos;
37 }
38
39 int main()
40 {
41 int arr[MAX];
42 int n,item,pos;
43
44
45 printf("\nEnter size of an Array :");
46 scanf("%d",&n);
47
48 printf("\nEnter elements of Array 1:\n");
49 readArray(arr,n);
50
51 printf("Enter an item to find :");
52 scanf("%d",&item);
53
54 pos=findElement(arr,n,item);
55 if(pos==-1)
56 printf("\n%d does not exists in array.\n",item);
57 else
58 printf("\n%d find @ %d position.\n",item,pos);
59
60
61 printf("\n\n");
62 return 0;
63 }

first run

Enter size of an Array :5

Enter elements of Array 1:

Enter 1 element :12

Enter 2 element :23

Enter 3 element :34

Enter 4 element :45

Enter 5 element :56

Enter an item to find :45

45 find @ 3 position.

second run

Enter size of an Array :5


Enter elements of Array 1:

Enter 1 element :12

Enter 2 element :23

Enter 3 element :34

Enter 4 element :45

Enter 5 element :56

Enter an item to find :10

10 does not exists in array.

97. program to sort array elements in ascending order.


1 /*program to sort array elements in ascending order. */
2 #include <stdio.h>
3
4 /** funtion : readArray()
5 input : arr ( array of integer ), size
6 to read ONE-D integer array from standard input device (keyboard).
7 **/
8 void readArray(int arr[], int size)
9 {
10 int i =0;
11
12 printf("\nEnter elements : \n");
13
14 for(i=0; i < size; i++)
15 {
16 printf("Enter arr[%d] : ",i);
17 scanf("%d",&arr[i]);
18 }
19 }
20
21 /** funtion : printArray()
22 input : arr ( array of integer ), size
23 to display ONE-D integer array on standard output device (moniter).
24 **/
25 void printArray(int arr[],int size)
26 {
27 int i =0;
28
29 printf("\nElements are : ");
30
31 for(i=0; i < size; i++)
32 {
33 printf("\n\tarr[%d] : %d",i,arr[i]);
34 }
35 printf("\n");
36 }
37
38 void sortArray(int arr[],int size)
39 {
40 int i=0,j=0,temp;
41
42 for( i = 0 ; i < size-1 ; i++)
43 {
44 for( j = i+1; j < size; j++ )
45 {
46 if( arr[i] > arr[j] )
47 {
48 temp = arr[i] ;
49 arr[i] = arr[j] ;
50 arr[j] = temp ;
51 }
52 }
53 }
54 }
55
56 int main()
57 {
58 int arr[5];
59
60 readArray(arr,5);
61
62 printf("\nBefore Sorting");
63 printArray(arr,5);
64
65 sortArray(arr,5);
66
67 printf("\nAfter Sorting");
68 printArray(arr,5);
69
70 return 0;
71 }

Enter elements :

Enter arr[0] : 12

Enter arr[1] : 10

Enter arr[2] : 67

Enter arr[3] : 88
Enter arr[4] : 10

Before Sorting

Elements are :

arr[0] : 12

arr[1] : 10

arr[2] : 67

arr[3] : 88

arr[4] : 10

After Sorting

Elements are :

arr[0] : 10

arr[1] : 10

arr[2] : 12

arr[3] : 67

arr[4] : 88

98. program to reverse array elements.


1 /*program to reverse array elements.*/
2
3 #include<stdio.h>
4 #define MAX 20
5
6 /* function : readArray()
7 to read array elements.
8 */
9
10 void readArray(int a[],int size)
11 {
12 int i;
13 for(i=0;i< size;i++)
14 {
15 printf("Enter %d element :",i+1);
16 scanf("%d",&a[i]);
17 }
18 }
19
20 /* function : printArray()
21 to print array elements.
22 */
23 void printArray(int a[],int size)
24 {
25 int i;
26 for(i=0;i < size; i++)
27 printf("%5d",a[i]);
28 }
29
30 /* function : reverseArray(),
31 to reverse array elements.
32 */
33 void reverseArray(int a[],int size)
34 {
35 int i,temp;
36 for(i=0;i < size/2; i++)
37 {
38 temp=a[i];
39 a[i]=a[((size-1)-i)];
40 a[((size-1)-i)]=temp;
41 }
42 }
43
44 int main()
45 {
46 int arr[MAX];
47 int n,item,pos;
48
49
50 printf("\nEnter size of an Array :");
51 scanf("%d",&n);
52
53 printf("\nEnter elements of Array 1:\n");
54 readArray(arr,n);
55
56 printf("\nArray elements before reverse :\n");
57 printArray(arr,n);
58
59 /* reverse array elements*/
60 reverseArray(arr,n);
61 printf("\nArray elements After reverse :\n");
62 printArray(arr,n);
63
64 printf("\n\n");
65 return 0;
66 }
first run (when number of elements are EVEN)

Enter size of an Array :6

Enter elements of Array 1:

Enter 1 element :11

Enter 2 element :22

Enter 3 element :33

Enter 4 element :44

Enter 5 element :55

Enter 6 element :66

Array elements before reverse :

11 22 33 44 55 66

Array elements After reverse :

66 55 44 33 22 11

second run (when number of elements are ODD)

Enter size of an Array :5

Enter elements of Array 1:

Enter 1 element :11

Enter 2 element :22

Enter 3 element :33

Enter 4 element :44

Enter 5 element :55

Array elements before reverse :


11 22 33 44 55

Array elements After reverse :

55 44 33 22 11
99. C program to swap adjacent elements of a one dimensional array.
1 /*C program to swap adjacent elements of an one dimensional array.*/

3 #include <stdio.h>

4 #define MAX 100

5 int main()

6 {

7 int arr[MAX],n,i;

8 int temp;

10 printf("Enter total number of elements: ");

11 scanf("%d",&n);

12

13 //value of n must be even

14 if(n%2 !=0)

15 {

16 printf("Total number of elements should be EVEN.");

17 return 1;

18 }

19 //read array elements

20 printf("Enter array elements:\n");

21 for(i=0;i < n;i++)

22 {

23 printf("Enter element %d:",i+1);

24 scanf("%d",&arr[i]);

25 }
26 //swap adjacent elements

27 for(i=0;i < n;i+=2)

28 {

29 temp = arr[i];

30 arr[i] = arr[i+1];

31 arr[i+1]= temp;

32 }

33

34 printf("\nArray elements after swapping adjacent elements:\n");

35 for(i=0;i < n;i++)

36 {

37 printf("%d\n",arr[i]);

38 }

39 return;

40 }

First Run:

Enter total number of elements: 11

Total number of elements should be EVEN.

Second Run:

Enter total number of elements: 10

Enter array elements:

Enter element 1: 10

Enter element 2: 20

Enter element 3: 30

Enter element 4: 40
Enter element 5: 50

Enter element 6: 60

Enter element 7: 70

Enter element 8: 80

Enter element 9: 90

Enter element 10: 100

Array elements after swapping adjacent elements:

20

10

40

30

60

50

80

70

100

90

100. C program to find occurrence of an element in one dimensional array.


1 /*C program to find occurrence of an element in one dimensional array.*/

3 #include <stdio.h>

4 #define MAX 100

5 int main()

6 {
7 int arr[MAX],n,i;

8 int num,count;

10 printf("Enter total number of elements: ");

11 scanf("%d",&n);

12

13 //read array elements

14 printf("Enter array elements:\n");

15 for(i=0;i< n;i++)

16 {

17 printf("Enter element %d: ",i+1);

18 scanf("%d",&arr[i]);

19 }

20

21 printf("Enter number to find Occurrence: ");

22 scanf("%d",&num);

23

24 //count occurance of num

25 count=0;

26 for(i=0;i< n;i++)

27 {

28 if(arr[i]==num)

29 count++;

30 }

31 printf("Occurrence of %d is: %d\n",num,count);

32 return 0;
33 }

Enter total number of elements: 5

Enter array elements:

Enter element 1: 10

Enter element 2: 10

Enter element 3: 20

Enter element 4: 30

Enter element 5: 10

Enter number to find Occurrence: 10

Occurrence of 10 is: 3

101. C program to sort a one dimensional array in ascending order.


1 /*C program to sort an one dimensional array in ascending order.*/

2 #include <stdio.h>

3 #define MAX 100

4 int main()

5 {

6 int arr[MAX],n,i,j;

7 int temp;

9 printf("Enter total number of elements: ");

10 scanf("%d",&n);

11

12 //read array elements

13 printf("Enter array elements:\n");

14 for(i=0;i< n;i++)
15 {

16 printf("Enter element %d: ",i+1);

17 scanf("%d",&arr[i]);

18 }

19

20 //sort array

21 for(i=0;i< n;i++)

22 {

23 for(j=i+1;j< n;j++)

24 {

25 if(arr[i]>arr[j])

26 {

27 temp =arr[i];

28 arr[i] =arr[j];

29 arr[j] =temp;

30 }

31 }

32 }

33

34 printf("\nArray elements after sorting:\n");

35 for(i=0;i< n;i++)

36 {

37 printf("%d\n",arr[i]);

38 }

39 return 0;

40 }
Enter total number of elements: 5

Enter array elements:

Enter element 1: 100

Enter element 2: 999

Enter element 3: 200

Enter element 4: 800

Enter element 5: 300

Array elements after sorting:

100

200

300

800

999

102.C program to sort a one dimensional array in descending order.


1 /*C program to sort an one dimensional array in descending order.*/

2 #include <stdio.h>

3 #define MAX 100

4 int main()

5 {

6 int arr[MAX],n,i,j;

7 int temp;

9 printf("Enter total number of elements: ");

10 scanf("%d",&n);

11
12 //read array elements

13 printf("Enter array elements:\n");

14 for(i=0;i< n;i++)

15 {

16 printf("Enter element %d: ",i+1);

17 scanf("%d",&arr[i]);

18 }

19

20 //sort array

21 for(i=0;i< n;i++)

22 {

23 for(j=i+1;j< n;j++)

24 {

25 if(arr[i]< arr[j])

26 {

27 temp =arr[i];

28 arr[i] =arr[j];

29 arr[j] =temp;

30 }

31 }

32 }

33

34 printf("\nArray elements after sorting:\n");

35 for(i=0;i< n;i++)

36 {

37 printf("%d\n",arr[i]);
38 }

39 return 0;

40 }

Enter total number of elements: 5

Enter array elements:

Enter element 1: 100

Enter element 2: 999

Enter element 3: 200

Enter element 4: 800

Enter element 5: 300

Array elements after sorting:

999

800

300

200

100

103.C program to delete given element from one dimensional array.


1 /*C program to delete given element from one dimensional array.*/

2 #include <stdio.h>

3 #define MAX 100

4 int main()

5 {

6 int arr[MAX],n,i,j;

7 int num,countDel;

8
9

10 printf("Enter total number of elements: ");

11 scanf("%d",&n);

12

13 //read array elements

14 printf("Enter array elements:\n");

15 for(i=0;i< n;i++)

16 {

17 printf("Enter element %d: ",i+1);

18 scanf("%d",&arr[i]);

19 }

20

21 printf("\nEnter number (element) to delete: ");

22 scanf("%d",&num);

23

24 //delete elements

25 countDel=0;

26 for(i=0;i< n;i++)

27 {

28 if(arr[i]==num)

29 {

30 countDel++;

31 //shift all other elements up

32 for(j=i;j< n;j++){

33 arr[j]=arr[j+1];

34 }
35 }

36 }

37 if(countDel)

38 printf("%d found %d times and deleted successfully.",num,countDel);

39 else

40 printf("%d not found.",num);

41

42 printf("\nArray elements after deleting %d.\n",num);

43 for(i=0;i<(n-countDel);i++)

44 {

45 printf("%d\n",arr[i]);

46 }

47 return 0;

48 }

First Run:

Enter total number of elements: 10

Enter array elements:

Enter element 1: 10

Enter element 2: 20

Enter element 3: 10

Enter element 4: 30

Enter element 5: 10

Enter element 6: 40

Enter element 7: 10

Enter element 8: 50

Enter element 9: 60
Enter element 10: 70

Enter number (element) to delete: 10

10 found 4 times and deleted successfully.

Array elements after deleting 10.

20

30

40

50

60

70

Second Run:

Enter total number of elements: 10

Enter array elements:

Enter element 1: 10

Enter element 2: 20

Enter element 3: 10

Enter element 4: 30

Enter element 5: 10

Enter element 6: 40

Enter element 7: 10

Enter element 8: 50

Enter element 9: 60

Enter element 10: 70


Enter number (element) to delete: 90

90 not found.

104.C program to create array with reverse elements of one dimensional


array.
1 /*C program to create array with reverse elements of one dimensional array.*/

2 #include <stdio.h>

3 #define MAX 100

4 int main()

5 {

6 int arr[MAX],revArr[MAX],i,j,n;

9 printf("Enter total number of elements: ");

10 scanf("%d",&n);

11

12 //read array elements

13 printf("Enter array elements:\n");

14 for(i=0;i< n;i++)

15 {

16 printf("Enter element %d: ",i+1);

17 scanf("%d",&arr[i]);

18 }

19

20 //store reverse values of arr into revArr

21 for(i=(n-1),j=0; i>=0; i--,j++)

22 {
23 revArr[j]=arr[i];

24 }

25

26 printf("\nArray elements after reverse:\n");

27 for(i=0;i< n;i++)

28 {

29 printf("%d\n",revArr[i]);

30 }

31 return 0;

32 }

Enter total number of elements: 5

Enter array elements:

Enter element 1: 10

Enter element 2: 20

Enter element 3: 30

Enter element 4: 40

Enter element 5: 50

Array elements after reverse:

50

40

30

20

10
105. Program to find first repeated element in C

#include <stdio.h>
int main()
{
int arr[5];
int i,j,n=5;
int ind,ele; //to store index & element

//read array elements


for(i=0; i<n; i++)
{
printf("Enter element %d: ",i+1);
scanf("%d",&arr[i]);
}

printf("Array elements are: ");


for(i=0; i<n; i++)
printf("%d ",arr[i]);

printf("\n");
ind=-1;
//check first repeated element
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(arr[i]==arr[j])
{
ele=arr[j];
ind=j;
break;
}
}
}
if(ind!=-1)
printf("%d repeated @ %d index\n",ele,ind);
else
printf("There is no repeated element\n");

return 0;
}

Output

Firsr run:
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter element 4: 20
Enter element 5: 40
Array elements are: 10 20 30 20 40
20 repeated @ 3 index
Second run:
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter element 4: 40
Enter element 5: 50
Array elements are: 10 20 30 40 50
There is no repeated element
106.C Program to read and print a RxC Matrix, R and C must be input by User

This program will read a two dimensional array (Matrix), number of rows (R) and number of columns (C)
will be read through the User.

#include <stdio.h>

#define MAXROW 10
#define MAXCOL 10

int main()
{
int matrix[MAXROW][MAXCOL];
int i,j,r,c;

printf("Enter number of Rows :");


scanf("%d",&r);
printf("Enter number of Cols :");
scanf("%d",&c);

printf("\nEnter matrix elements :\n");


for(i=0;i< r;i++)
{
for(j=0;j< c;j++)
{
printf("Enter element [%d,%d] : ",i+1,j+1);
scanf("%d",&matrix[i][j]);
}
}

printf("\nMatrix is :\n");
for(i=0;i< r;i++)
{
for(j=0;j< c;j++)
{
printf("%d\t",matrix[i][j]);
}
printf("\n"); /*new line after row elements*/
}
return 0;
}

Output

Enter number of Rows :3


Enter number of Cols :3

Enter matrix elements :


Enter element [1,1] : 1
Enter element [1,2] : 1
Enter element [1,3] : 1
Enter element [2,1] : 2
Enter element [2,2] : 2
Enter element [2,3] : 2
Enter element [3,1] : 3
Enter element [3,2] : 3
Enter element [3,3] : 3

Matrix is :
1 1 1
2 2 2
3 3 3
107.C Program to read a matrix and find sum, product of all elements of two dimensional (matrix)
array

This program will read a matrix and prints sum and product of all elements of the two dimensional array.

#include <stdio.h>

#define MAXROW 10
#define MAXCOL 10

int main()
{
int matrix[MAXROW][MAXCOL];
int i,j,r,c;
int sum,product;

printf("Enter number of Rows :");


scanf("%d",&r);
printf("Enter number of Cols :");
scanf("%d",&c);

printf("\nEnter matrix elements :\n");


for(i=0;i< r;i++)
{
for(j=0;j< c;j++)
{
printf("Enter element [%d,%d] : ",i+1,j+1);
scanf("%d",&matrix[i][j]);
}
}

/*sum and product of all elements*/


/*initializing sun and product variables*/
sum =0;
product =1;
for(i=0;i< r;i++)
{
for(j=0;j< c;j++)
{
sum += matrix[i][j];
product *= matrix[i][j];
}

printf("\nSUM of all elements : %d \nProduct of all elements :%d",sum,product);


return 0;
}

Output

Enter number of Rows :3


Enter number of Cols :3

Enter matrix elements :


Enter element [1,1] : 1
Enter element [1,2] : 1
Enter element [1,3] : 1
Enter element [2,1] : 2
Enter element [2,2] : 2
Enter element [2,3] : 2
Enter element [3,1] : 3
Enter element [3,2] : 3
Enter element [3,3] : 3

SUM of all elements : 18


Product of all elements :216
108. Program to find sum of all elements of each row of a matrix.
1 #include <stdio.h>
2
3 #define MAXROW 10
4 #define MAXCOL 10
5
6 int main()
7 {
8 int matrix[MAXROW][MAXCOL];
9 int i,j,r,c;
10 int sum,product;
11
12 printf("Enter number of Rows :");
13 scanf("%d",&r);
14 printf("Enter number of Cols :");
15 scanf("%d",&c);
16
17 printf("\nEnter matrix elements :\n");
18 for(i=0;i< r;i++)
19 {
20 for(j=0;j< c;j++)
21 {
22 printf("Enter element [%d,%d] : ",i+1,j+1);
23 scanf("%d",&matrix[i][j]);
24 }
25 }
26 printf("\n");
27 /*sum of all rows*/
28 for(i=0;i< r;i++)
29 {
30 sum=0; /*initializing sum*/
31 for(j=0;j< c;j++)
32 {
33 printf("%d\t",matrix[i][j]); /*print elements*/
34 sum += matrix[i][j];
35 }
36 printf("\tSUM : %d",sum);
37 printf("\n"); /*after each row print new line*/
38 }
39
40 }

Enter number of Rows :3

Enter number of Cols :3

Enter matrix elements :

Enter element [1,1] : 1

Enter element [1,2] : 2

Enter element [1,3] : 3

Enter element [2,1] : 4

Enter element [2,2] : 5

Enter element [2,3] : 6


Enter element [3,1] : 7

Enter element [3,2] : 8

Enter element [3,3] : 9

1 2 3 SUM : 6

4 5 6 SUM : 15

7 8 9 SUM : 24

109. Program to transpose a matrix.


1 #include <stdio.h>
2
3 #define MAXROW 10
4 #define MAXCOL 10
5
6 int main()
7 {
8 int matrix[MAXROW][MAXCOL];
9 int i,j,r,c;
10
11 printf("Enter number of Rows :");
12 scanf("%d",&r);
13 printf("Enter number of Cols :");
14 scanf("%d",&c);
15
16 printf("\nEnter matrix elements :\n");
17 for(i=0;i< r;i++)
18 {
19 for(j=0;j< c;j++)
20 {
21 printf("Enter element [%d,%d] : ",i+1,j+1);
22 scanf("%d",&matrix[i][j]);
23 }
24 }
25
26 /*Transpose a matrix */
27 printf("\nTranspose Matrix is :");
28 for(i=0;i< c;i++)
29 {
30 for(j=0;j< r;j++)
31 {
32 printf("%d\t",matrix[j][i]); /*print elements*/
33 }
34 printf("\n"); /*after each row print new line*/
35 }
36 return 0;
37 }

Enter number of Rows :2

Enter number of Cols :3

Enter matrix elements :

Enter element [1,1] : 1

Enter element [1,2] : 2

Enter element [1,3] : 3

Enter element [2,1] : 4

Enter element [2,2] : 5

Enter element [2,3] : 6

Transpose Matrix is :

1 4

2 5

3 6

110. Program to read a matrix and print it's diagonals.


1 #include <stdio.h>
2
3 #define MAXROW 10
4 #define MAXCOL 10
5
6 int main()
7 {
8 int matrix[MAXROW][MAXCOL];
9 int i,j,r,c;
10
11 printf("Enter number of Rows :");
12 scanf("%d",&r);
13 printf("Enter number of Cols :");
14 scanf("%d",&c);
15
16 printf("\nEnter matrix elements :\n");
17 for(i=0;i< r;i++)
18 {
19 for(j=0;j< c;j++)
20 {
21 printf("Enter element [%d,%d] : ",i+1,j+1);
22 scanf("%d",&matrix[i][j]);
23 }
24 }
25
26 /*check condition to print diagonals, matrix must be square matrix*/
27 if(r==c)
28 {
29 /*print diagonals*/
30 for(i=0;i< c;i++)
31 {
32 for(j=0;j< r;j++)
33 {
34
35 if(i==j)
36 printf("%d\t",matrix[j][i]); /*print elements*/
37 else
38 printf("\t"); /*print space*/
39 }
40 printf("\n"); /*after each row print new line*/
41 }
42 }
43 else
44 {
45 printf("\nMatrix is not a Square Matrix.");
46 }
47 return 0;
48 }

First Run:

Enter number of Rows :2

Enter number of Cols :3

Enter matrix elements :

Enter element [1,1] : 1

Enter element [1,2] : 2

Enter element [1,3] : 3

Enter element [2,1] : 4

Enter element [2,2] : 5


Enter element [2,3] : 6

Matrix is not a Square Matrix.

Second Run:

Enter number of Rows :4

Enter number of Cols :4

Enter matrix elements :

Enter element [1,1] : 1

Enter element [1,2] : 2

Enter element [1,3] : 3

Enter element [1,4] : 4

Enter element [2,1] : 5

Enter element [2,2] : 6

Enter element [2,3] : 7

Enter element [2,4] : 8

Enter element [3,1] : 9

Enter element [3,2] : 10

Enter element [3,3] : 11

Enter element [3,4] : 12

Enter element [4,1] : 13

Enter element [4,2] : 14

Enter element [4,3] : 15

Enter element [4,4] : 16

6
11

16
111.Program to find sum and subtraction of two matrices.
1 #include <stdio.h>
2
3 #define MAXROW 10
4 #define MAXCOL 10
5
6
7 /*User Define Function to Read Matrix*/
8 void readMatrix(int m[][MAXCOL],int row,int col)
9 {
10 int i,j;
11 for(i=0;i< row;i++)
12 {
13 for(j=0;j< col;j++)
14 {
15 printf("Enter element [%d,%d] : ",i+1,j+1);
16 scanf("%d",&m[i][j]);
17 }
18 }
19 }
20
21 /*User Define Function to Read Matrix*/
22 void printMatrix(int m[][MAXCOL],int row,int col)
23 {
24 int i,j;
25 for(i=0;i< row;i++)
26 {
27 for(j=0;j< col;j++)
28 {
29 printf("%d\t",m[i][j]);
30 }
31 printf("\n");
32 }
33 }
34
35 int main()
36 {
37 int a[MAXROW][MAXCOL],b[MAXROW][MAXCOL],result[MAXROW][MAXCOL];
38 int i,j,r1,c1,r2,c2;
39
40
41 printf("Enter number of Rows of matrix a: ");
42 scanf("%d",&r1);
43 printf("Enter number of Cols of matrix a: ");
44 scanf("%d",&c1);
45
46 printf("\nEnter elements of matrix a: \n");
47 readMatrix(a,r1,c1);
48
49
50
51 printf("Enter number of Rows of matrix b: ");
52 scanf("%d",&r2);
53 printf("Enter number of Cols of matrix b: ");
54 scanf("%d",&c2);
55
56 printf("\nEnter elements of matrix b: \n");
57 readMatrix(b,r2,c2);
58
59
60 /*sum and sub of Matrices*/
61 if(r1==r2 && c1==c2)
62 {
63 /*Adding two matrices a and b, and result storing in matrix result*/
64 for(i=0;i< r1;i++)
65 {
66 for(j=0;j< c1;j++)
67 {
68 result[i][j]=a[i][j]+b[i][j];
69 }
70 }
71
72 /*print matrix*/
73 printf("\nMatrix after adding (result matrix):\n");
74 printMatrix(result,r1,c1);
75
76 /*Subtracting two matrices a and b, and result storing in matrix result*/
77 for(i=0;i< r1;i++)
78 {
79 for(j=0;j< c1;j++)
80 {
81 result[i][j]=a[i][j]-b[i][j];
82 }
83 }
84
85 /*print matrix*/
86 printf("\nMatrix after subtracting (result matrix):\n");
87 printMatrix(result,r1,c1);
88
89 }
90 else
91 {
92 printf("\nMatrix can not be added, Number of Rows & Cols are Different");
93 }
94 return 0;
95 }

Enter number of Rows of matrix a: 3


Enter number of Cols of matrix a: 3

Enter elements of matrix a:

Enter element [1,1] : 11

Enter element [1,2] : 22

Enter element [1,3] : 33

Enter element [2,1] : 44

Enter element [2,2] : 55

Enter element [2,3] : 66

Enter element [3,1] : 77

Enter element [3,2] : 88

Enter element [3,3] : 99

Enter number of Rows of matrix b: 3

Enter number of Cols of matrix b: 3

Enter elements of matrix b:

Enter element [1,1] : 1

Enter element [1,2] : 2

Enter element [1,3] : 3

Enter element [2,1] : 4

Enter element [2,2] : 5

Enter element [2,3] : 6

Enter element [3,1] : 7

Enter element [3,2] : 8

Enter element [3,3] : 9


Matrix after adding (result matrix):

12 24 36

48 60 72

84 96 108

Matrix after subtracting (result matrix):

10 20 30

40 50 60

70 80 90
112. Program to find multiplication of two matrices.
1 #include <stdio.h>
2
3 #define MAXROW 10
4 #define MAXCOL 10
5
6
7 /*User Define Function to Read Matrix*/
8 void readMatrix(int m[][MAXCOL],int row,int col)
9 {
10 int i,j;
11 for(i=0;i< row;i++)
12 {
13 for(j=0;j< col;j++)
14 {
15 printf("Enter element [%d,%d] : ",i+1,j+1);
16 scanf("%d",&m[i][j]);
17 }
18 }
19 }
20
21 /*User Define Function to Read Matrix*/
22 void printMatrix(int m[][MAXCOL],int row,int col)
23 {
24 int i,j;
25 for(i=0;i< row;i++)
26 {
27 for(j=0;j< col;j++)
28 {
29 printf("%d\t",m[i][j]);
30 }
31 printf("\n");
32 }
33 }
34
35 int main()
36 {
37 int a[MAXROW][MAXCOL],b[MAXROW][MAXCOL],result[MAXROW][MAXCOL];
38 int i,j,r1,c1,r2,c2;
39 int sum,k;
40
41
42 printf("Enter number of Rows of matrix a: ");
43 scanf("%d",&r1);
44 printf("Enter number of Cols of matrix a: ");
45 scanf("%d",&c1);
46
47 printf("\nEnter elements of matrix a: \n");
48 readMatrix(a,r1,c1);
49
50
51
52 printf("Enter number of Rows of matrix b: ");
53 scanf("%d",&r2);
54 printf("Enter number of Cols of matrix b: ");
55 scanf("%d",&c2);
56
57 printf("\nEnter elements of matrix b: \n");
58 readMatrix(b,r2,c2);
59
60
61 if(r1==c2)
62 {
63 /*Multiplication of two matrices*/
64 for(i=0;i< r1;i++)
65 {
66 for(j=0;j< c1;j++)
67 {
68 sum=0;
69 for(k=0;k< r1;k++)
70 {
71 sum=sum + (a[i][k]*b[k][j]);
72 }
73 result[i][j]=sum;
74 }
75 }
76
77 /*print matrix*/
78 printf("\nMatrix after multiplying elements (result matrix):\n");
79 printMatrix(result,r1,c1);
80
81
82 }
83 else
84 {
85 printf("\nMultiplication can not be done.");
86 }
87
88
89 return 0;
90 }

Enter number of Rows of matrix a: 3

Enter number of Cols of matrix a: 3

Enter elements of matrix a:

Enter element [1,1] : 1

Enter element [1,2] : 2

Enter element [1,3] : 3

Enter element [2,1] : 4

Enter element [2,2] : 5

Enter element [2,3] : 6

Enter element [3,1] : 7

Enter element [3,2] : 8

Enter element [3,3] : 9

Enter number of Rows of matrix b: 3

Enter number of Cols of matrix b: 3

Enter elements of matrix b:

Enter element [1,1] : 1

Enter element [1,2] : 1

Enter element [1,3] : 1

Enter element [2,1] : 2

Enter element [2,2] : 2


Enter element [2,3] : 2

Enter element [3,1] : 3

Enter element [3,2] : 3

Enter element [3,3] : 3

Matrix after multiplying elements (result matrix):

14 14 14

32 32 32

50 50 50

113.Program to print lower triangle of a square matrix in C

#include <stdio.h>

#define ROW 3
#define COL 3

int main() {
int matrix[ROW][COL] = {{2,3,4},{4,5,6},{6,7,8}};

printf("Lower Triangular Matrix\n");

for(int i=0; i<3; i++) {


for(int j=0; j<3; j++) {
if(i>=j)
printf("%d ", matrix[i][j]);
else
printf("%d ", 0);
}
printf("\n");
}

return 0;
}

Output

Lower Triangular Matrix


200
450
678
114.C program to read and print an employee's detail using structure

C program to read and print an Employee’s Details using Structure - In this program, we will read
employee’s details like name, employee id and salary using structure and then print the entered values.

Employee Detail program in C

/*C program to read and print employee's record using structure*/

#include <stdio.h>

/*structure declaration*/
struct employee{
char name[30];
int empId;
float salary;
};

int main()
{
/*declare structure variable*/
struct employee emp;

/*read employee details*/


printf("\nEnter details :\n");
printf("Name ?:"); gets(emp.name);
printf("ID ?:"); scanf("%d",&emp.empId);
printf("Salary ?:"); scanf("%f",&emp.salary);

/*print employee details*/


printf("\nEntered detail is:");
printf("Name: %s" ,emp.name);
printf("Id: %d" ,emp.empId);
printf("Salary: %f\n",emp.salary);
return 0;
}

Output

Enter details :
Name ?:Mike
ID ?:1120
Salary ?:76543

Entered detail is:


Name: Mike
Id: 1120
Salary: 76543.000000
115.C program to create, declare and initialize structure

n this program, we will learn how to declare a structure with different types of variables, declare and
initialization of structure variable? Here we are not reading values from keyboard; we are assigning the
values to the structure members at the time of structure variable declaration.

#include <stdio.h>

/*structure declaration*/
struct employee{
char name[30];
int empId;
float salary;
};

int main()
{
/*declare and initialization of structure variable*/
struct employee emp={"Mike",1120,76909.00f};

printf("\n Name: %s" ,emp.name);


printf("\n Id: %d" ,emp.empId);
printf("\n Salary: %f\n",emp.salary);
return 0;
}

Output

Name: Mike
Id: 1120
Salary: 76909.000000
116.C program to demonstrate example of Nested Structure

In this program, we will learn how to declare, initialize Nested Structure (Structure within Structure)?
How to assign values/read values and access the Nested Structure members?

Here, in this example - we will create a structure dateOfBirth which will be declared inside the
structure student.

/*C program to demonstrate example of nested structure*/


#include <stdio.h>

struct student{
char name[30];
int rollNo;

struct dateOfBirth{
int dd;
int mm;
int yy;
}DOB; /*created structure varoable DOB*/
};

int main()
{
struct student std;

printf("Enter name: "); gets(std.name);


printf("Enter roll number: "); scanf("%d",&std.rollNo);
printf("Enter Date of Birth [DD MM YY] format: ");
scanf("%d%d%d",&std.DOB.dd,&std.DOB.mm,&std.DOB.yy);
printf("\nName : %s \nRollNo : %d \nDate of birth : %02d/%02d/
%02d\n",std.name,std.rollNo,std.DOB.dd,std.DOB.mm,std.DOB.yy);

return 0;
}

Output

Enter name: Mike


Enter roll number: 101
Enter Date of Birth [DD MM YY] format: 14 03 92

Name : Mike
RollNo : 101
Date of birth : 14/03/92
117.C program to demonstrate example of structure pointer (structure with pointer)*/
#include <stdio.h>

struct item
{
char itemName[30];
int qty;
float price;
float amount;
};

int main()
{

struct item itm; /*declare variable of structure item*/


struct item *pItem; /*declare pointer of structure item*/

pItem = &itm; /*pointer assignment - assigning address of itm to pItem*/

/*read values using pointer*/


printf("Enter product name: ");
gets(pItem->itemName);
printf("Enter price:");
scanf("%f",&pItem->price);
printf("Enter quantity: ");
scanf("%d",&pItem->qty);

/*calculate total amount of all quantity*/


pItem->amount =(float)pItem->qty * pItem->price;

/*print item details*/


printf("\nName: %s",pItem->itemName);
printf("\nPrice: %f",pItem->price);
printf("\nQuantity: %d",pItem->qty);
printf("\nTotal Amount: %f",pItem->amount);

return 0;
}

Output

Enter product name: Pen


Enter price:5.50
Enter quantity: 15

Name: Pen
Price: 5.500000
Quantity: 15
Total Amount: 82.500000
118./*C program to demonstrate example of structure pointer
using user define function*/

#include <stdio.h>

struct item
{
char itemName[30];
int qty;
float price;
float amount;
};

/*readItem()- to read values of item and calculate total amount*/


void readItem(struct item *i)
{
/*read values using pointer*/
printf("Enter product name: ");
gets(i->itemName);
printf("Enter price:");
scanf("%f",&i->price);
printf("Enter quantity: ");
scanf("%d",&i->qty);

/*calculate total amount of all quantity*/


i->amount =(float)i->qty * i->price;
}

/*printItem() - to print values of item*/


void printItem(struct item *i)
{
/*print item details*/
printf("\nName: %s",i->itemName);
printf("\nPrice: %f",i->price);
printf("\nQuantity: %d",i->qty);
printf("\nTotal Amount: %f",i->amount);

}
int main()
{

struct item itm; /*declare variable of structure item*/


struct item *pItem; /*declare pointer of structure item*/

pItem = &itm; /*pointer assignment - assigning address of itm to pItem*/


/*read item*/
readItem(pItem);
/*print item*/
printItem(pItem);

return 0;
}

Output

Enter product name: Pen


Enter price:5.50
Enter quantity: 15

Name: Pen
Price: 5.500000
Quantity: 15
Total Amount: 82.500000
119.C program to declare, initialize an UNION, example of UNION

#include <stdio.h>

// union declaration
union pack{
char a;
int b;
double c;
};

int main()
{

pack p; //union object/variable declaration

printf("\nOccupied size by union pack: %d",sizeof(pack));

// assign value to each member one by one other it will replace last value
p.a='A';
printf("\nValue of a:%c",p.a);

p.b=10;
printf("\nValue of b:%d",p.b);

p.c=12345.6790;
printf("\nValue of c:%f",p.c);

// see, what will happen? if u will assign values together


p.a='A';
p.b=10;
p.c=12345.6790;

// here the last value of p.c will be accessed by all members


printf("\nValue of a:%c, b:%d, c:%f",p.a,p.b,p.c);

return 0;
}

Output

Occupied size by union pack: 8


Value of a:A
Value of b:10
Value of c:12345.679000
Value of a:�, b:-377957122, c:12345.679000
120.C program to demonstrate example of structure of array.

#include <stdio.h>

struct student
{
char name [30];
int marks[ 5];
int total;
float perc;
};

int main()
{
struct student std;
int i;

printf("Enter name: ");


gets(std.name);

printf("Enter marks:\n");
std.total=0;
for(i=0;i< 5;i++){
printf("Marks in subject %d ?: ",i+1);
scanf("%d",&std.marks[i]);
std.total+=std.marks[i];
}
std.perc=(float)((float)std.total/(float)500)*100;

printf("\nName: %s \nTotal: %d \nPercentage: %.2f",std.name,std.total,std.perc);

return 0;
}

Output

Enter name: Mike


Enter marks:
Marks in subject 1? : 88
Marks in subject 2? : 98
Marks in subject 3? : 98
Marks in subject 4? : 78
Marks in subject 5? : 99

Name: Mike
Total: 461
Percentage: 92.20
121.C program to add two distances in feet and inches using structure

#include <stdio.h>

struct distance{
int feet;
int inch;
};
void addDistance(struct distance d1,struct distance d2){
struct distance d3;
d3.feet= d1.feet + d2.feet;
d3.inch= d1.inch + d2.inch;

d3.feet= d3.feet + d3.inch/12; //1 feet has 12 inches


d3.inch= d3.inch%12;

printf("\nTotal distance- Feet: %d, Inches: %d",d3.feet,d3.inch);


}

int main()
{
struct distance d1,d2;
printf("Enter first distance in feet & inches:");
scanf("%d%d",&d1.feet, &d1.inch);

printf("Enter second distance in feet & inches:");


scanf("%d%d",&d2.feet, &d2.inch);
/*add two distances*/
addDistance(d1,d2);
return 0;
}

Output

Enter first distance in feet & inches: 10 8


Enter second distance in feet & inches: 5 7
Total distance- Feet: 16, Inches: 3
122. C union program to extract individual bytes from an unsigned int

#include<stdio.h>

union tagname
{
unsigned int a;
unsigned char s[4];
};

union tagname object;

int main()
{
char i; //for loop counter

//assign an integer number


object.a=0xAABBCCDD;

printf("Integer number: %ld, hex: %X\n",object.a,object.a);


printf("Indivisual bytes: ");
for(i=3;i>=0;i--)
printf("%02X ",object.s[i]);

printf("\n");
return 0;
}

Output

Integer number: 2864434397, hex: AABBCCDD


Indivisual bytes: AA BB CC DD
123.Passing structure in function and returning structure from function program in C

#include <stdio.h>

//Lets create a structure first


struct FirstStruct
{
int Num1;
int Num2;
}FirstStruct_IP;

//function declarations
struct FirstStruct TakeUserInput(void);
void DisplayOutput(struct FirstStruct Input);

//structure object declaration


struct FirstStruct inputStruct;

int main()
{
//create a structure to get a return from TakeUserInput function
//Now use the DisplayOutput to print the input
DisplayOutput(TakeUserInput());

return 0;
}

//This function returns a structure after storing the user input into it
struct FirstStruct TakeUserInput(void)
{

printf("Enter a number: ");


scanf("%d",&inputStruct.Num1);
printf("Enter a number again: ");
scanf("%d",&inputStruct.Num2);
return inputStruct;
}
//Function taking Structure as argument
void DisplayOutput(struct FirstStruct Input)
{
printf("%d\n",((Input.Num1)+(Input.Num2)));
}

Output

Enter a number: 10
Enter a number again: 20
30
124.Calculate party expenses using C program

#include <stdio.h>
#define MAX 50 //maximum items entry

//structure definition
typedef struct item_details{
char itemName[30]; //item name
int quantity; //item quantity
float price; //per item price
float totalAmount; //total amount = quantity*price
}item;

int main(){
item thing[MAX]; //structure variable
int i,choice;
int count=0;
float expenses=0.0f;

i=0;
//infinite loop
do{
printf("Enter item details [%2d]:\n",i+1);

printf("Item? ");
fgets(thing[i].itemName,30,stdin);

printf("Price? ");
scanf("%f",&thing[i].price);

printf("Quantity? ");
scanf("%d",&thing[i].quantity);

thing[i].totalAmount=(float)thing[i].quantity*thing[i].price;
expenses += thing[i].totalAmount;
i++; //increase loop counter
count++;//increase record counter

printf("\nWant to more items (press 1): ");


scanf("%d",&choice);

getchar();

}while(choice==1);

//print all items


printf("All details are:\n");
for(i=0; i<count; i++)
{
printf("%-30s\t %.2f \t %3d \n %.2f\n",thing[i].itemName, thing[i].price,
thing[i].quantity, thing[i].totalAmount);
}
printf("#### Total expense: %.2f\n",expenses);

printf("Want to divide in friends (press 1 for yes): ");


scanf("%d",&choice);
if(choice==1)
{
printf("How many friends? ");
scanf("%d",&i);
printf("Each friend will have to pay: %.2f\n",(expenses/(float)i));
}

printf("~Thanks for using me... Enjoy your party!!!~\n");


return 0;
}

Output

Enter item details [ 1]:


Item? Beer (Kingfisher)
Price? 90.50
Quantity? 10

Want to more items (press 1): 1


Enter item details [ 2]:
Item? RUM (Old Monk)
Price? 5
Quantity? 186

Want to more items (press 1): 1


Enter item details [ 3]:
Item? R.S. Whisky
Price? 250.50
Quantity? 2
Want to more items (press 1): 0
All details are:
Beer (Kingfisher) 90.50 10 905.00
RUM (Old Monk) 186.00 5 930.00
R.S. Whisky 250.50 2 501.00

#### Total expense: 2336.00


Want to divide in friends (press 1 for yes): 1
How many friends? 6
Each friend will have to pay: 389.33

~Thanks for using me... Enjoy your party!!!~


125.C program to create, initialize, assign and access a pointer variable.

#include <stdio.h>

int main()
{
int num; /*declaration of integer variable*/
int *pNum; /*declaration of integer pointer*/

pNum=& num; /*assigning address of num*/


num=100; /*assigning 100 to variable num*/

//access value and address using variable num


printf("Using variable num:\n");
printf("value of num: %d\naddress of num: %u\n",num,&num);
//access value and address using pointer variable num
printf("Using pointer variable:\n");
printf("value of num: %d\naddress of num: %u\n",*pNum,pNum);

return 0;
}

Output

Using variable num:


value of num: 100
address of num: 2764564284
Using pointer variable:
value of num: 100
address of num: 2764564284
126.Swap two numbers using call by reference (address) in C

/*C program to swap two numbers using pointers.*/


#include <stdio.h>

// function : swap two numbers using pointers


void swap(int *a,int *b)
{
int t;
t = *a;
*a = *b;
*b = t;
}

int main()
{
int num1,num2;

printf("Enter value of num1: ");


scanf("%d",&num1);
printf("Enter value of num2: ");
scanf("%d",&num2);

//print values before swapping


printf("Before Swapping: num1=%d, num2=%d\n",num1,num2);

//call function by passing addresses of num1 and num2


swap(&num1,&num2);

//print values after swapping


printf("After Swapping: num1=%d, num2=%d\n",num1,num2);

return 0;
}

Output

Enter value of num1: 10


Enter value of num2: 20
Before Swapping: num1=10, num2=20
After Swapping: num1=20, num2=10
127.C program to change the value of constant integer using pointers

Since, we cannot change the value of a constant but using pointer we can change it, in this program we
are doing the same. Here, we have an integer constant and changing its value using pointer.

/*C program to change the value of constant integer using pointers.*/

#include <stdio.h>

int main()
{
const int a=10; //declare and assign constant integer
int *p; //declare integer pointer
p=&a; //assign address into pointer p

printf("Before changing - value of a: %d",a);

//assign value using pointer


*p=20;

printf("\nAfter changing - value of a: %d",a);


printf("\nWauuuu... value has changed.");

return 0;
}

Output

Before changing - value of a: 10


After changing - value of a: 20
Wauuuu... value has changed.

128.Consider the program

/*C program to print a string using pointer.*/


#include <stdio.h>
int main()
{
char str[100];
char *ptr;

printf("Enter a string: ");


gets(str);

//assign address of str to ptr


ptr=str;

printf("Entered string is: ");


while(*ptr!='\0')
printf("%c",*ptr++);

return 0;
}

Output

Enter a string: This is a test string.


Entered string is: This is a test string.
129.C program to read array elements and print with addresses.
#include <stdio.h>
int main()
{
int arr[10]; //declare integer array
int *pa; //declare an integer pointer
int i;

pa=&arr[0]; //assign base address of array

printf("Enter array elements:\n");


for(i=0;i < 10; i++){
printf("Enter element %02d: ",i+1);
scanf("%d",pa+i); //reading through pointer
}

printf("\nEntered array elements are:");


printf("\nAddress\t\tValue\n");
for(i=0;i<10;i++){
printf("%08X\t%03d\n",(pa+i),*(pa+i));
}

return 0;
}

Output

Enter array elements:


Enter element 01: 11
Enter element 02: 23
Enter element 03: 444
Enter element 04: 4
Enter element 05: 5
Enter element 06: 6
Enter element 07: 77
Enter element 08: 89
Enter element 09: 67
Enter element 10: 12

Entered array elements are:


Address Value
E73BF180 011
E73BF184 023
E73BF188 444
E73BF18C 004
E73BF190 005
E73BF194 006
E73BF198 077
E73BF19C 089
E73BF1A0 067
E73BF1A4 012
130.C program to read and print student details using structure pointer,
demonstrate example of structure with pointer.

#include <stdio.h>

struct student{
char name[30];
int roll;
float perc;
};

int main()
{
struct student std; //structure variable
struct student *ptr; //pointer to student structure

ptr= &std; //assigning value of structure variable

printf("Enter details of student: ");


printf("\nName ?:"); gets(ptr->name);
printf("Roll No ?:"); scanf("%d",&ptr->roll);
printf("Percentage ?:"); scanf("%f",&ptr->perc);

printf("\nEntered details: ");


printf("\nName:%s \nRollNo: %d \nPercentage: %.02f\n",ptr->name,ptr->roll,ptr->perc);

return 0;
}

Output

Enter details of student:


Name ?:Mike
Roll No ?:101
Percentage ?:89.7

Entered details:
Name:Mike
RollNo: 101
Percentage: 89.70
131.C program to print size of different types of pointer variables.
1 /*C program to print size of different types of pointer variables.*/

2 #include <stdio.h>

4 int main()
5 {

6 printf("\nsize of char pointer: %d" ,sizeof(char*));

7 printf("\nsize of int pointer: %d" ,sizeof(int*));

8 printf("\nsize of float pointer: %d" ,sizeof(float*));

9 printf("\nsize of long int pointer: %d" ,sizeof(long int*));

10 printf("\nsize of double pointer: %d\n" ,sizeof(double*));

11 return 0;

12 }

~~~~ Output depends on the system architecture,


~~~~ but each type of pointer will take same memory space ~~~

size of char pointer: 4

size of int pointer: 4

size of float pointer: 4

size of long int pointer: 4

size of double pointer: 4

132.C program to demonstrate example of double pointer (pointer to


pointer).
1 /*C program to demonstrate example of double pointer (pointer to pointer).*/

2 #include <stdio.h>

4 int main()

5 {

6 int a; //integer variable

7 int *p1; //pointer to an integer

8 int **p2; //pointer to an integer pointer

9
10 p1=&a; //assign address of a

11 p2=&p1; //assign address of p1

12

13 a=100; //assign 100 to a

14

15 //access the value of a using p1 and p2

16 printf("\nValue of a (using p1): %d",*p1);

17 printf("\nValue of a (using p2): %d",**p2);

18

19 //change the value of a using p1

20 *p1=200;

21 printf("\nValue of a: %d",*p1);

22 //change the value of a using p2

23 **p2=200;

24 printf("\nValue of a: %d",**p2);

25

26 return 0;

27 }

Value of a (using p1): 100

Value of a (using p2): 100

Value of a: 200

Value of a: 200
133. C program to demonstrate example of array of pointers.
1 /*C program to demonstrate example of array of pointers.*/

2 #include <stdio.h>

3
4 int main()

5 {

6 /*declare same type of variables*/

7 int a,b,c;

9 /*we can create an integer pointer array to

10 store the address of these integer variables*/

11 int *ptr[3];

12

13 /*assign the address of all integer variables to ptr*/

14 ptr[0]= &a;

15 ptr[1]= &b;

16 ptr[2]= &c;

17

18 /*assign the values to a,b,c*/

19 a=100;

20 b=200;

21 c=300;

22

23 /*print values using pointer variable*/

24 printf("value of a: %d, b: %d, c: %d\n",*ptr[0],*ptr[1],*ptr[2]);

25

26 /*add 10 to all values using pointer*/

27 *ptr[0] +=10;

28 *ptr[1] +=10;

29 *ptr[2] +=10;
30 printf("After adding 10\nvalue of a: %d, b: %d, c: %d\n",*ptr[0],*ptr[1],*ptr[2]);

31

32 return 0;

33 }

value of a: 100, b: 200, c: 300

After adding 10

value of a: 110, b: 210, c: 310

134. Dynamic Memory Allocation Examples using C programs


1) C program to create memory for int, char and float variable at run time.

In this program we will create memory for int, char and float variables at run time using malloc() function
and before exiting the program we will release the memory allocated at run time by using free() function.

1 /*C program to create memory for int,

2 char and float variable at run time.*/

4 #include <stdio.h>

5 #include <stdlib.h>

7 int main()

8 {

9 int *iVar;

10 char *cVar;

11 float *fVar;

12

13 /*allocating memory dynamically*/

14
15 iVar=(int*)malloc(1*sizeof(int));

16 cVar=(char*)malloc(1*sizeof(char));

17 fVar=(float*)malloc(1*sizeof(float));

18

19 printf("Enter integer value: ");

20 scanf("%d",iVar);

21

22 printf("Enter character value: ");

23 scanf(" %c",cVar);

24

25 printf("Enter float value: ");

26 scanf("%f",fVar);

27

28 printf("Inputted value are: %d, %c, %.2f\n",*iVar,*cVar,*fVar);

29

30 /*free allocated memory*/

31 free(iVar);

32 free(cVar);

33 free(fVar);

34

35 return 0;

36 }

Enter integer value: 100


Enter character value: x
Enter float value: 123.45
Inputted value are: 100, x, 123.45
2) C program to input and print text using Dynamic Memory Allocation.

In this program we will create memory for text string at run time using malloc() function, text string will
be inputted by the user and displayed. Using free() function we will release the occupied memory.

1 /*C program to input and print text

2 using Dynamic Memory Allocation.*/

4 #include <stdio.h>

5 #include <stdlib.h>

7 int main()

8 {

9 int n;

10 char *text;

11

12 printf("Enter limit of the text: ");

13 scanf("%d",&n);

14

15 /*allocate memory dynamically*/

16 text=(char*)malloc(n*sizeof(char));

17

18 printf("Enter text: ");

19 scanf(" "); /*clear input buffer*/

20 gets(text);

21
22 printf("Inputted text is: %s\n",text);

23

24 /*Free Memory*/

25 free(text);

26

27 return 0;

28 }

Enter limit of the text: 100


Enter text: I am mike from California, I am computer geek.
Inputted text is: I am mike from California, I am computer
geek.

3) C program to read a one dimensional array, print sum of all elements along with inputted array
elements using Dynamic Memory Allocation.

In this program we will allocate memory for one dimensional array and print the array elements along
with sum of all elements. Memory will be allocated in this program using malloc() and released
using free().

1 /*C program to read a one dimensional array,

2 print sum of all elements along with inputted array

3 elements using Dynamic Memory Allocation.*/

5 #include <stdio.h>

6 #include <stdlib.h>

8 int main()

9 {

10 int *arr;
11 int limit,i;

12 int sum=0;

13

14 printf("Enter total number of elements: ");

15 scanf("%d",&limit);

16

17 /*allocate memory for limit elements dynamically*/

18 arr=(int*)malloc(limit*sizeof(int));

19

20 if(arr==NULL)

21 {

22 printf("Insufficient Memory, Exiting... \n");

23 return 0;

24 }

25

26 printf("Enter %d elements:\n",limit);

27 for(i=0; i<limit; i++)

28 {

29 printf("Enter element %3d: ",i+1);

30 scanf("%d",(arr+i));

31 /*calculate sum*/

32 sum=sum + *(arr+i);

33 }

34

35 printf("Array elements are:");

36 for(i=0; i<limit; i++)


37 printf("%3d ",*(arr+i));

38

39

40 printf("\nSum of all elements: %d\n",sum);

41

42 return 0;

43 }

Enter total number of elements: 5


Enter 5 elements:
Enter element 1: 11
Enter element 2: 22
Enter element 3: 33
Enter element 4: 44
Enter element 5: 55
Array elements are: 11 22 33 44 55
Sum of all elements: 165

4) C program to read and print the student details using structure and Dynamic Memory Allocation.

In this program we will create a structure with student details and print the inputted details. Memory to
store and print structure will be allocated at run time by using malloc() and released by free().

1 /*C program to read and print the student details

2 using structure and Dynamic Memory Allocation.*/

4 #include <stdio.h>

5 #include <stdlib.h>

7 /*structure declaration*/

8 struct student
9 {

10 char name[30];

11 int roll;

12 float perc;

13 };

14

15 int main()

16 {

17 struct student *pstd;

18

19 /*Allocate memory dynamically*/

20 pstd=(struct student*)malloc(1*sizeof(struct student));

21

22 if(pstd==NULL)

23 {

24 printf("Insufficient Memory, Exiting... \n");

25 return 0;

26 }

27

28 /*read and print details*/

29 printf("Enter name: ");

30 gets(pstd->name);

31 printf("Enter roll number: ");

32 scanf("%d",&pstd->roll);

33 printf("Enter percentage: ");

34 scanf("%f",&pstd->perc);
35

36 printf("\nEntered details are:\n");

37 printf("Name: %s, Roll Number: %d, Percentage: %.2f\n",pstd->name,pstd->roll,pstd->perc);

38

39 return 0;

40 }

Enter name: Mike


Enter roll number: 1
Enter percentage: 87.50

Entered details are:


Name: Mike, Roll Number: 1, Percentage: 87.50

5) C program to read and print the N student details using structure and Dynamic Memory Allocation.

In this program we will create a structure with N number of student details and print the inputted details.
Memory to store and print structure will be allocated at run time by using malloc() and released by free().

1 /*C program to read and print the N student

2 details using structure and Dynamic Memory Allocation.*/

4 #include <stdio.h>

5 #include <stdlib.h>

7 /*structure declaration*/

8 struct student

9 {

10 char name[30];

11 int roll;
12 float perc;

13 };

14

15 int main()

16 {

17 struct student *pstd;

18 int n,i;

19

20 printf("Enter total number of elements: ");

21 scanf("%d",&n);

22

23 /*Allocate memory dynamically for n objetcs*/

24 pstd=(struct student*)malloc(n*sizeof(struct student));

25

26 if(pstd==NULL)

27 {

28 printf("Insufficient Memory, Exiting... \n");

29 return 0;

30 }

31

32 /*read and print details*/

33 for(i=0; i<n; i++)

34 {

35 printf("\nEnter detail of student [%3d]:\n",i+1);

36 printf("Enter name: ");

37 scanf(" "); /*clear input buffer*/


38 gets((pstd+i)->name);

39 printf("Enter roll number: ");

40 scanf("%d",&(pstd+i)->roll);

41 printf("Enter percentage: ");

42 scanf("%f",&(pstd+i)->perc);

43 }

44

45 printf("\nEntered details are:\n");

46 for(i=0; i<n; i++)

47 {

48 printf("%30s \t %5d \t %.2f\n",(pstd+i)->name,(pstd+i)->roll,(pstd+i)->perc);

49 }

50

51 return 0;

52 }

Enter total number of elements: 3

Enter detail of student [1]:


Enter name: Mike
Enter roll number: 1
Enter percentage: 87.50

Enter detail of student [2]:


Enter name: Jussy
Enter roll number: 2
Enter percentage: 88

Enter detail of student [3]:


Enter name: Macalla
Enter roll number: 3
Enter percentage: 98.70

Entered details are:


Mike 1 87.50
Jussy 2 88.00
Macalla 3 98.70
135. Read N strings and print them with the length program in C language

#include <stdio.h>
#include <string.h>

int main()
{
//Declare Variables
char string[10][30]; //2D array for storing strings
int i, n;

//Get the maximum number of strings


printf("Enter number of strings to input\n");
scanf("%d", &n);

//Read the string from user


printf("Enter Strings one by one: \n");
for(i=0; i< n ; i++) {
scanf("%s",string[i]);
}

//Print the length of each string


printf("The length of each string: \n");
for(i=0; i< n ; i++) {
//Print the string at current index
printf("%s ", string[i]);

//Print the length using `strlen` function


printf("%d\n", strlen(string[i]));
}

//Return to the system


return 0;
}

Output

Enter number of strings to input


3
Enter Strings one by one:
www.google.com
www.includehelp.com
www.duggu.org

The length of each string:


www.google.com 14
www.includehelp.com 19
www.duggu.org 13
136.Code to Convert String to Integer in C programming
Direct Method

#include <stdio.h>

int main()
{
unsigned char text[]="1234";
int intValue;

intValue=((text[0]-0x30)*1000)+((text[1]-0x30)*100)+((text[2]-0x30)*10)+((text[3]-0x30));
printf("Integer value is: %d",intValue);
}

Output

Integer value is: 1234


Using atoi Function

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

int main()
{
unsigned char text[]="1234";
int intValue;

intValue=atoi(text);
printf("Integer value is: %d",intValue);

return 0;
}

Output

Integer value is: 1234


Using sscanf Function

#include <stdio.h>

int main()
{
unsigned char text[]="1234";
int intValue;

sscanf(text,"%04d",&intValue);
printf("Integer value is: %d",intValue);
return 0;
}

Output

Integer value is: 1234

S-ar putea să vă placă și