0% found this document useful (0 votes)
13 views103 pages

Lab Manual C

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views103 pages

Lab Manual C

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 103

Theme: General Programs

Program No: 1
Objective:
Write a program to calculate the area of triangle using formula at=√s (s- a) (s-b) (s-c)
Logic
Given a triangle with side lenths a, b and c. Then is area can be calculated as==√s (a+b+c)/2where
s=(a+b+c)/2
Example:
If the input is:
a = 3.
b = 5.
c = 7.

Triangle area = 6.49519062

Algorithm:

1. Start
2. Enter the value of a, b and c
3. Calculate the value of s as s=(a+b+c)/2
4. Calculate the value of Area as area=sqrt(s(s-1) (s-b) (s-c)
5. Print the area
6. Stop

Program Code:

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a, b, c, s, area;
clrscr();
printf(“Enter the value of a)
scanf(%f,&a)
printf(“Enter the value of b”);
scanf(“ %f”,&b);
printf(“Enter the value of c”);
scanf(“%f ”, &d);
s = (a+b+c)/2;
area= sqrt(s*(s-a)*(s-b)*(s-c);
print(“ Area of the triangle %f”, area);
getch();

Output Window :
Program No: 2
Objective:

Basic salary of an employee is input through the keyboard. The DA is 25% of the basic salary while
the HRA is 15% of the basic salary. Provident Fund is deducted at the rate of 10% of the gross salary
(BS+DA+HRA). Program to calculate the Net Salary.

Logic:

Let the basic salary =7500


Determine the 25% DA of Basic means 25% of the 7500 as (7500*25)/100=1874
Determine the 15% HRA of Basic means15% of the 7500 as (7500*15)/100=1125
Calculate Gros salary=(Basic+DA+HRA)GrossSalary=(7500+1874+1125)=10499
Calculate the provident fund 10% of Provident= (10*Gross salry)/100=1049.9
Calculate Net Salary ,Deduct the Provident fund from gross salary, Net salary= Gross salary-
Provident=10499-1049.9=9449.1
Algorithm:

1. Start
2. Enter the value of basic
3. Compute the value of DA
4. Compute the value of HRA
5. Compute the value of Gross salary
6. Compute the value of Provident fund
7. Compute the value net salary
8. End

Program Code:

#include<stdio.h>
#include<conio.h>
void main()
{
float basic, da,hra,pf, gross_salary, net_salary;
clrscr();
printf(“Enter the Basic Salary of employee)
scanf(%f,& basic)
da = (basic*25)/100;
hra = (basic*15)/100;
gross_salary = basic+da+hra;
pf = (10*gross_salary)/100;
net_salary = gross_salary-pf;
Printf(“ Net salary= %f”, net_salary);
getch();
}

Output Window:
THEME: Conditional Branching

Program No:1

Objective:

Write a program to determine the roots of quadratic equation.

Logic:

The general form of a quadratic equation is (ax^2 + bx + c = 0). The formula to find the roots of a
quadratic equation is given as follows

x = [-b +/- sqrt (-b^2 - 4ac)]/2a


The discriminant of the quadratic equation is
d= (b^2 - 4ac).
Depending upon the nature of the discriminant, the roots can be found in different ways.

1. If the discriminant is positive, then there are two distinct real roots.
2. If the discriminant is zero, then the two roots are equal.
3. If the discriminant is negative, then there are two distinct complex roots.

For example, consider the following equation

2x^2 8x + 3 = 0.

a = 2, b = -8, c = 3

Discriminant value, d =b^2 - 4ac = 8^2 - 4*(-8) *3 = 40

The discriminant value is positive. Hence, the roots are real and distinct.

r1 = (-b +d)/ 2a= (8 +40) /2*2 = 2.3875

r2 = (b +d)/ 2a =(-8 +40) /2*2 = -0.3875

r1 = 2.3875andr2 = -0.3875 are the two roots.


Algorithm:

1. Start
2. Enter the value of a, b and c
3. Calculate the value of discriminant d= b2-4ac
4. If discriminate > 0 calculate first_root=-b+sqrt(discriminant)/2*a and second_root = - b-
sqrt(discriminant)/2*a and print both roots
Else If discriminate = 0 calculate first_root = second_root = -b/2*a and print both roots
Else If discriminant <0 calculate real_part = -b/2*a, imag_part = sqrt(-discriminant)/2*a
and print the roots
5. Stop
Program Code:

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
double a, b, c, discriminant, first_root, second_root, real_part, imaginary_part ;
clrscr();
printf(“Enter the value of a)
scanf(%lf,&a)
printf(“Enter the value of b”);
scanf(“ %lf”,&b);
printf(“Enter the value of c”);
scanf(“%lf ”, &d);
discriminante= b^2-4*a*c;
if(discriminat>0)
{
first_root=-b+sqrt(discriminant)/2*a;
second_root = - b-sqrt(discriminant)/2*a;
printf(Fist root of equation is %lf”, first_root);
printf(second root of equation is %lf, Second_root);
}
else if( discriminant = = 0)
{
first_root = second_root = -b/2*a;
printf(Fist root of equation is %lf”, first_root);
printf(Second root of equation is %lf, Second_root);
}
else {
real_part = -b/2*a;
imag_part = sqrt(-discriminant)/2*a;
printf(First root of the equation is %lf+%lf”, real_part, imag_part);
printf(Second root of the equation is %lf-%lf”, real_part, imag_part);
getch();
}
}
Output Window :
Program No:2

Objective:

Write a program to find the largest of three numbers using nested if else

Logic:

Given three numbers A, B and C


The task is to find the largest number among the three.
Input: A = 2, B = 8, C = 1
Output: Largest number = 8
Input: A = 231, B = 4751, C = 75821
Output: Largest number = 75821

Algorithm:

1. Start
2. Read the three numbers to be compared, as A, B and C.
3. Check if A is greater than B.
3.1 If true, then check if A is greater than C.
3.1.1 If true, print 'A' as the greatest number.
3.1.2 If false, print 'C' as the greatest number.
3.2 If false, then check if B is greater than C.
3.1.1 If true, print 'B' as the greatest number.
3.1.2 If false, print 'C' as the greatest number.
4. Stop

Program Code:

#include<stdio.h>
#include<conio.h>
void main()
{
float a, b, c:
clrscr();
printf(“Enter the value of a)
scanf(%f,&a)
printf(“Enter the value of b”);
scanf(“ %f”,&b);
printf(“Enter the value of c”);
scanf(“%f ”, &d);
if(a>b && a>c)
{
printf( a is largest of three number %/f”, a);
}
if(b>c && b>a)
{
printf( b is largest of three number %/f”, b);
}

else
printf( c is largest of three number %/f”, c);
getch();
}

Output Window :
Program No: 3

Objective:

Write a program to receive marks of physics, chemistry & maths from user & check its eligibility for
course if
a) Marks of physics > 40
b) Marks of chemistry > 50
c) Marks of math’s > 60
d) Total of physics & math’s marks > 150 or
Total of three subjects marks > 200

Logic:

Take the marks of Physics , Chemistry and Math from user


Case1: if Marks of Physics >40
Case2: if Marks of Chemistry >50
Case3: if Marks of Math >60
Case 4: if Addition of Physics and maths marks >150
Case5: if Addition of Physics , chemistry and Maths>200
If all five cases are satisfied then candidate is eligible .

Algorithm:

1. Start
2. Input marks of Physics , Chemistry and Math from user
3. If Marks of Physics is greater than 40 and
4. If Marks of Chemistry is greater than 50 and
5. If Marks of Maths is greater than 60 and
6. If Total marks of Physics and Maths is greater than 150
7. If total marks of Physics , Chemistry and Maths is greater than 200
8. If all step 9, 10, 11 12 13 is satisfied than candidate is eligible for course admission
9. Otherwise not eligible for admission in course
10. end

Program Code:

#include<stdio.h>
#include<conio.h>

void main()
{
int physics, chemistry, maths, total1,total2;
clrscr();
printf(“ Enter the marks of Physics”);
scanf(“%d”, & physics);

printf(“ Enter the marks of Chemistry”);


scanf(“%d”, & chemistry);

printf(“ Enter the marks of Maths”);


scanf(“%d”, & maths);
toatl1=physics+maths;
total2=physics+chemistry+maths;

if(physics>40)

if(chemistry>50)

if(maths>60)

if(total1>150|| total2>200)

printf(“ Applicants is eligible for admission”);

else
printf(“ Applicants is not eligible for admission”);
else
printf(“ Applicants is not eligible for admission”);
else
printf(“ Applicants is not eligible for admission”);
else
printf(“ Applicants is not eligible for admission”);
}

getch()
}
Output Window:
Program -4
Objective:

Write a program to find the value of y for a particular value of n. The a, x, b, n is input by user
(switch)
if n=1 y=ax%b
if n=2 y=ax2+b2
if n=3 y=a-bx
if n=4 y=a+x/b

Logic:

Use the switch feature to choose one condition from multiple condition.
Case 1: n=1, calculate using formula y=ax%b
Case2: n=2 calculate using y=ax2+b2
Case3: n=3 calculate using y=a-bx
Case 3 n=4 calculate using y=a+x/b
Example: Input: If a=5, b=1, x=1, n=3
Output=4.0 beacause as n=3 case 3 will be executed as y=a-bx=5-1*1=4
Algorithm:

1. Start
2. Enter the value of a, b,x and n ,
3. Apply the switch case to select only one match case.
4. If case label is n=1 then compute using formula y=ax%b
5. If case label is n=2 then compute using formula y=ax2+b2
6. If case label is n=1 then compute using formula y=a-bx
7. If case label is n=1 then compute using formula y=a+x/b
8. Stop

Program Code:

#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, x , n;
float y;
clrscr();
printf(" Eneter the value of a\n");
scanf("%d",&a);
printf(" Eneter the value of b\n");
scanf("%d",&b);
printf(" Eneter the value of x\n");
scanf("%d",&x);
printf(" Eneter the value ofn\n");
scanf("%d",&n);
switch(n)
{
case 1:
y=(a*x%b);
printf(" The value of y is=%f" );
break;
case 2:
y=(a*x*2+b*2);
printf( " The value of y is=%f" ,y);
break;
case 3:
y=(a-b*x);
printf( " The value of y is=%f" ,y);
break;
case 4:
y=(a+x/b);
printf( " The value of y is=%f" ,y);
break;
}
getch();
}

Output Window :
Theme – 3-Loop Constructs

Program No:1

Objective:

Write a program to construct a Fibonacci series upto n terms.

Logic:

Fibonacci series is a series of numbers where the current number is the sum of previous two terms.
For Example: 0, 1, 1, 2, 3, 5, 8, 13, 21...
Fibonacci series algorithm
If you look to the given series very carefully you will find a specific pattern i.e. the current number is the
sum of previous two numbers.
Fibonacci series : 0, 1, 1, 2, 3, 5, 8, 13, 21...
1 is the sum of 0 + 1
2 is the sum of 1 + 1
3 is the sum of 2 + 1
5 is the sum of 3 + 2
and so on....
Example:
Input upper limit: 10
Output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Algorithm:
1. Start
2. Declare variables i, a,b, c,term
3. Initialize the variables, a=0, b=1, and c =0
4. Enter the number of terms of Fibonacci series to be printed
5. Print First two terms of series
6. Repeat steps until i<term-2
c=a+b
a=b
b=c
increase value of i each time by 1
print the value of c
7. End

Program Code:

#include<stdio.h>
#include<conio.h>
void main()
{
int a ,b ,c , i, terms;
clrscr();
printf(“ Enter the number the terms”);
scanf(“%d”, &terms);
a = 0;
b= 1;
c=0;
printf(“Fibonacci series is :\n”);
for(i=0;i<+terms;i++)
{
printf(“\t%d”,c);
a=b;
b=c;
c=a+b;
getch();
}

Output Window :
Program No:2

Objective:

Write a program to find whether the number is Armstrong number.

Logic:

If Sum of cubes of every digit of number is equal to itself number is known as Armstrong Number like
0, 1, 153, 370, 371 and 407
153= 13+53+33
Determine Remainder of Given number as Remainder=Number%10.Then calculate the last digit of
given number as Number=Number/10.
Algorithm:

1. Start
2. Input any integer number
3. Set Original number = Number
4. Calculate the Remainder= Original number %10
5. Compute the Sum=Sum+Remainder*Remainder*Remainder
6. Original number=Original number /10;
7. Repeat steps 4 ,5 and 6 while Number>0
8. If Sum= Number
Print Number is Armstrong
Otherwise print number is not Armstrong.
9. Stop

Program Code:

#include<stdio.h>
#include<conio.h>

void main()
{
int Number, Original_number, Remainder, Sum=0;
clrscr();
printf("enter the number of three digit integer\n");
scanf("%d",& Number);
Original_number=Number;
while(Original_number!=0)
{
Remainder=Original_number%10;
Sum=Sum+Remainder*Remainder*Remainder;
Original_number=Original_number/10;
}
if(Sum==Number)
printf(" %d is an armstrong number",Number);
else
printf("%d is not an armstrong number", Number);
getch();
}

Output Window :
Program No:3

Objective:

Write a program to generate sum of series 1!+2!+3!+ n!.

Logic:

Apply loop to Compute the summation of every Integer value.Initialize the value of sum=0 and loop
counter by 1.At each iteration factorial of each term and then compute Sum.
Example:
Input: Terms=
So,
Sum=1! +2! +3! +4! +5!=1+2+6+24+120=153
Output:153

Algorithm:

1. Start
2. Enter the value of terms ie n
3. Calculate the value of P=P*I
4. Calculate the value Sum=Sum+P
5. Repeat steps 3 ,4 for i=0 to term
6. Print the value of Sum
7. Stop

Program Code:

#include<stdio.h>
#include<conio.h>

void main()
{
long i , term, Sum=0, P=1;
printf( “Enter the terms”)
scanf(“%d”, &term);
for(i=0;i<term;i++)
{
P= P*i;
Sum=Sum+P;
}
printf(“ The sum of the series is: %d”,Sum);
getch();
}

Output Window :
Program -4

Objective:

Write a program to find the sum of following series 1-X1/1!+X2/2!-…………Xn/n!.

Logic:

The sum of following series can be calcoulated as 1-X1/1!+X2/2!-…………Xn/n!.


Apply nested loop to Compute the summation of every Integer value.Initialize the value of sum=0 and
loop counters.At each iteration compute factorial of each term which will be divided by x*n and then
compute Sum.
Example:
Input: terms=4,x=2
So,
Sum=1-(1*2/1! +2*2/2! +2*3/3! +2*4/4!)

Algorithm:
1. Start
2. Enter the value of x and n
3. Repeat steps 4 to 10 for i=1 to n
4. Intialize fact=1
5. Repeat step 6 for j=1 to i
6. Fact=Fact*j
7. term=term*(-1);
8. m=term*(x*i)/fact;
9. Calculate the value of sum=sum+m
10. Print the values of sum
11. End

Program Code:

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
double sum=1, n,,x, fact,i,j,m,term=1 ;
clrscr();
printf(“Enter the value of n)
scanf(%f,&n)
printf(“Enter the value of x”);
scanf(“ %f”,&x);
for(i=1,i<n,i++)
{
Fact=1;
for(j=1,j<=I;j++)
{
Fact = Fact*j;
}
term=term*(-1);
m=term*(x*i)/fact;
Sum=sum+m;
}
printf(The sum of the series is %d”, Sum);
getch();
}

Output Window:
Program-5

Objective:

Write a program to print the entire prime no between 1 and 300.

Logic:
A number one has not any other divisors except 1 and itself. In other word we can say which has only
two divisors 1 and number itself. For example: 5
Their divisors are 1 and 5
Example:
Input lower limit: 1
Input upper limit: 10
Output prime numbers between 1-10: 2, 3, 5, 7
Prime number is a positive integer greater than 1 that is only
divisible by 1 and self. Example: 2, 3 , 5, 7, 11 are the first five
prime numbers

Algorithm

1. Start
2. set max=300
3. for num=1 to max
set flag= 0
4. for i=2 to num/2
if (num%i==0)
set flag=1
go to step 5
5. if flag==0 and num! =1
print “num”
6. Stop

Program Code:

#include<stdio.h>
#include<conio.h>
int main()
{
int num, max=300, i, flag;
//create a for loop to run a counter from 1 to 300.

for(num=1;num<=max;num++)
{
flag=0;
//second for loop to check the number from 1 to 300 is prime or not.
for(i=2;i<=num/2;i++)
{
if(num%i==0)
{
flag=1;
break;
}
}

if(flag==0 && num!=1) // we remove 1 from this condition


printf("%d\t", num);
}
}

Output Window :
Program-6

Objective:
Write a program to print out all the Armstrong number between 100 and 500.

Logic:

An armstrong number is a number which equal to the sum of the cubes of its individual digits. For
example, 153 is an armstrong number as −
153 = (1)3 + (5)3 + (3)3
153 = 1 + 125 + 27
153 = 153

Algorithm:

1. Start
2. Set number=100,
3. Repeat steps 4 to 9 while number<=1000
4. digit1 = number - ((number / 10) * 10);
5. digit2 = (number / 10) - ((number / 100) * 10);
6. digit3 = (number / 100) - ((number / 1000) * 10);
7. temp = (digit1 * digit1 * digit1) + (digit2 * digit2 * digit2) + (digit3 * digit3 * digit3);
8. if (temp == number)
print temp
9. number= number+1
10. End

Program:

#include <stdio.h>
void main()
{
int number, temp, digit1, digit2, digit3;

printf("Print all Armstrong numbers between 1 and 1000:\n");


number = 100;
while (number <= 999)
{
digit1 = number - ((number / 10) * 10);
digit2 = (number / 10) - ((number / 100) * 10);
digit3 = (number / 100) - ((number / 1000) * 10);
temp = (digit1 * digit1 * digit1) + (digit2 * digit2 * digit2) + (digit3 * digit3 * digit3);
if (temp == number)
{
printf("\n Armstrong no is:%d", temp);
}
number++;
}
}

Output Window:
Program-7

Objective :

Write a program to draw the following figure:


321 *
21 **
1 ***

Logic:

C Programs to print Star Series, and Different Pattern Printing Programs in C Language. Pattern printing
programs contains Star Pattern, Number Pattern and Character Pattern printing. A pyramid is a
polyhedron formed by connecting a polygonal base and a point, called the apex. Each base edge and
apex form a triangle, called a lateral face. It is a conic solid with polygonal base.
Example:

Algorithm:

1. Start
2. Get the number of rows from the user
3. Iterate through the given number using outer for loop to handle the number of rows
4. Iterate through the inner loop to handle the number of columns. Inner loop iteration depends on the
values of the outer loop
5. Print asterisk or number in pyramid or diamond pattern using the print() function
6. Add a new line after each row (after each iteration of outer for loop) to display the pattern
appropriately
7. Stop

Program Code:
#include <stdio.h>
int main()
{
int i, j, n;
printf("Enter n: ");
scanf("%d", &n);
for(i=n; i>=1; i--)
{
for(j=i; j>=1; j--)
{
printf("%d", j);
}
printf("\n");
}
return 0;
}

Output Window:

Program Code :

#include <stdio.h>
void main()
{
int i, j, n, k = 0;
printf("Enter Number of line ");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
for(j=1; j<=n-i; j++)
printf(" ");
for(j=1; j<=i; j++)
printf("* ");
printf("\n");
}
}
Output Window:
Program-8

Objective:

Write a program to receive a five-digit no and display as like 24689:


2
4
6
8
9

Logic:

Given a number N, the task is to write a C program to print all digits of the number N in their original
order.

Examples:

Input: N = 12
Output: 1, 2

Input: N = 1032
Output: 1, 0, 3, 2

Algorithm:

1. Start
2. Input num, rev, d;
3. Enter the last number of series
4. Initialize rev=0
5. Repeat steps 6 to 8owhile num!=0
6. d=num%10;
7. rev=rev*10+d;
8. num=num/10;
9. Repeat steps 10 to 13 while rev!=0
10. d=rev%10;
11. Print value of d
12. rev=rev/10;
13. End

Program Code :

#include<stdio.h>
int main()
{
int num,rev,d;
printf("Enter the last number of series:\n");
scanf("%d",&num);
rev=0;
while(num!=0)
{
d=num%10;
rev=rev*10+d;
num=num/10;
}
while(rev!=0)
{
d=rev%10;
printf("%d\n",d);
rev=rev/10;
}
}

Output Window:
Theme -4: Modular Programming

Program -1

Objective:

Write a function that return sum of all the odd digits of a given positive no entered through keyboard.

Logic:

Even number can be divided by 2. The remainder after dividing an even number by 2 is zero. Odd number
can not be divided by 2. The remainder after dividing an Odd number by 2 is one.
For example: Sum of Even digits of number 6547 is 10 and Sum of Odd digits of number 6547 is 12. The
below given C program is used to find the Sum of odd digits and Sum of even digits present in the given
Integer number using if statement. Kindly check out to find the Sum of odd digits and Sum of even digits
present in the given Integer number.

Algorithm:

1. Start
2. Create a function which return integer and having one integer parameter
3. In function: sum=0 Loop while parameter n != 0
4. temp = n % 10
5. if temp is odd then sum = sum + temp
6. After completion of loop return sum
7. Stop

Program code:

#include <stdio.h>
int sumodd(int);
int main()
{
int n, sum;
printf("Enter the number : ");
scanf("%d", &n);
sum = sumodd(n);
printf("Sum of odd digit : %d", sum);
return 0;
}
int sumodd(int n)
{
int d,s=0;
while(n!=0)
{
d=n%10;
if(d%2==0)
s=s+d;
n=n/10;
}
return s;
}

Output Window:
Program -2

Objective: Write a program to print area of rectangle using function & return its value to main function

Logic:

The area of a rectangle is written as,


A=l*b
Where,
A=area
l=length
b=breadth
Example: If l=2 and b=3 then area of triangle will be a=l*b+2*3=6

Algorithm:

1. Start
2. Create a function which return integer value and having two integer parameters L and B for
length and breadth respectively
3. In function return L * B
4. Stop

Program code:

#include <stdio.h>
int areaRectangle(int, int);
int main()
{
int l, b, area;
printf("Enter the length : ");
scanf("%d", &l);
printf("Enter the width : ");
scanf("%d", &b);
area = areaRectangle(l, b);
printf("The area of the rectangle : %d", area);
return 0;
}
int areaRectangle(int length, int width)
{
return length * width;
}
Output Window:
Program -3

Objective:

Write a program to calculate the factorial for given number using function.

Logic:

In mathematics, there are n! ways to arrange n objects in sequence. "The factorial n! gives the number of
ways in which n objects can be permuted."
For example:
factorial is 2! = 2 x 1 = 2 There are 2 different ways to arrange the numbers 1 through 2. {1,2,} and
{2,1}.
factorial is 4! = 4 x 3 x 2 x 1 = 24 There are 24 different ways to arrange the numbers 1 through 4.
{1,2,3,4}, {2,1,3,4}, {2,3,1,4}, {2,3,4,1}, {1,3,2,4}, etc.

factorial is 5! = 5 x 4 x 3 x 2 x 1 = 120
0 factorial is a definition: 0! = 1. There is exactly 1 way to arrange 0 objects.

Algorithm:

1. Start
2. Create a function which return an integer value and having only one parameter n as number
whose factorial is to be find out
3. In function calculate factorial by loop
4. Return factorial calculated
5. Stop

Program code:

#include <stdio.h>
int fact(int);
void main()
{
int no,factorial;
printf("Enter a number to calculate it's factorial\n");
scanf("%d",&no);
factorial=fact(no);
printf("Factorial of the num(%d) = %d\n",no,factorial);
}
int fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}

Output Window:
Program-4

Objective: Write a program to find sum of Fibonacci series using function.

Logic:

Given a number positive number n, find value of f0 + f1 + f2 + …. + fn where fi indicates i’th Fibonacci
number. Remember that f0 = 0, f1 = 1, f2 = 1, f3 = 2, f4 = 3, f5 = 5, …
Examples :
Input : n = 3
Output : 4
Explanation : 0 + 1 + 1 + 2 = 4

Input : n = 4
Output : 7
Explanation : 0 + 1 + 1 + 2 + 3 = 7

Algorithm:

1. Start
2. Create a function which return integer value and having only one parameter n as number of
Fibonacci terms
3. In function calculate sum of Fibonacci series by loop
4. Return Sum calculated
5. Stop

Program code:

#include <stdio.h>
int main(void) {
int i, n, first = 0, second = 1, sum = 1, third;
printf (" Enter the range \n");
scanf( "%d", &n);
for(i = 2; i < n; i++)
{
third = first + second;
sum = sum + third;
first = second;
second = third;
}
printf("Sum of Fibonacci series for given range is %d", sum);
return 0;
}
Output Window:
Program -5

Objective: Write factorial function & use the function to find the sum of series S=1!+2!+ n!.

Logic:

Sum of series 1*1! + 2*2! + …….+ n*n!


Given n, we need to find sum of 1*1! + 2*2! + ……..+ n*n!

Examples:

Input: 1
Output: 1

Input: 3
Output: 23
1 * 1! + 2 * 2! + 3 * 3! = 1 + 4 + 18 = 23

Algorithm:

1. Start
2. Create a factorial function
3. In Main block: Sum =0 a for loop of i from 1 to n
4. Temp=call factorial function for i Sum=Sum + Temp
5. After Loop termination print Sum
6. Stop

Program code:

#include <stdio.h>
int fact(int);
void main()
{
int n,sum=0,i;
printf("Enter a terms\n");
scanf("%d",&n);
for(i=1; i<=n;i++)
{
sum=sum+fact(i);
}

printf("Sum of series(%d) = %d\n",n,sum);


}
int fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}

Output Window:
Program-6

Object:

Write a program to find factorial of a given number using recursion.

Logic:

Factorial is the product of an integer with it's all below integer till 1. In mathematic representation
factorial represents by ‘!’ sign.

For Example:
Factorial of 6 is:
6! = 720 [That is equivalent to 6*5*4*3*2*1 =120]

Input any number: 6


Output: 720
The factorial of any number can be recursively given by: fact(0) = 1 {Base case}

fact(num) = num * fact(num-1) {Numbers greater than 1}

Algorithm:

1. Start
2. Input n
3. Create a function fact(n) which return integer value and having only one parameter n as number
whose factorial to be calculated
4. In function fact(n) calculate factorial using recursion
if n>1
return n*fact(n-1)
else
return 1
5. Print factorial returned by the function
6. Stop

Program Code:

#include<stdio.h>
long int fact_rec(int n);
int main()
{
int n;
clrscr();
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, fact_rec(n));
getch();
return 0;
}
long int fact_rec(int n)
{
if (n>=1)
return n*fact_rec(n-1);
else
return 1;
}

Output window :
Program No.-7

Objective:

Write a program to find sum of digits of a number using recursion.

Logic:

Sum of a digits of number means if an integer number is given for eg: 1678 its sum will be equivalent to
1+6+7+8=22.

Logic of this program can be divided in three basic steps: Find the last digit of number by performing
modular division.
Add the last digit just found above to sum.
Remove the last digit from number by dividing the number by 10.

Repeat the above three steps till the number becomes 0 and you will be left with the sum of digits.

Algorithm:

1. Start
2. Input n
3. Create a function sum_of_digits(n) which return integer value and having only one parameter n
as number whose digits need to be calculated
4. In function sum_of_digits(n) calculate factorial using recursion
If n == 0
Return 0
Else
Return (n % 10 + sum_of_digit(n / 10))
5. Print sum of digits returned by the function
6. Stop

Program Code:

#include <stdio.h>
#include<conio.h>

int sum_of_digit(int n)

{
if (n == 0)
return 0;
return (n % 10 + sum_of_digit(n / 10));
}

int main()
{
int num,result;
clrscr();
printf(“Enter any number”);
scanf(“%d”,&num);
result = sum_of_digit(num);
printf("Sum of digits in %d is %d\n", num, result);
getch();
return 0;

Output Window:
Program No.-8

Objective:

Write a program to find GCD of given numbers using recursion.

Logic:

GCD(HCF) of two numbers is the largest number that divides both of them. For eg: GCD OF 98 and 56
is 14.

This program takes two positive integers as input from the user and calculates GCD using recursion

Algorithm:

1. Start
2. Input n1, n2
3. Create a function GCD (n1, n2) which return integer value and having only two parameters as
numbers whose GCD needs to be calculated
4. In function GCD (n1, n2) calculate GCD using recursion
If (n2! = 0)
Return GCD (n2, n1 % n2)
Else
Return n1
5. Print GCD returned by the function
6. Stop

Program Code:
#include <stdio.h>
#include<conio.h>
int GCD(int n1, int n2);

int main()
{
int n1, n2;
clrscr();

printf("Enter two positive integers: ");


scanf("%d %d", &n1, &n2);
printf("G.C.D of %d and %d is %d.", n1, n2, GCD(n1, n2));
return 0;
}

int GCD(int n1, int n2) {


if (n2 != 0)
return GCD(n2, n1 % n2);
else
return n1;
}

Output Window:
Program -9

Objective:

Write a program to convert binary number into decimal.

Logic:

Given a decimal number we can obtain its binary equivalent by continuously dividing decimal number
until the result becomes 0 and obtaining its remainder at each division.
For eg: (9)10 =(1001)2

9/2=4 rem=1
4/2=2 rem=0
2/2=1 rem=0
1/2=0 rem=1

And taking remainder digits from bottom to top.

Algorithm:

1. Start
2. Input decimalnum
3. Create a function decimaltobinary(decimalnum) which returns binary equivalent value and
having only one parameter as number whose binary equivalent needs to be calculated
4. In function GCD (n1, n2) calculate while decimalnum! =0
rem = decimalnum%2
decimalnum = decimalnum / 2
binarynum = binarynum + rem*temp
temp = temp * 10
return binary number
5. Print binary number returned by the function
6. Stop

Program Code:
#include <stdio.h>
#include <math.h>

long decimalToBinary(int decimalnum)


{
long binarynum = 0;
int rem, temp = 1;

while (decimalnum!=0)
{
rem = decimalnum%2;
decimalnum = decimalnum / 2;
binarynum = binarynum + rem*temp;
temp = temp * 10;
}
return binarynum;
}

int main()
{
int decimalnum;
printf("Enter a Decimal Number: ");
scanf("%d", &decimalnum);
printf("Equivalent Binary Number is: %ld", decimalToBinary(decimalnum));
return 0;

}
Program -10

Objective: Write a program to convert binary number into decimal.

Logic:

Given a binary number we can obtain its decimal equivalent by multiplying its bits with increasing
power of two and adding them .For eg: (1001)2=(9)10 [23*1+22*0+21*0+20*1=9]
In this program binary bits are fetched using modulus operator and divison operator is also used.

Algorithm:

1. Start
2. Input binary number n
3. Create a function convert(n) which returns decimal equivalent value and having only one
parameter as number.
4. In function convert (n) initialize dec = 0, i = 0 and calculate while n! = 0
rem = n % 10
n /= 10
dec += rem * pow(2, i)
++i
5. Print decimal number returned by the function
6. Stop

Program Code:

#include <math.h>
#include <stdio.h>
int convert(long long n);
int main() {
long long n;
printf("Enter a binary number: ");
scanf("%lld", &n);
printf("%lld in binary = %d in decimal", n, convert(n));
return 0;
}
int convert(long long n) {
int dec = 0, i = 0, rem;
while (n != 0) {
rem = n % 10;
n /= 10;
dec += rem * pow(2, i);
++i;
}
return dec;
}

Output Window:
Theme-5: Array

Program-1

Objective:
Write a program to delete duplicate element in a list of 10 elements & display it on screen

Logic:

If elements of the array are: 1, 2, 3, 5, 1, 5, 20, 2, 12, 10 All unique elements in the array are: 3, 20, 12,
10. Given an array containing 10 elements we will store its elements in another array one by one and
checking whether it’s already present or not by comparing it with all the inserted elements in second
array and if present then we will not store it in second array. After all iterations final array will not
contain duplicate elements.

Algorithm:

1. Start
2. Declare variables c, d,count,n
3. Declare two array say A and B. A will hold the original values and B will hold unique elements.
4. Initialize count=0.
5. Enter size of array ie n
6. Enter elements in array A.
7. Repeat steps 7 and 9 for c=0 to c<n
8. Repeat step 8 for d=0 to d<count
9. If a[c]equals to b[d] then go to step 9
10. If d equals to count, then b[count] = a[c] and increment value of count by 1
11. Print the unique array B.
12. Stop

Program Code:

#include <stdio.h>
int main()
{
int n, a[100], b[100], count = 0, c, d;
clrscr();
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &a[c]);
for (c = 0; c < n; c++)
{
for (d = 0; d < count; d++)
{
if(a[c] == b[d])
break;
}

if (d == count)
{
b[count] = a[c];
count++;
}
}
printf("Array obtained after removing duplicate elements:\n");
for (c = 0; c < count; c++)
printf("%d\n", b[c]);
getch();
return 0;
}

Output Window:
Program-2

Objective:

Write a program to merge two sorted array & no element is repeated during merging.

Logic:

Take two sorted array let a and b. Take 3rd empty array say c. Now take three variables i,j,k for a,b,c
respectively.Compare a[i]with b[j] and insert smallest of both in c[k] now only increase k and either of i
or j depend on from which array smallest element came.

Algorithm:

1. Start
2. Declare three matrices a,b and c and initialize necessary variables i,j,k
3. Enter size of two matrices ie a and b
4. Enter the sorted elements of both matrices row wise using loops
5. Compare a[i]with b[j] and insert smallest of both in c[k].
6. Increase k and either i or j depending on from which array element came.
7. Print merged elements
8. Stop

Program Code:

#include <stdio.h>
#include<conio.h>
void main()
{ int array1[50], array2[50], array3[100], m, n, i, j, k = 0;
clrscr();
printf("\n Enter size of array Array 1: ");
scanf("%d", &m);
printf("\n Enter sorted elements of array 1: \n");
for (i = 0; i < m; i++)
{
scanf("%d", &array1[i]);
}
printf("\n Enter size of array 2: ");
scanf("%d", &n);
printf("\n Enter sorted elements of array 2: \n");
for (i = 0; i < n; i++)
{
scanf("%d", &array2[i]);
}
i = 0; j = 0;
while (i < m && j < n)
{ if (array1[i] < array2[j])
{ array3[k] = array1[i];
i++;
}
else
{
array3[k] = array2[j];
j++;
}
k++;
}
if (i >= m)
{
while (j < n)
{
array3[k] = array2[j];
j++;
k++;
}
}
if (j >= n)
{ while (i < m)
{ array3[k] = array1[i];
i++;
k++;
}
}
printf("\n After merging: \n");
for (i = 0; i < m + n; i++)
{
printf("\n%d", array3[i]);
}
getch();
}
Program :3

Objective: Write a program to find sum of diagonal elements of a square matrix

Logic:

If the array elements


are: 1 2 3 4 5 6 7 8 9
Output: Sum of diagonal elements = 15

Diagonal elements of matrix

Main diagonal of a matrix A is a collection of elements Aij Such that i = j.

Algorithm:
1. Start
2. Enter elements in array A.
3. Print entered matrix
4. Repeat Step 5 for i=0 to i<row
5. Repeat Step 6 for j=0 to j<col
6. If i equals to j, then calculate sum=sum+mat[i][j]
7. Print sum of diagonal elements.
8. Stop

Program Code:

#include<stdio.h>
void main()
{
int mat[12][12];
int i,j,row,col,sum=0;
clrscr();
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d",&row,&col);
printf("Enter the elements of the matrix\n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
scanf("%d",&mat[i][j]);
}
} printf("The matrix\n");
for(i=0;i<row;i++)
{ for(j=0;j<col;j++)
{
printf("%d\t",mat[i][j]);
}
printf("\n");
}
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
if(i==j)
{
sum=sum+mat[i][j];
}
}
}
printf("The sum of diagonal elements of a square matrix = %d\n",sum);
getch();
}

Output Window:

Program :4

Objective: Write a program to find the transpose of a given matrix & check whether it
is symmetric or not.

Logic:

Symmetric matrix is a square matrix which is equal to its transpose. All symmetric matrix must be a
square matrix.

A symmetric matrix A is defined as: A = AT


Example: If elements of the matrix is:

123
245
358

Output: Given matrix is symmetric matrix.

Algorithm:

13. Start
14. Take two array say A and B. A will hold the original values and B will hold the reversed values.
15. Read elements in array A.
16. Set i=size - 1, j=0 (Where size is the size of array).
17. Set B[j] = A[i]
18. Set j = j + 1 and i = i - 1.
19. Repeat Step 4-5 till i>=0.
20. Print the reversed array in B.
21. If transpose is equal to the original Matix then print matrix is symmetric otherwise asymmetric.
22. Stop

Program Code:

#include<stdio.h>
#include<conio.h>
int main()
{
int c, d, a[10][10], b[10][10], n, temp;
clrscr();
printf("Enter the dimension of the matrix: \n");
scanf("%d", &n);
printf("Enter the %d elements of the matrix: \n",n*n);
for(c = 0; c < n; c++)
for(d = 0; d < n; d++)
scanf("%d", &a[c][d]);
for(c = 0; c < n; c++)
for(d = 0; d < n; d++)
b[d][c] = a[c][d];

// printing the original matrix


printf("The original matrix is: \n");
for(c = 0; c < n; c++)
{
for(d = 0; d < n; d++) {
printf("%d\t", a[c][d]);
}
printf("\n");
}

printf("\nThe Transpose matrix is: \n");


for(c = 0; c < n; c++) // to iterate the rows
{
for(d = 0; d < n; d++) // to iterate the columns
{
printf("%d\t", b[c][d]);
}
printf("\n");
}

// checking if the original matrix is same as its transpose


for(c = 0; c < n; c++) // to iterate the rows
{
for(d = 0; d < n; d++) // to iterate the columns
{
/*
even if they differ by a single element,
the matrix is not symmetric
*/
if(a[c][d] != b[c][d])
{
printf("Matrix is not Symmetric\n");
exit(0); // a system defined method to terminate the program
}
}
}

/*
if the program is not terminated yet,
it means the matrix is symmetric
*/
printf("\nMatrix is Symmetric");

getch();
return 0;
}
Output Window:
Program :5

Objective: Write a program to print the multiplication of two N*N (Square) matrix.

Logic: If matrix 1 = 1
23
456
789
And matrix 2 =
987
654
321
Product of both matrices =
30 24 18
84 69 54
138 114 90
Multiplication of matrices is different from simple Scalar multiplication of matrix in C. Two matrices
can be multiplied only and only if number of columns in the first matrix is same as number of rows in
second matrix. Multiplication of two matrices can be defined as

Algorithm:

9. Start
10. Declare variables and initialize necessary variables
11. Enter the element of matrices by row wise using loops
12. Check the number of rows and column of first and second matrices
13. If number of rows of first matrix is equal to the number of columns of second matrix, go to step 6.
Otherwise, print matrix multiplication is not possible and go to step 3.
14. Multiply the matrices using nested loops.
15. Print the product in matrix form.
16. Stop
Program Code:

#include <stdio.h>
#include<conio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
clrscr();
printf("Enter number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
printf("Enter elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);
if (n != p)
printf("The multiplication isn't possible.\n");
else
{
printf("Enter elements of second matrix\n");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
printf("Product of the matrices:\n");
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);
printf("\n");
}
}
getch();
return 0;
}
Output Window:

Program :4

Objective:

Write a program in C to check whether the given string is a palindrome or not.


Logic:

Palindrome string is a special string which reads same from backward or forward such as madam, mom,
eye, dad etc.
Logic to check palindrome string
The basic idea behind checking palindrome is if it can be read same from forward and backward then it
is palindrome else not. Here in the below algorithm we will traverse the string character by character in
both directions at the same time if they are equal then the string is palindrome.
Example:
Input String: madam
Output: Palindrome string

Algorithm:

1. Start
2. Declare variables begin, middle, end, length = 0
3. Declare array text[] elemnets
4. Enter string in array using gets function
5. Find length of the string
6. Set end=length-1 and middle=length/2
7. Repeat steps 7 to 10 for begin=0 to begin<middle
8. If text[begin] is not equal to text[end] print string is not palindrome and go to step 12
9. end=end-1
10. begin=begin+1
11. If begin equals to end print string is palindrome.
12. Stop

Program Code:

#include <stdio.h>
int main()
{
char text[100];
int begin, middle, end, length = 0;
clrscr();
printf("Enter string\n");
gets(text);

while (text[length] != '\0')


length++;
end = length - 1;
middle = length/2;
for (begin = 0; begin < middle; begin++)
{
if (text[begin] != text[end])
{
printf("Not a palindrome.\n");
break;
}
end--;
}
if (begin == middle)
printf("Palindrome.\n");
getch();
return 0;
}

Output Window :
Program :5

Objective : Write program to sort the array of character (String) in alphabetical order like STRING in
GINRST.

Logic:
If a user inputs a string "bbac" then the output will be "abbc", so output string will contain characters in
alphabetical order. We assume input string contains only lower case alphabets. We count how many
times characters 'a' to 'z' appear in the input string and then create another string that contains characters
'a' to 'z' as many times as they appear in the input string.

Algorithm:

1. Start
2. Declare a character array, temp,i,j,n
3. Input string
4. Calculate string length
5. Repeat step 6 for i=0 to n-1
6. Repeat steps for j-i+1 to n
If string[i]>string[j]
temp = string[i]
string[i] = string[j]
string[j] = temp
7. Print sorted string
8. Stop

Program Code:

#include <stdio.h>
#include <string.h>
int main () {
char string[15] ;
char temp;
int i, j,n;
clrscr();
printf("Enter any string\n");
scanf("%s",string);
printf("\nString before sorting - %s \n", string);
n = strlen(string);
for (i = 0; i < n-1; i++)
{
for (j = i+1; j < n; j++)
{
if (string[i] > string[j])
{
temp = string[i];
string[i] = string[j];
string[j] = temp;
}
}
}

printf("String after sorting - %s \n", string);


getch();
return 0;
}

Output Window :
Program No.-6

Objective:

Write a program to remove all the blank space from the string & print it, also count the no of characters.

Logic:

A string is nothing but an array of characters. The value of a string is determined by the terminating
character. he strings entered here is as follows:” hello how are you “
As you can see, there are quite a few blank spaces in the string entered above.
Hence, the string becomes like this after removing all the blank spaces:“hellohowareyou”

Algorithm:

1. Start
2. Declare variables i,k, character array
3. Read the user entered string using gets(s) function.
4. Intialize k=0.
5. The for loop iterates through the string until the end of the string becomes to null.
s[i]=s[i+k].
If the element at s[i] is equal to white space or tab then increase the k value and decrease
the i value.
Shift the elements right to white space or tab, to one position left as s[i]=s[i+k].
6. After removing the blank spaces to print the string.
7. Stop

Program Code:

#include <string.h>
#includestdio.h>
int main()
{
char s[50];
int i,k=0;
clrscr()
printf("Enter the string : ");
gets(s);
for(i=0;s[i];i++)
{
s[i]=s[i+k];
if(s[i]==' '|| s[i]=='\t')
{
k++;
i--;
}

}
printf("string after removing all blank spaces:");

printf("%s",s);

getch();
return 0;
}

Output Window :
Program No.-6

Objective:

Write a program to store the following string “zero”, “one” “five”. Print the no in words, given in figure
as 3205

Logic:

The idea is to traverse through every digit of the number and use switch-case. Since there are only ten
possible values for digits, ten cases can be defined inside a switch block. For each digit, its corresponding
case block will be executed and that digit will get printed in words.

Example: Input-3478

Output: three four seven eight

Algorithm :-

Input number from user. Store it in some variable say num.

Extract last digit of given number by performing modulo division by 10. Store the result in a variable say
digit = num % 10.

Switch the value of digit found above. Since there are 10 possible values of digit i.e. 0, 1, 2, 3, 4, 5, 6, 7,
8, 9 hence, write 10 cases. Print corresponding word for each case.

Remove last digit from num by dividing it by 10 i.e. num = num / 10.

Repeat step 2 to 4 till number becomes 0.

Program code:

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

int main()
{
int n, num = 0, digits;

/* Input number from user */


printf("Enter any number to print in words: ");
scanf("%d", &n);

/* Find total digits in n */


digits = (int) log10(n);
/* Store reverse of n in num */
while(n != 0)
{
num = (num * 10) + (n % 10);
n /= 10;
}

/* Find total trailing zeros */


digits = digits - ((int) log10(num));

/* Extract last digit of number and print corresponding number in words


till num becomes 0 */
while(num != 0)
{
switch(num % 10)
{
case 0:
printf("Zero ");
break;
case 1:
printf("One ");
break;
case 2:
printf("Two ");
break;
case 3:
printf("Three ");
break;
case 4:
printf("Four ");
break;
case 5:
printf ("Five ");
break;
case 6:
printf ("Six ");
break;
case 7:
printf ("Seven ");
break;
case 8:
printf ("Eight ");
break;
case 9:
printf ("Nine ");
break;
}

num /= 10;
}

/* Print all trailing zeros */


while(digits)
{
printf ("Zero ");
digits--;
}
getch ();
return 0;
}

Output Window:
Theme-6: Structures

Objective:
Write a program to compare two given dates. To store a date uses a structure that contains three
members namely day, month and year. If the dates are equal, then display message equal otherwise
unequal.

Logic:

First create a structure with day, month and year as its elements. Input two dates from user.Compare
both dates and if day, month, year all three of first date is equal to respective day, month, year of second
date then print equal else print unequal.

Example: If user inpus date 1=12-12-20 and date 2=12-12-20 then we can check that both dates are
same and message will be printed as equal.

Algorithm:

1. Start
2. Create a structure with day, month and year as its elements.
3. Take two inputs from user.
4. Compare both dates and if day, month, year all three of first date is equal to respective day,
month, year of second date then print equal else print unequal.
5. Stop

Program Code:

include<stdio.h>
#include<conio.h>
struct ddate
{
int day;
int month;
int year;
};
int main()
{
struct date d1,d2;
clrscr();
printf("\nEnter first date,month,year:");
scanf("%d%d%d",&d1.day,&d1.month,&d1.year);
printf("\nEnter second date,month,year:");
scanf("%d%d%d",&d2.day,&d2.month,&d2.year);
if((d1.day==d2.day)&&(d1.month==d2.month)&&(d1.year==d2.year))
printf("\nEQUAL");
else
printf("\nUNEQUAL");
getch();
return 0;
}

Output Window:
Program :2

Objective:

Define a structure that can describe a hotel. It should have the member that includes the name,
address, grade, room charge and number of rooms. Write a function to print out hotel of given grade
in order of room charges.

Logic:

First create a structure with hotel name, address, grade, room charge, number of room as it members.Take
values of all the members and store it in array of structure .Sort the array of structure by room charge.Take
grade from user to display hotel.Display all hotel having grade is equal to input grade.

Algorithm:

1. Start
2. Create a structure with element of hotel name, address, grade, room charge , number of room
3. Take Input from user
4. Sort the array of structure by room charge
5. Take grade from user to display hotel
6. Display all hotel having grade is equal to input grade
7. Stop

Program Code:

#include <stdio.h>
struct hotel
{
char name[20];
char add[20];
int grade;
int arc;
int rooms;
};
void output();
void out();
struct hotel inn[]={
{"PLAZA","G-99,DELHI",3,4500,50},
{"MYUR","E-45,NOIDA",4,5000,100},
{"RAJDOOT","H-44,DELHI",2,4000,50},
{"SAMRATH","B-75,BOMBAY",5,6000,200},
{"SURYA","A-77,NOIDA",1,3500,150}
};
void main()
{
int go;
clrscr();
printf("Enter 1 for grade search\n");
printf("Enter 2 to search by charge:");
scanf("%d",&go);
switch(go)
{
case 1: output();
break;
case 2: out();
break;
default:printf("Wrong input");
break;
}
getch();
}
void output()
{
int gr,i;
printf("Enter Grade 1 to 5:");
scanf("%d",&gr);
if(gr>=1||gr<=5)
{
for(i=0;i<=4;i++)
{
if(inn[i].grade==gr)
printf("Hotel Name: %s\nAddress:%s\nGrade:%d\nAverage Room charge:%d\n\
Number of Rooms:%d",inn[i].name,inn[i].add,inn[i].grade,inn[i].arc,inn[i].rooms);
}
}
else
printf("Wrong grade input!");
}
void out()
{
int ch,i=0;
printf("Enter the Room charges not greater than 6000:");
scanf("%d",&ch);
while(i<5)
{
if(inn[i].arc<ch)
printf("Hotel Name: %s\nAddress:%s\nGrade:%d\nAverage Room charge:%d\n\
Number of Rooms:%d\n",inn[i].name,inn[i].add,inn[i].grade,inn[i].arc,inn[i].rooms);
i++;
}
}

Output Window:
Program :3

Objective:

Define a structure called cricket with player name, team name, batting average, for 50 players & 5
teams. Print team wise list contains names of player with their batting

Logic:

First of all a structure will be created containg player name, team name, batting average as its
memebers and then input is provided b the user and data is sorted according to the team nameand gets
printed.

Algorithm:

1. Start
2. Create a structure with name of the player, name of team and average of batting as its
members
3. Input data of 50 players from user.
4. Sort the structure array as per name of team.
5. Player name and batting average will get printed.
6. Stop

Program Code:

#include<stdio.h>
#include<conio.h>
#include<string.h>
struct cricket
{ char P_Name[20]; char T_Name[20]; float B_Ave; };
void main()
{ struct cricket s[5],t;
int i,j,n=3;
float p;
clrscr();
printf("Enter Data Of %d Player\n",n);
for(i=0;i<n;i++)
{
printf("\nEnter Player Name,Team Name And Bating Average
For Player %d :- \n",i+1);
scanf("%s %s %f",s[i].P_Name,s[i].T_Name,&p);
s[i].B_Ave=p;
}
for(i=1;i<=n-1;i++)
{
for(j=0;j<=n-i;j++)
{
if(strcmp(s[j-1].T_Name,s[j].T_Name)>0)
{
t=s[j-1]; s[j-1]=s[j]; s[j]=t; } } }
printf("\nAfter Teamwise Sorting...Player List Is");
for(i=0;i<n;i++)
{
printf("\n%-20s %-20s
%.2f",s[i].P_Name,s[i].T_Name,s[i].B_Ave);
}
getch();
}

Output Window:
Theme-Application of Pointers

Program -1

Objective:

Write a c program to copy & count the character content of one file to another file.
Logic:
A File can be used to store a large volume of persistent data. Like many other languages’ 'C' provides
the following file management functions,

 Creation of a file
 Opening a file
 Reading a file
 Writing to a file
 Closing a file
In this program we will copy a file to another file, firstly you will specify a file to copy. We will
open the file and then read the file that we wish to copy in "read" mode and target file in "write"
mode.

Algorithm:
1. Start
2. Input file path of source and destination file.
3. Open source file in r (read) and destination file in w (write) mode.
4. Read character from source file and write it to destination file using fputc().
5. Repeat step 3 till source file has reached end.
6. Close both source and destination file.
7. Stop

Program Code:
#include <stdio.h>
#include <stdlib.h> // For exit()

int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
clrscr();
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
// Open one file for reading
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}

printf("Enter the filename to open for writing \n");


scanf("%s", filename);

// Open another file for writing


fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}

// Read contents from file


c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}

printf("\nContents copied to %s", filename);

fclose(fptr1);
fclose(fptr2);
getch();
return 0;
}
Output window:
Program 2
Objective:

Write a program to take 10 integers from file and write square of these integer in other file.
Logic:
A File can be used to store a large volume of persistent data. Like many other languages’ 'C' provides
the following file management functions,

 Creation of a file
 Opening a file
 Reading a file
 Writing to a file
 Closing a file
To write this program first we need to open a file in read mode and second file in write mode. After
that start scanning the numbers from 1st file and then write this in second file by making square of
each numbers. After that close both files.

Algorithm:

1. Start
2. Open 1st file in read mode and 2nd file in write mode
3. Scan number from 1st file and write it in 2nd file by squaring it
4. Close both files.
5. Stop
Program Code :

#include<stdio.h>
#include<conio.h>
void main()
{
FILE * f,*s;
int a;
f=fopen(“abc.txt”,”r”)
s=fopen(“xyz.txt”,”w”)
while((fscanf(f,”%d”,&a)!=EOF)
{
fprintf(s,”%d”,a*a);
}
fclose(f);
sclose(s);
}
Output Window:
Program-3

Objective:

Write a program to read number from file and then write all ‘odd’ number to
file ODD.txt & all even to file EVEN.txt.

Logic:

To write this program first we need to have the basic understanding of all the file functions like
fopen(), fclose() etc. For this first open the file in read mode using read command then identify even
and odd number file using write command by using if condition. According to condition differentiate
the file then close the files properly.

Algorithm :

1. Open main file in read mode


2. Open even_number file and odd_number file in write mode
3. Start scanning number in main file
4. If (number % 2 ==0) then write that number in even_number file else write
5. it in odd_number file
6. Close all the file properly.

Program Code:

#include<stdio.h>
#include<conio.h>
#include<process.h>

void main()
{
int a,n,i;
FILE *fp1,*fp2,*fp3;
clrscr();
fp1=fopen("DATA","w");

if(fp1==NULL)
{
printf("File could not open!!");
exit(0);
}

printf("How many numbers?");


scanf("%d",&n);
printf("Enter contents of DATA file:");
for(i=0;i<n;++i)
{
scanf("%d",&a);
putw(a,fp1);
}

fclose(fp1);

fp1=fopen("DATA","r");
fp2=fopen("ODD","w");
fp3=fopen("EVEN","w");

if(fp1==NULL||fp2==NULL||fp3==NULL)
{
printf("File could not open!!");
exit(0);
}

while((a=getw(fp1))!=EOF)
{
if(a%2!=0)
putw(a,fp2);
else
putw(a,fp3);
}

fclose(fp1);
fclose(fp2);
fclose(fp3);

fp2=fopen("ODD","r");
fp3=fopen("EVEN","r");

if(fp2==NULL||fp3==NULL)
{
printf("File could not open!!");
exit(0);
}

printf("Contents of ODD file:");


while((a=getw(fp2))!=EOF)
printf("\t%d" ,a);

printf("\nContents of EVEN file:");


while((a=getw(fp3))!=EOF)
printf("\t%d",a);
fclose(fp2);
fclose(fp3);
getch();
}

Output Window:
Program-4

Objective:

Write a program to print all the prime number, between 1 to 100 in file prime.txt.

Logic:

To write this program first we need to write a function to check for prime number. For this first we
have to open a file in write mode then condition for primality will be checked. After that file will be
closed.

Algorithm:
1. Start
2. Create a function to check prime number
3. Open file in write mode
4. Initiate a loop 1 to 100
5. Check every number for prime if it is prime then write it in file already open
6. After loop termination close the file properly to save.
7. Stop

Program Code :

#include <stdio.h>
#include<conio.h>
int is_prime(int n)
{
int d;
for (d = 2; d < n; d++)
{
if (n % d == 0)
break;
}
return (d == n) ? 1 : 0;
}
int main ()
{
char fname[] = "prime.txt";
FILE *fp;
int m, n, i;
clrscr();
/* add prime numbers in a given range to primes.dat file */
printf("Enter range : ");
scanf ("%d %d", &m, &n);
fp=fopen(fname,"w");
printf("writing in prime.txt file\n");
for (i = m; i <= n; i++)
{
if (is_prime(i))
fprintf(fp, "%d ", i);
}
fclose (fp);
/* display contents of primes.dat file */
fp = fopen(fname,"r");
printf("Prime numbers in primes.dat file:\n");
while (fscanf (fp, "%d", &i) != EOF)
printf("%d ", i);
fclose (fp);
getch();
return 0;
}

Output Window:
Program-5
Objective:

Write the following C program using pointer


a) To sort the list of numbers through pointer
b) To reverse the string through pointer.

Logic:
To write this program first we need to make use of calloc or malloc functions for memory block.
After that input list will be provided. Then we will apply the sorting algorithm using pointers and
then use reverse function and print the result.

Algorithm:
1. Start
2. Make a block of memory using calloc or malloc
3. Input the elements
4. Then apply bubble sort same as above just use pointer here
5. For reverse start a loop from 1st element to middle element and swap each element with
element from last like 1st with last, 2nd with 2nd last, 3rd with 3rd last and so on.
6. Stop
Program Code :

a) To sort the list of numbers through pointer


#include <stdio.h>
#include <conio.h>
#include <alloc.h>
void main()
{
int n,*p,i,j,temp;
clrscr();
printf("\nHOW MANY NUMBER: ");
scanf("%d",&n);
p=(int *) malloc(n*2);
if(p==NULL)
{
printf("\nMEMORY ALLOCATION UNSUCCESSFUL");
exit();
}
for(i=0;i<n;i++)
{
printf("\nENTER NUMBER %d: ",i+1);
scanf("%d",p+i);
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(*(p+i)<*(p+j))
{
temp=*(p+i);
*(p+i)=*(p+j);
*(p+j)=temp;
}
}
}
printf("\nTHE SORTED NUMBERS ARE:\n");
for(i=0;i<n;i++)
printf("%d ",*(p+i));
getch();
}

Output Window:

b) To reverse the string through pointer.


#include<stdio.h>
int string_length(char*);
void reverse(char*);
main()
{
char string[100];
printf("Enter a string\n");
gets(string);
reverse(string);
printf("Reverse of entered string is \"%s\".\n", string);
return 0;
}
void reverse(char *string)
{
int length, c;
char *begin, *end, temp;
length = string_length(string);
begin = string;
end = string;
for ( c = 0 ; c < ( length - 1 ) ; c++ )
end++;
for ( c = 0 ; c < length/2 ; c++ )
{
temp = *end;
*end = *begin;
*begin = temp;
begin++;
end--;
}
}
int string_length(char *pointer)
{
int c = 0;
while( *(pointer+c) != '\0' )
c++;
return c;
}
Output Window:
Program-6

Objective:

Write a program to find the largest no among 4 (Can be extended to up to any number of elements) integers
array using dynamic memory allocation

Logic:

Given an array arr[] consisting of N integers, the task is to find the largest element in the given
array using Dynamic Memory Allocation.

Examples:

Input: arr[] = {4, 5, 6, 7}


Output: 7

Explanation:
The largest element present in the given array is 7.

Algorithm:

1. Start
2. Take N elements and a pointer to store the address of N elements
3. Allocate memory dynamically for N elements.
4. Store the elements in the allocated memory.
5. Traverse the array to find the largest element among all the numbers by comparing the values using
pointers.
6. Stop

Program Code:

#include <stdio.h>
#include <stdlib.h>
// Function to find the largest element
// using dynamic memory allocation
void findLargest(int* arr, int N)
{
int i;
// Traverse the array arr[]
for (i = 1; i < N; i++) {
// Update the largest element
if (*arr < *(arr + i)) {
*arr = *(arr + i);
}
}

// Print the largest number


printf("\n\nLargest element among fouris %d ", *arr);
}

int main()
{
int i, N = 4;
int* arr;
clrscr();
// Memory allocation to arr
arr = (int*)calloc(N, sizeof(int));

// Condition for no memory


// allocation
if (arr == NULL) {
printf("No memory allocated");
exit(0);
}
*(arr + 0) = 14;
*(arr + 1) = 12;
*(arr + 2) = 19;
*(arr + 3) = 20;
// Function Call
findLargest(arr, N);
getch();
return 0;
}

Output Window:
Program-7

Objective:

Using Dynamic Memory Allocation, write a program to find the transpose of given matrix.

Logic:
Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose
of A[][] is obtained by changing A[i][j] to A[j][i].

Algorithm:
1. Start
2. Declare and initialize a two-dimensional array a.
3. Calculate the number of rows and columns present in the matrix and store it variables rows and cols
respectively.
4. Declare another array t with reversed dimensions i.e t[cols][rows]. Array t will be used to store the
elements of the transposed matrix.
5. Loop through the array a and convert its rows into columns of matrix t using
t[ i ][ j ] = a[ j ][ i ];
6. Finally, display the elements of matrix t.
7. Stop

Program Code:

#include<stdio.h>
#include<stdlib.h>
int main()
{
int *transpose,i,j,r,c; //declaring pointers
printf("\n How many rows and columns in the matrix:- ");
scanf(" %d %d",&r,&c);
//allocating memory by using dynamic memory allocation
transpose=(int*)calloc(r*c,sizeof(int));
printf("\n Enter the elements:- ");
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
scanf("%d",transpose+(i*c+j)*sizeof(int));
}
// You can achieve the same result by using pointer concept
printf("\n The transpose of matrix is:- \n");
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
printf("%5d",*(transpose+(j*c+i)*sizeof(int)));
printf("\n");
}
return 0;
}

Output Window:
Program-8

Objective:

Write a program to find the factorial of given number using command line argument.
Logic:

Given a number, the task is to find the Factorial of this number using Command Line Arguments. Factorial of a
non-negative integer is the multiplication of all integers smaller than or equal to n.
Examples:
Input: 3
Output: 6
1*2*3=6

Algorithm:

1. Start
2. Take integer variable A
3. Assign value to the variable
4. From value A upto 1 multiply each digit and store
5. Final stored value is factorial of A.
6. Stop

Program Code:

#include <stdio.h>
#include <stdlib.h> /* atoi */
// Function to find factorial of given number
unsigned int factorial(unsigned int n)
{
int res = 1, i;
for (i = 2; i <= n; i++)
res *= i;
return res;
}

int main(int argc, char* argv[])


{
int num, res = 0;
// Check if the length of args array is 1
if (argc == 1)
printf("No command line arguments found.\n");
else {

// Get the command line argument and


// Convert it from string type to integer type
// using function "atoi( argument)"
num = atoi(argv[1]);

// Find the factorial


printf("%d\n", factorial(num));
}
return 0;
}

Output Window:
Program-9

Objective:

Write a program to find the sum of digits of a 5-digit number using command line argument.

Logic:

If the input is 98, the variable sum is 0 initially


98%10 = 8 (% is modulus operator, which gives us the remainder when 98 is divided by 10).
sum = sum + remainder
so sum = 8 now.
98/10 = 9 because in C language, whenever we divide an integer by another one, we get an integer.
9%10 = 9
sum = 8 (previous value) + 9
sum = 17
9/10 = 0.
So finally, n = 0, the loop ends; we get the required sum.

Algorithm:

1. Start
2. Since the number is entered as Command line Argument, there is no need for a dedicated
input line
3. Extract the input number from the command line argument
4. This extracted number will be in String type.
5. Convert this number into integer type and store it in a variable, say num
6. Declare a variable to store the sum and set it to 0
7. Repeat the next two steps till the number is not 0
8. Get the rightmost digit of the number with help of remainder ‘%’ operator by dividing it with
10 and add it to sum.
9. Divide the number by 10 with help of ‘/’ operator
10. Print or return the sum.
11. Stop

Program Code:
#include <stdio.h>
#include <stdlib.h> /* atoi */

// Function to Find the sum of digits


int findSumOfDigits(int num)
{

// Variable to store the


// the sum of digits
int sum = 0;

// Traverse through the number digit by digit


while (num > 0) {

// Add the last digit of num


// to the sum
sum = sum + (num % 10);

// Remove the last digit from the num


num = num / 10;
}

// Return the sum


return sum;
}

// Driver code
int main(int argc, char* argv[])
{

int num;

// Check if the length of args array is 1


if (argc == 1)
printf("No command line arguments found.\n");
else {

// Get the command line argument and


// Convert it from string type to integer type
// using function "atoi( argument)"
num = atoi(argv[1]);

// Find the sum of digits and print it


printf("%d\n", findSumOfDigits(num));
}
return 0;
}

Output Window:

You might also like