Académique Documents
Professionnel Documents
Culture Documents
LabManual
ComputerEngineeringandInformationTechnology
IIISemester/KScheme
PreparedBy
K.ManiRaj M.Sc.,M.Phil.,&P.Vinitha M.Sc M.Phil
Lecturer,
DepartmentofCE/IT,
M.S.P.V.LPolytechnicCollege,
Pavoorchatram.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page1
1A CelsiustoFahrenheitConversionandviceversa
Aim:
To write a C program to convert the given temperature in degree
centigrade to Fahrenheit and vice versa.
Flow chart:
Start
Read C
F=9.0/5.0*c+32
Print F
Read F
C=5.0/9.0*(F-32)
Print C
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page2
Algorithm:
1. Read the temperature in degree Centigrade.
2. Convert the Centigrade to Fahrenheit using the formula
F=9/5*c+32
3. Print the Celsius and Fahrenheit value.
4. Read the temperature in degree Fahrenheit.
5. Convert the Fahrenheit to Centigrade using the formula
C=5/9*(F-32)
6. Print the Fahrenheit and Celsius value.
7. Stop
Program:
/* Program to convert Centigrade to Fahrenheit and vice versa */
#include <stdio.h>
#include<conio.h>
void main()
{
float
c,f;
clrscr();
/*To convert Centigrade to Fahrenheit*/
printf("Enter the temperature in centigrade:");
scanf("%f",&c);
f=9.0/5.0*c+32;
printf("\n\t%.2f Centigrade=%.2f Fahrenheit",c,f);
/*To convert Fahrenheit to centigrade*/
printf("\n\nEnter the temperature in Fahrenheit:");
scanf("%f",&f);
c=5.0/9.0*(f-32);
printf("\n\t%.2f Fahrenheit=%.2f Centigrade",f,c);
getch();
}
Output:
Enter the temperature in centigrade:45
45.00 Centigrade=113.00 Fahrenheit
Enter the temperature in Fahrenheit:114
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page3
1B
SimpleInterestandCompoundInterestCalculation
Aim:
To write a C program to find the simple interest and Compound interest
for the Amount (P), Rate of Interest (R) and Number of years (N)
Flowchart:
Start
Read P,N,R
SI=(P*N*R)/100
CI=P*(1+R/100)^N-P
Print SI,CI
Stop
Algorithm:
1. Read Principal (P), Rate of Interest (R) and Number of years (N).
2. Calculate Simple Interest (SI) and Compound Interest using the
formula
SI=(P*N*R)/100
CI=P * ((1+R)/100)^N P
3. Display the result.
4. Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page4
Program:
/* Program to calculate Simple Interest and Compound Interest */
#include<conio.h>
#include<stdio.h>
#include<math.h>
void main()
{
double p,n,r,si,ci,x;
clrscr();
printf("Enter the principal:Rs ");
scanf("%lf",&p);
printf("Enter rate of interest:");
scanf("%lf",&r);
printf("Enter number of years:");
scanf("%lf",&n);
/* To calculate Simple Interest*/
si=p*n*r/100;
/* To calculate Compound Interest*/
ci=pow((1+r/100),n)*p-p;
/* Display the result*/
printf("\n\nSimple interest =Rs %.2lf\n\n",si);
printf("Compound Interest =Rs %.2lf",ci);
getch();
}
Output:
Enter the principal:Rs 1000
Enter rate of interest:3
Enter number of years:5
Simple interest =Rs 150.00
Compound Interest =Rs 159.27
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page5
1C
Toperformarithmeticoperationoftwonumbers
Aim:
To write a program to read two numbers and print the sum, difference,
product and quotient of the two numbers.
Algorithm:
1. Read the numbers a,b;
2. Calculate
Sum=a+b
Difference=a-b
Product=a*b
Quotient=a/b
3. Print sum, difference, product and the quotient.
4. Stop
Flowchart:
Start
Read A,B
Sum=A+B
Diff=A-B
Pro=A*B
Quo=A/B
Print Sum,Diff,
Pro,Quo
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page6
Program:
/* Program to find sum, difference, product and quotient */
#include<conio.h>
#include<stdio.h>
void main()
{
float a,b,sum,diff,pro,quo;
clrscr();
printf("Enter the value for A:");
scanf("%f",&a);
printf("Enter the value for B(B<>0):");
scanf("%f",&b);
sum=a+b;
diff=a-b;
pro=a*b;
quo=a/b;
printf("\n\tThe sum of %.2f and %.2f
= %.2f",a,b,sum);
= %.2f",a,b,pro);
= %.2f",a,b,quo);
getch();
}
Output:
Enter the value for A:7
Enter the value for B(B<>0):5
The sum of 7.00 and 5.00
= 12.00
= 35.00
= 1.40
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page7
Viva Questions:
1) What are the various arithmetic operators?
+ Addition
-
Subtraction
* Multiplication
/ Divison
% modulus
2) What is an arithmetic expression?
An arithmetic expression is a combination operators and operands.
3) What are the various relational operators?
<
Less than
>
Greater than
Equal
!=
Not equal
- Logical AND
||
- Logical OR
- Logical NOT
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page8
Ex2AIdentificationofEvenandOddnumber
Aim:
To write a program to find whether the given number is even or odd.
Flowchart:
Start
Read N
R=N%2
False
True
If R=0
Print Even
Print Odd
Stop
Algorithm:
1. Read the number N.
2. Find the remainder of N divided by 2 using the Modulus operator
(N%2);
3. If the remainder is zero
The number is Even number
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page9
Otherwise
The number is Odd number
4. Print the result.
5. Stop.
Program:
/* To find whether the number is even or odd*/
#include<conio.h>
#include<stdio.h>
void main()
{
int n,r;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
r=n%2;
if(r= =0)
printf("\n\tThe given number %d is even",n);
else
printf("\n\tThe given number %d is odd",n);
getch();
}
Output 1:
Enter a number:8
The given number 8 is even
Output 2:
Enter a number:-7
The given number -7 is odd
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page10
2B
TodisplaystudentsGrade
Aim:
To write a C program to read the mark of the student and display grade
based on the following norms:
>=75 Grade A , >=50 and <75 Grade B , >=25 and <50 Grade C
<25 Grade F
Flowchart:
Start
Read average
mark (avg)
True
If avg>=75
Print Grade A
False
True
If avg>=50
Print Grade B
False
True
If avg>=75
Print Grade C
Print Grade C
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page11
Algorithm:
1. Read the average mark of the student.
2. If the mark is >=75 print GRADE A.
3. If the mark is between 50 to 75 print GRADE B.
4. If the mark is between 25 to 50 print GRADE C.
5. If the mark is less than 25 print GRADE F.
6. Stop.
Program:
/* To display the grade of the student */
#include<stdio.h>
#include<conio.h>
void main()
{
float avg;
clrscr();
printf("Enter the average mark of the student:");
scanf("%f",&avg);
if(avg>=75)
printf("\n\tThe student's grade - A");
else if(avg>=50)
printf("\n\tThe student's grade - B");
else if(avg>=25)
printf("\n\tThe student's grade - C");
else
printf("\n\tThe student's grade -F");
getch();
}
Output 1:
Enter the average mark of the student:78
The student's grade - A
Output 2:
Enter the average mark of the student:50
The student's grade B
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page12
Output 3:
Enter the average mark of the student:30
The student's grade - C
Output 4:
Enter the average mark of the student:24
The student's grade -F
Viva Questions:
1) What is a decision making statement?
Decision making statement is used to break the normal flow of the
program and execute part of the statement based on some condition
2) What are the various decision making statements available in C ?
If statement
If ..else statement.
Nested if statement
Switch statement
3) Write the program logic to find biggest among three without using
, =
return (a>b) ? (a>c ? a:c) : (b>c ? b: c)
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page13
Aim:
3A
TocheckforperfectNumber
Aim:
To write a C program to find whether the given number is perfect number
or not.
A number is a perfect number if the sum of the factors of the number
other than itself is equal to that number.
Example: 28=1+2+4+7+14 is a perfect number.
Algorithm:
1. Read the number N.
2. If the number is less than 0 goto step 7
3. Initialize sum=1, i=2
4. if N % i=0 then sum=sum+i
5. Increment i. If i<=N/2 goto step 4
6. if sum=N
Print the number is a perfect number
else
Print the number is not a perfect number
7. Stop.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page14
Flowchart:
Start
Read N
If N>0
Sum=1
I=2
If
N % i=0
True
Sum=Sum + i
False
i = i+1
True
If
i <= N/2
False
If
Sum=N
False
Print NonPerfect Number
True
Print
Perfect Number
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Stop
Page15
Program:
/* To find whether the given number is perfect number */
#include<stdio.h>
#include<conio.h>
void main()
{
int n,sum=1,i;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
if(n>0)
{
for(i=2;i<=n/2;i++)
if(n%i==0) sum=sum+i;
if(sum==n)
printf("\n\t%d is a perfect number",n);
else
printf("\n\t%d is not a perfect number",n);
}
else
printf("\n\tThe input number should be greater than zero");
getch();
}
Output -1:
Enter a number:28
28 is a perfect number
Output-2:
Enter a number:56
56 is not a perfect number
Output-3:
Enter a number:-28
The input number should be greater than zero
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page16
3B
TodesignsimpleCalculator
Aim:
To write a simple program to develop a simple calculator that accepts two
floating point numbers from the keyboard. Display a menu to the user and get
the users choice. Perform the operation and display the result using switch
statement.
Algorithm:
1. Read the two floating point numbers A, B.
2. Display the menu.
1 - Add
2 - Subtract
3 - Multiply
4 - Divide
3. Get the users choice.
4. If choice =1 then Result=A+B. Goto step 8.
5. If choice =2 then Result=A-B. Goto step 8.
6. If choice =3 then Result=A*B. Goto step 8.
7. If choice =4 then Result=A/B. Goto step 8.
8. Display the result.
9. Stop.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page17
Flowchart:
Start
Read A, B
Read Choice
Switch
Choice
Choice=1
Res = A + B
Res = A - B
Res = A * B
Res = A / B
Choice=2
Choice=3
Choice=4
Print Res
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page18
Program:
/* To design simple calculator */
#include<stdio.h>
#include<conio.h>
void main()
{
float
a,b,res;
int ch;
clrscr();
printf("Enter the value of A:");
scanf("%f",&a);
printf("Enter the value of B(B<>0):");
scanf("%f",&b);
printf("\n\nMathematical Operations");
printf("\n************************");
printf("\n\t1->Add");
printf("\n\t2->Subtract");
printf("\n\t3->Multiply");
printf("\n\t4->Divide");
printf("\n\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:res=a+b;
break;
case 2:res=a-b;
break;
case 3:res=a*b;
break;
case 4:res=a/b;
break;
}
printf("Answer =%.2f",res);
getch();
}
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page19
Output 1:
Enter the value of A:5
Enter the value of B(B<>0):7
Mathematical Operations
************************
1->Add
2->Subtract
3->Multiply
4->Divide
Enter your choice:1
Answer =12.00
Output 2:
Enter the value of A:7
Enter the value of B(B<>0):56
Mathematical Operations
************************
1->Add
2->Subtract
3->Multiply
4->Divide
Enter your choice:2
Answer =-49.00
Output 3:
Enter the value of A:5.2
Enter the value of B(B<>0):3
Mathematical Operations
************************
1->Add
2->Subtract
3->Multiply
4->Divide
Enter your choice:3
Answer =15.60
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page20
4ATofindsumofintegersbetweenAandB
Aim:
To write a C program to find the sum of all integers between any two
numbers.
Flowchart:
Start
Read A,B
Sum=0
False
For i =A to B
True
Sum = Sum + i
Print Sum
Stop
Algorithm:
1. Read the two numbers A and B
2. Initialize sum=0, i=A
3. Repeat step 4 and 5 until i <=B
4. Sum=Sum+i
5. i=i+1
6. Print Sum
7. Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page21
Program:
/* Sum of integers between given two ranges */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,i,sum=0;
clrscr();
printf("Enter the starting number:");
scanf("%d",&a);
printf("Enter the ending number:");
scanf("%d",&b);
for(i=a;i<=b;i++)
sum=sum+i;
printf("\n\tThe sum of integers between %d and %d=%d",a,b,sum);
getch();
}
Output:
Enter the starting number:5
Enter the ending number:12
The sum of integers between 5 and 12=68
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page22
4B
ToprintFibonaccinumbers
Aim:
To write a C program to print the first ten terms of the Fibonacci
Sequence assuming the first two terms as 0 and 1.
Flowchart:
Star
f1=0, f2=1
Print f1,f2
False
For i=3 to 10
True
f3=f1+f2
Print f3
f1=f2
f2=f3
Stop
Algorithm:
1. Initialize f1=0 , f2=1, i=3
2. Print f1,f2
3. Repeat steps 4 to 8 until i<=10.
4. f3=f1+f2
5. Print f3
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page23
6. f1=f2 ,f2=f3
7. i= i +1
8. Stop
Program:
/* Fibonacci series */
#include<stdio.h>
#include<conio.h>
void main()
{
int f1=0,f2=1,f3,i;
clrscr();
printf("Fibonacci series");
printf("\n****************\n\t");
printf("%5d%5d",f1,f2);
for(i=3;i<=10;i++)
{
f3=f1+f2;
printf("%5d",f3);
f1=f2;
f2=f3;
}
getch();
}
Output:
Fibonacci series
****************
0
13
M.S.P.V.LPolytechnicCollege,Pavoorchatram
21
34
Page24
4C
Tofindnumberofpositive,negativeandzeroinNelements
Aim:
To find the number of positive, negative and zeros in given N elements
Flowchart:
Start
Read N
Pos =0
Neg =0
Ze = 0
False
For i =1 to N
True
False
False
If
i=0
If
i >0
True
Ze = ze + 1
neg = neg + 1
True
pos = pos + 1
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page25
Algorithm:
1. Read the number of elements N.
2. Initialize pos=0, neg=0, ze=0
3. Repeat steps 4 to 5 N times.
4. Read the number X
5. If X =0
ze++
else if X>0
pos++
else
neg++
6. Print pos, neg, ze
7. Stop
Program:
/* To find number of Positive, Negative and Zeros in given 'N' numbers */
#include<stdio.h>
#include<conio.h>
void main()
{
int n,x,i,pos=0,neg=0,ze=0;
clrscr();
printf("Enter number of terms:");
scanf("%d",&n);
printf("\n\nEnter %d numbers\n",n);
printf("***************\n");
for(i=1;i<=n;i++)
{
scanf("%d",&x);
if(x==0)
ze++;
else if(x>0)
pos++;
else
neg++;
}
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page26
Output:
Enter number of terms:7
Enter 7 numbers
**************
23
0
-6
4
-12
0
3
Number of positive numbers=3
Number of negative number=2
Number of zeros=2
Viva Questions:
1) What are the various looping statements available in C?
a) While statement
b) Do..while statement
c) For statement
2) What is the difference between while and do..while statement?
While is an entry controlled statement. The statements inside the
while may not be executed at all when the condition becomes false at the
first attempt itself.
The do..while is an exit controlled statement. The statements in the
block are executed at least once.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page27
5ATocalculate&displaytheTotalandAverageofintegers
Aim:
To calculate and display the total and the average of 10 integer numbers.
Algorithm:
1. Define main Function & Declare all variables required.
2. Assign Initial value to the variable sum=0;
3. Read 10 numbers and store it in an array variable a[i].
4. Calculate the total of 10 numbers and find the average.
5. Sum=sum + a[i].
6. Avg=sum / 10;
7. Display the array elements and the total.
8. Stop.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page28
Flow chart:
Start
Sum=0
False
For i=0 to 9
True
Read a[i]
False
For i=0 to 9
True
sum=sum=a[i]
avg=sum/10
Print sum,
avg
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page29
Program:
/* Program to find sum and average of 10 numbers */
#include<stdio.h>
void main()
{
int i,a[10];
float sum,avg;
sum=0;
clrscr();
printf("---------- INPUT------------\n\n");
printf("Enter the Array Elements (10 Nos)...\n");
for (i=0;i<10;i++)
scanf("%d",&a[i]);
for(i=0;i<10;i++)
sum=sum+a[i];
printf("----------- OUTPUT----------\n\n");
printf("The Array Elements are...\n");
for(i=0;i<10;i++)
printf("%d\n",a[i]);
printf("Sum of 10 Numbers=== %.0f\n\n",sum);
avg=sum/10;
printf("Average of 10 Numbers=== %.2f",avg);
getch();
}
Output:
---------- INPUT-----------Enter the Array Elements (10 Nos)...
1
2
3
4
5
6
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page30
7
8
9
10
----------- OUTPUT---------The Array Elements are...
Sum of 10 Numbers=== 55
Average of 10 Numbers=== 5.50
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page31
5BTocalculate&displaytheTotalmarksusing2Darray
Aim:
Read 3 subject marks of 4 students. Write a program to calculate and
display the total marks of each student. Use a 2D (two-dimensional) array to
store the marks
Algorithm:
1. Define main Function.
2. Declare all variables in specified data type.
3. Get the details for 4 students. R.no & Name of the students using a
single dimensional array.
4. And a inner for loop is to be used to get 3 marks of each students.
5. Calculate the total marks and store it in a 2-D array variable marks[i][j];
6. Display all the details of 4 students.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page32
Flow chart:
Start
False
For i=0 to 3
True
sum[i]=0
Read regno[i],name[i]
False
For j=0 to 3
True
Read mark[i][j]
Sum=sum+mark[i][j]
avg=sum/10
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page33
False
For i=0 to 3
True
Print Regno[i],
False
For j=0 to 3
True
Print mark[i][j]
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page34
Program:
/* Program to calculate and display the total marks of each student */
#include<stdio.h>
void main()
{
int i,j,k,rno[10],sum[10],mark[10][10],tot[10];
float avg[10];
char name[10][10],*sub[10];
clrscr();
for(i=0;i<4;i++)
{
sum[i]=0;
printf("\nStudent Detail No : %d\n",i);
printf("Enter the Student Rno
");
scanf("%d",&rno[i]);
printf("Enter the Student Name ");
scanf("%s",name[i]);
for(j=0;j<3;j++)
{
printf("Enter the Mark %d ",j);
scanf("%d",&mark[i][j]);
sum[i]=sum[i]+mark[i][j];
}
avg[i]=sum[i]/3;
}
printf("\n---------OUTPUT--------\n\n");
for(i=0;i<4;i++)
{
printf("\nStudent No %d",i);
printf("\n\t Rno \t: ");
printf("%d",rno[i]);
printf("\n\t Name\t: ");
printf("%s",name[i]);
for(j=0;j<3;j++)
{
printf("\n\t Sub%d\t\t",j);
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page35
printf("%d",mark[i][j]);
}
printf("%n");
printf("\n\tTotal Marks
: ");
printf("%d",sum[i]);
printf("\n\tAverage
: %.2f",avg[i]);
}
getch();
}
Output:
Student Detail No : 0
Enter the Student Rno
1001
1002
1003
1004
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page36
: 1001
Name : MuthuKumar
Sub0
89
Sub1
78
Sub2
82
Total Marks
:249
Average
:83.00
Student No 1
Rno
: 1002
Name
: ShivaKumar
Sub0
76
Sub1
80
Sub2
83
Total Marks
:239
Average
:79.66
Student No 2
Rno
: 1003
Name
: RamKumar
Sub0
89
Sub1
90
Sub2
91
Total Marks
:270
Average
:90.00
Student No 3
Rno
: 1004
Name
: NanthaKumar
Sub0
86
Sub1
56
Sub2
73
Total Marks
Average
:215
:71.66
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page37
Viva questions:
1) What is an array?
An array is a collection of data of same data type. The elements of the
array are stored in consecutive memory locations.
The array elements can be processed using its index.
2) What is the starting index of an array in C?
The starting index of an array in C is 0.
3) What are the types of array?
Multidimensional array.
Debugging is easier
Testing is easier
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page38
6ATofindminimumoftwonumbersusingfunction
Aim:
Devise a function called min (x , y) that returns the smaller of two double
values. Test the function with a simple data.
Flow chart:
start
Read X,Y
min(X,Y)
mm =Call
min(X,Y)
False
If (X<Y)
Return Y
B
True
Return X
Print mm
Stop
Algorithm:
1.
2.
3.
4.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page39
Program:
/* Program to write a function to find minimum value */
#include<conio.h>
#include<stdio.h>
/* Main Function */
void main()
{
double x,y,mm;
double min(double,double);
/* Function Prototype */
clrscr();
printf("Enter the value of x:");
scanf("%lf",&x);
printf("Enter the value of y:");
scanf("%lf",&y);
mm=min(x,y);
/* Calling the function min(a,b) */
printf("\n\n\tThe minimum of %.4lf and %.4lf is %.4lf",x,y,mm);
getch();
}
/* Function to return the minimum of two numbers */
double min(double a,double b)
{
if(a<b)
return(a);
else
return(b);
}
Output 1:
Enter the value of x:45.565
Enter the value of y:32.23
The minimum of 45.5650 and 32.2300 is 32.2300
Output 2:
Enter the value of x:-1.2
Enter the value of y:1.2
The minimum of -1.2000 and 1.2000 is -1.2000
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page40
6BTocalculatefactorialusingrecursivefunction
Aim:
To calculate the factorial of given number using recursive function.
Flow chart:
Start
Read N
Factorial
(N)
Call
F=Factorial(N)
False
Return
N*Factorial(N
1)
If
(N<2)
B
True
Return N
Print f
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page41
Algorithm:
1. Define main Function & Declare all variables required.
2. Define a Function prototype with one argument and return value.
3. Read an integer value and store it in a variable .
4. Call the function called factorial( ) and pass the value as argument.
5. Print the return value.
In function Definition
A)
Program:
/* Program to find Factorial of Given No: using Recursive Function */
#include <stdio.h>
/*Function Declaration with one argument and with return value */
long factorial(long);
/* Main Function */
void main()
{
long number=0,f;
clrscr();
printf("\nEnter an integer value: ");
scanf("%ld",&number);
f=factorial(number);
/* Calling Function */
/* Terminating Condition */
return N;
else
return N*factorial(N-1);
/* Recursive call */
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page42
Output:
Enter an integer value:
6
The Factorial of 6 is 720
Viva Questions
1) What is a function?
Functions are group of statements that can perform a task.
Functions reduce the amount of coding and the functions can be called
from another program.
2) Write the syntax of a function definition.
return-value-type function-name( parameter-list )
{
declarations and statements
}
Call by value
o Copy of argument passed to function
o Changes in function do not effect original
o Use when function does not need to modify argument
o Avoids accidental changes
Call by reference
o Passes original argument
o Changes in function effect original
o Only used with trusted functions
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page43
7ATocalculatethenumberofvowelsinastring
Aim:
Write a C program to find the number of vowels present in the string.
[Assume your string contains both uppercase and lowercase characters]
Algorithm:
1. Begin a program with a comment line.
2. Include Header Files for standard input output function.
3. Define main Function & Declare all variables required.
4. Assign the vowels to an array variable.
A[ ] = aeiouAEIOU
5. Get the String and store it in a variable
6. In a nested for Loop
* Check the given string is equal to the value assigned in the array
variable.
* This is done until the string becomes NULL(\o)
* If the character in a string is equal increment the COUNT variable
by 1.
7. Print the Count variable which gives the result.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page44
Flow chart:
Start
Leta[]={aeiouAEIOU}
Count=0
len=strlen(str)
False
For i=0 to len-1
True
False
For j=0 to 9
True
False
If
(str[i]==a[j]
True
A
Count ++
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page45
Program:
/* Program to count No:of Vowels in a String */
#include<stdio.h>
#include<string.h>
void main()
{
char *str;
char a[]="aeiouAEIOU";
int i,j,count=0;
clrscr();
printf("\nEnter the string\n");
gets(str);
for(i=0;str[i]!='\0';i++)
for(j=0;a[j]!='\0';j++)
if(a[j] == str[i])
{
count++;
break;
}
printf("\n %d vowels are present in the string -> %s",count,str);
getch();
}
Output:
Enter the String
Programming
3 Vowels are present in the string -> Programming
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page46
7BTofindgivenstringispalindromeornot
Aim:
Write a program to find whether a given string is palindrome or not.
Algorithm:
1. Define main Function & Declare all variables required.
2. Let flag =0
3. Read a String and Find the Length of the String as n.
4. Using a for loop check the character str[i] and str[n-1-i].
5. if equal
continue the for loop until i=n/2
else
set flag=1 and break the for loop.
6. If flag =0
Print The string is Palindrome
Else
Print The string is not palindrome
7. Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page47
Flowchart
Start
Flag =0
Read
string
N= length(str)
False
For i =0 to n/2
True
If str[i] !=
False
str[n-1-i]
True
Flag =1
False
If flag = 0
Print Not
Palindrome
True
Print
Palindrome
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page48
Program
/* Program to find whether the string is Palindrome */
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{
char str[20];
int n,i,flag=0;
clrscr();
printf("Enter the string:");
gets(str);
n=strlen(str);
Output:
Enter the String
malayalam
The Given String is Palindrome
Enter the String
TamilNadu
The Given String is not Palindrome
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page49
7CToconvertthelowercaseintouppercase
Aim:
Read a string, which consists of both lower case characters and upper case
characters. Convert the lowercase character into upper case and vice versa.
Display the new string
Algorithm:
1. Define main Function & Declare all variables required.
2. Read a String and Find the Length of the String.
3. Check the characters ASCII value whether it lies between 97 and 122.
4. If the Condition is true
a. Change the ASCII value of the character by subtracting 32
5. Else check the ASCII value lies between 65 and 90
a. If the condition becomes true
i. Add 32 to the value for the character.
6. Repeat the step 4 & step 5 until the length of the string becomes NULL.
7. Print the result.
8. Stop.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page50
Flow chart:
Start
len=strlen(str)
False
For i=0 to len-1
True
If (str[i]>=65
&&str[i]<=90)
False
False
True
A
If (str[i]>=97
&&str[i]<=122
Str[i]=str[i]+32
True
Str[i]=str[i]-32
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page51
Program:
/* Convert the lowercase character into upper case and vice versa. */
#include<stdio.h>
void main()
{
char str[20];
int i;
clrscr();
printf("\n--------INPUT---------\n");
printf("Enter any string->");
scanf("%s",str);
printf("\n\n---------OUTPUT--------\n\n");
printf("The Entered string is---->%s\n\n",str);
for(i=0;i<=strlen(str);i++)
{
if(str[i]>=65 && str[i]<=90)
str[i]=str[i]+32;
else if(str[i]>=97 && str[i]<=122)
str[i]=str[i]-32;
}
printf("\nThe Converted string is---->%s",str);
getch();
}
Output:
--------INPUT--------Enter any string->jAVAiNTERFACE
---------OUTPUT-------The Entered string is---->jAVAiNTERFACE
The Converted string is---->JavaInterface
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page52
Viva Questions:
1) What is a string?
String is a sequence of characters.
2) What is the use of getchar() and gets() functions?
The getchar() function is used to read a single character from the key
board.
The gets() function is used to read a sequence of characters from the
keyboard.
3) What is the use of puts() function?
The puts() function is used to display a string in the standard output
device.
4) What is the difference between getchar() and getch() function?
Both the functions are used to read a single character from the keyboard.
When we use getchar() the character read is displayed on the screen. When we
use getch() the character is not echoed on the screen.
5) What is the difference between strings and character arrays?
A major difference is string will have static storage duration, whereas as
a character array will not, unless it is explicity specified by using the static
keyword.
6) Give some string processing functions.
strcmp() - Used to compare two strings
strcat() Used to concatenate two string.
strlen() Returns the length of the string.
strcpy() Copies one string to another.
toupper() Converts the lowercase letters to uppercase.
tolower() Converts the uppercase letters to lower case.
7) What is the delimiter for string?
\0 is the string delimiter
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page53
8ADisplaythestudentsdetailusingnestedstructure
Aim:
Write a program for nested structure, the two structures are declared
within a single structure. The two inner structures are : dob ( fields : dd, mm,
yy) and address (st, cty) and the outer structure Student ( fields : rollno,
name).
Write a main program to get and display the details of N students.
Algorithm:
1. Begin a program with a comment line.
2. Include Header Files for standard input output function.
3. Define the Structure called student and structure members (Rno &
Name).
4. Define a nested structure called dob and define the structure
members(day, month & year). Also define a structure variable d.
5. Define another nested structure called address and define the structure
members (street & City). Also define a structure variable ad.
6. Define main Function & Define a structure of array variable Stu [ ].
7. Read N for number of students.
8. Get the students details by structure referencing operator (.).
Eg.,
Stu[ ].d.day
Stu[ ] .ad.street
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page54
Flow chart:
Start
structstudent
{
intrno;
char name[10];
struct dob
{
int day; int year;
char mon[10];
}d;
struct address
{
char * st,*city;
}ad;
Read N
False
For i=0 to n-1
};
True
Read the details
of student[i]
False
For i=0 to n-1
True
Print the details of
student[i]
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page55
Program:
/* program to get and display the details of N students. Using structure */
#include<stdio.h>
struct student
{
int rno;
char name[10];
struct dob
{
int day;
char mon[10];
int year;
}d;
struct address
{
char * st,*city;
}ad;
};
void main()
{
struct student stu[10];
int n,i;
clrscr();
printf("Enter No of Students....");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Student Detail No %d",i);
printf("\nEnter The Student Rno...\t");
scanf("%d",&stu[i].rno);
printf("\nEnter the Student Name...\t");
scanf("%s",stu[i].name);
printf("\nEnter the Date of Birth...\t");
printf("\n\t\tDay \t ");
scanf("%d",&stu[i].d.day);
printf("\n\t\tMonth \t");
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page56
scanf("%s",stu[i].d.mon);
printf("\n\t\tYear \t");
scanf("%d",&stu[i].d.year);
printf("\nEnter The Address...\n");
printf("\n\t Enter the Street Name\t");
scanf("%s",stu[i].ad.st);
printf("\n \tEnter the City Name \t");
scanf("%s",stu[i].ad.city);
}
clrscr();
printf("\n\n ----------OUTPUT----------\n\n");
for(i=0;i<n;i++)
{
printf("Student No %d\n\n",i);
printf("\t\tStudent RNo\t\t");
printf("%d",stu[i].rno);
printf("\n\t\tStudent Name\t\t");
printf("%s",stu[i].name);
printf("\n\t\tDate of Birth\t\t");
printf("%d- %s - %d ",stu[i].d.day,stu[i].d.mon,stu[i].d.year);
printf("\n\t\tAddress...\n");
printf("\n\t\t\t Street \t%s",stu[i].ad.st);
printf("\n\t\t\t City
\t%s\n",stu[i].ad.city);
}
getch();
}
Output:
Enter No of Students....2
Student Detail No 0
Enter The Student Rno...
Enter the Student Name...
552001
ArunKumar
06
Month
11
Year
1979
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page57
Tenkasi
Student Detail No 1
Enter The Student Rno...
552002
BanuMathi.K
07
Month
November
Year
1979
Madurai
----------OUTPUT---------Student No 0
Student RNo
Student Name
Date of Birth
27713
ArunKumar
6- 11 - 1979
Address...
Street
City
SakthiNagar
Tenkasi
Student No 1
Student RNo
Student Name
Date of Birth
27714
BanuMathi.
7- November - 1979
Address...
Street
City
FirstStreet
Madurai
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page58
8BToprintthestudentsname,rollnousingunions
Aim:
Write a Program to print the student name, rollno, marks using unions.
Algorithm:
1. Begin a program with a comment line.
2. Include Header Files for standard input output function.
3. Define union called student and structure members (Rno , Name &
mark[ ]).
4. Define the main function and all variables.
5. Read the student rno and name.
6. Get 3 marks of the students and store it in a array variable(mark[ ]).
7. Print the student details.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page59
Flow Chart:
Start
unionstudent
{
intrno;
char*name;
intmark[10];
}stu;
Read rno,
name
False
For i=0 to 3
True
Read mark[i]
Read rno,
name
False
For i=0 to n-1
True
Print mark[i]
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page60
Program:
/* Program to print the student name, rollno, marks using unions*/
#include<stdio.h>
union student
{
int rno;
char *name;
int mark[10];
}stu;
void main()
{
int i;
clrscr();
printf("\nEnter the Student Rno :\t");
scanf("%d",&stu.rno);
printf("\nEnter the Student Name :\t");
scanf("%s",stu.name);
for(i=0;i<3;i++)
{
printf("\nEnter the Mark%d
:\t",i);
scanf("%d",&stu.mark[i]);
}
printf("\n--------OUTPUT-----------\n");
printf("Students Record:");
printf("\n\t\tRno
:");
printf("%d",stu.rno);
printf("\n\t\tName
:");
printf("%s",stu.name);
for(i=0;i<3;i++)
{
printf("\n\t\tMark%d :",i);
printf("%d",stu.mark[i]);
}
getch();
}
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page61
Output:
Enter the Student Rno :
Enter the Student Name :
Enter the Mark0
: 87
: 78
: 90
100
Shiva
--------OUTPUT----------Students Record:
Rno
:87
Name
:Shiva
Mark0
:87
Mark1
:78
Mark2
:90
Viva Questions:
1) What is a structure?
Combined with pointers, can create linked lists, stacks, queues, and
trees
2) What is an union?
Conserves storage
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page62
9AToswaptwointegerusingpointers
Aim:
Write a program to swap two integer numbers using pointers.
Flowchart
start
Read a,b
swap(*x,*y)
Call
swap(&a,&b)
temp=x;
x=y;
y=x
Print a,b
Stop
Algorithm:
1. Begin a program with a comment line.
2. Include Header Files for standard input output function.
3. Define main Function & Declare all variables required.
4. Define a function prototype swap(int*,int*) with two pointer argument.
5. Read two values as input.
6. Print the two values before swapping process.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page63
Program:
/*
#include<stdio.h>
void main()
{
int a,b;
/* Function Declaration with two arguments */
void swap(int*,int*);
clrscr();
printf("Enter the First Number\n");
scanf("%d",&a);
printf("Enter the Second Number\n");
scanf("%d",&b);
printf(" Result Before Swapping...\n");
printf("A=== %d\n",a);
printf("B=== %d\n",b);
swap(&a,&b);
/* Call of Function */
/* contents of pointer */
*x = *y;
*y = temp;
}
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page64
Output:
Enter the First Number
28
Enter the Second Number
42
Result Before Swapping
A=== 28
B=== 42
Result After Swapping
A=== 42
B=== 28
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page65
9BToreadastringusepointer
Aim:
Read a string. Print the above string such that each line contains a single
Flow chart:
Start
Declare
char*ptr,*str,c
Read str
ptr=str;
len=strlen(ptr)
ptr++
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page66
Algorithm:
1. Begin a program with a comment line.
2. Include Header Files for standard I/O function and string function.
3. Define main Function & Declare all variables required.
4. Get the string to print character by character.
5. Find the length of the string.
6. Assign the first pointer address content to the character variable.
7. Print the character variable.
8. Repeat step 6 and step 7 until length of the string becomes 0.
Program:
/* Program to Print the string such that each line contains a single character */
#include<stdio.h>
#include<string.h>
void main()
{
int i,len;
char *str,c,*ptr;
clrscr();
printf("Enter the String\n");
scanf("%s",str);
ptr=str;
len=strlen(ptr);
printf("---------OUTPUT----------\n\n");
printf("Entered String is --> %s\t\n\n",str);
printf("Output character by character....\n");
for(i=0;i<len;i++)
{
c=*ptr;
printf("%c\n",c);
ptr++;
}
getch();
}
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page67
Output:
Enter the String
programming
---------OUTPUT---------Entered String is --> programming
Output character by character....
p
r
o
g
r
a
m
m
i
n
g
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page68
9CToprinttheelementsinreverseorderusingpointers
Aim:
Read an integer array consist of N elements. Print the elements in reverse
order using pointers
Algorithm:
1. Begin a program with a comment line.
2. Include Header Files for standard I/O function.
3. Define main Function & Declare all variables required.
4. Get the array number N.
5. Read N number of elements and store it in the array variable num[ ] ).
6. Print the array list.
7. Print the value using pointer operator *.
8. Repeat step 7 for N times from N to 0.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page69
Flow Chart:
Start
Read N
False
For i=0 to n-1
True
Read (num+i)
False
For i=0 to n-1
True
Print *(num+i)
False
For i=n-1 to 0
True
Read *(num +i)
)
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page70
Program:
/* Program to print the elements in reverse order using pointers */
#include <stdio.h>
void main()
{
int i,n,num[10];
clrscr();
printf("Enter the number of elements in the array:");
scanf("%d",&n);
printf("Enter the Array Numbers\n");
for (i= 0; i<n; i++ )
scanf("%d",num+i);
printf("\n\nThe Array Numbers are...\n");
for(i=0;i<n;i++)
printf("%5d",*(num+i));
printf("\n\nReversed Array List ...\n");
for (i = n-1; i >= 0; i-- )
printf("%5d",*( num+i));
getch();
}
Output:
Enter the number of elements in the array:5
Enter the Array Numbers
23
78
45
23
78
45
23
23
45
78
23
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page71
10AToreadanarrayusingpointer
Aim:
Write a C program to read through an array of any type using pointers.
Write a C program to scan through this array to find a particular value
Algorithm:
1. Begin a program with a comment line.
2. Include Header Files for standard I/O function, Conversion and String
function.
3. Define a function prototype called search( ).
4. Define main Function & Declare all variables required.
5. Allocate dynamic memory for a variable using malloc( ) function.
6. Read a string.
7. Repeat step 5 and step 6 until n number of array elements.
8. Print the array elements.
9. Call the function Search ( ) by passing N number of strings.
10 .In function Definition
*Define a temporary variable and allocate the memory space using
malloc( ).
* Read the String to search and store it in the temporary variable.
* Check the value with the array element by using string compare
function.
* If they are equal set flag = 0 else set flag = 1.
11. Check the condition if flag = 0 Print the value is found. Otherwise print
the value given to search is not found.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page72
Flowchart
Start
Define a string
pointer array
Call
read
Return
False
If
flag=0
PrintStringNot
Found
True
Print String
Found
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page73
Read
No
If
(strcmp(str[
i] , temp)
True
False
Flag=0
return
Flag=1
Program:
/* Pointer and Array of any data type to search a given value */
# include<stdio.h>
# include<string.h>
# include<ctype.h>
int flag;
/* FUNCTION PROTOTYPE */
int search(char **, int );
/* Function main */
void main( )
{
char choice;
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page74
int i, n = 0;
char *string[100];
clrscr();
do
{
string[n] = (char *) malloc(50);
printf("Input string: ");
gets(string[n]);
n++;
printf("\n Input another Y/N? ");
choice = getchar();
fflush(stdin);
}while(toupper(choice) == 'Y');
printf("\nArray list \n");
printf("********** \n");
for (i = 0; i < n; i++)
{
printf("%s\n", string[i]);
}
/* Function CALL */
search(string, n);
if (flag==0)
printf("The String Given is FOUND");
else
printf("The String Given is Not Found");
getch();
}
/* Definition of function */
int search(char **str, int n)
{
int i,j;
char *temp[10] ;
temp[0]= (char *)malloc(50);
printf("Enter the string to Find\n");
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page75
gets(temp);
printf("\nThe String to Find\n");
puts(temp);
for(i=0;i<n;i++)
{
if(strcmp(str[i],temp)==0)
flag=0;
else
flag=1;
}
return(flag);
}
Output:
Input string: Mani
Input another Y/N? y
Input string: Raaju
Input another Y/N? y
Input string: 123
Input another Y/N? y
Input string: 56.34
Input another Y/N? n
Array list
**********
Mani
Raaju
123
56.34
Enter the string to Find
56.34
The String to Find
56.34
The String Given is FOUND
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page76
10BTofindthelengthofthestringusingpointer
Aim:
To find the length of the string using pointer.
Flow chart:
Start
x=0
Read str
False
While(*str!=0)
True
x++;
str++;
Stop
Algorithm:
1. Begin a program with a comment line.
2. Include Header Files for standard input output function.
3. Define main Function & Declare all variables required.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page77
Program:
/* Program to Find Length of Strings using Pointers */
#include<stdio.h>
void main()
{
int x;
char *str;
x=0;
clrscr();
printf("Enter the String\n");
scanf("%s",str);
printf("Length of %s is ",str);
while (*str != '\0')
{
x++;
str++;
}
printf("%d",x);
getch();
}
Output:
Enter the String
Programming
Length of Programming is 11
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page78
10CToconcatenatetwostringusingpointer
Aim:
To concatenate two string using pointer
Algorithm:
1. Begin a program with a comment line.
2. Include Header Files for standard input output function.
3. Define main Function & Declare all variables required.
4. Read two strings s1 and s2
5. Move to the end of first string using a temporary pointer.
6. Add the second string to the end of first string pointed by
temporary variable.
7. Print the concatenated string s1
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page79
Flow Chart:
Start
Declare
char*s1,*s2,*temp
Read s1,s2
temp=s1
While
(*temp!=\0)
False
True
temp++;
While
(*s2!=\0)
False
True
*temp=*s2
temp++
s2++
Print s1
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page80
Program:
/* String Concatenation */
#include<stdio.h>
#include<conio.h>
void main()
{
char *s1,*s2,*temp;
clrscr();
printf("Enter the first string:");
gets(s1);
printf("Enter the second string:");
gets(s2);
printf("\n\tThe string s1 before concatenation:%s",s1);
printf("\n\tThe string s2 before concatenation:%s",s2);
temp=s1;
while(*temp!='\0') /* Move to end of string1 */
temp++;
while(*s2!='\0')
{
*temp=*s2;
temp++;
s2++;
}
*temp='\0';
printf("\n\tThe concatenated string s1:%s",s1);
getch();
}
Output:
Enter the first string:Operating
Enter the second string:System
The string s1 before concatenation:Operating
The string s2 before concatenation:System
The concatenated string s1:OperatingSystem
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page81
Viva Questions:
1) What is a pointer?
Pointer is a variable that holds the address of another variable.
2) What is called the indirection operators?
* is called the indirection operator since it is used to indirectly access the
value of a variable through its pointer.
3) What are the advantages of pointer?
*p=a[0];
*(p+1)=a[1];
*(p+2)=a[2];
*(p+3)=a[3]
*(p+4)=a[4];
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page82
Ex11ATocreateandPrintSinglyLinkedListofVowels
Aim:
To write a C program to create a linked list to contain the vowels a, e,
i, o, u in the data field of the nodes.
Algorithm:
1. Define the structure of the node.
2. Define function to get a new node
This function allocates memory for the node structure defined and
returns the pointer to that node say newnode.
3. Define function insafter( p,x) to insert a node after a given node.
Let the address for the previous node be prenode and data to be
inserted as X
newnodedata=X
prenodenext=newnode
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page83
Flow Chart:
Start
i=0
i = i +1
True
If i<6
False
Print the List
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page84
Program:
/*
#include<stdio.h>
#include<conio.h>
/* Node structure definition */
struct node
{
char data;
struct node *next;
};
typedef struct node *nodeptr;
nodeptr prenode,first;
/* Get node Function */
nodeptr getnode()
{
nodeptr d;
=(nodeptr) malloc(sizeof(struct node));
return d;
}
/*
*/
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page85
void createlist()
{
char vow[]={'a','e','i','o','u'};
int i;
prenode=first=getnode();
prenode->data=vow[0];
prenode->next=NULL;
fflush(stdin);
for(i=1;i<6;i++)
prenode=insafter(prenode,vow[i]);
}
void show()
/*
*/
{
prenode=first;
while (prenode->next!= NULL)
{
printf("%c---->",prenode->data);
prenode=prenode->next;
}
printf("NULL");
}
void main()
/* Main Function */
{
clrscr();
createlist();
printf("\nThe created List");
printf("\n*****************\n\n");
show();
getch();
}
Output:
The created List
**************
a---->e---->i---->o---->u---->NULL
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page86
11B
Aim:
Todeletethefirstnodeinthelinkedlistofintegers
Algorithm:
1. Define functions getnode(), insafter() and createlist() to get a new
node, insert a node after a node and create the linked list respectively.
2. The first pointer points the address of the first node.
3. Define a function delfirst() that deletes the first node and returns the
data in the first node using the algorithm given below.
Make
first
pointer
to
point
the
next
node
as
first=firstnext.
6. Stop.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page87
Flow Chart:
Start
Read the
data
Yes
More
data?
No
Print the
List
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page88
Program:
/*
#include<stdio.h>
#include<conio.h>
/* Node structure definition */
struct node
{
int data;
struct node *next;
};
typedef struct node *nodeptr;
nodeptr prenode,first;
/* Get node Function */
nodeptr getnode()
{
nodeptr d;
d=(nodeptr) malloc(sizeof(struct node));
return d;
}
/*
*/
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page89
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page90
/*
*/
void show()
{
prenode=first;
while (prenode!= NULL)
{
printf("%d---->",prenode->data);
prenode=prenode->next;
}
printf("NULL");
}
/* Main Function */
void main()
{
int del;
clrscr();
printf("\n Creating the list");
printf("\n******************");
createlist();
printf("\n Displaying the list");
printf("\n--------------------\n\n");
show();
del=delfirst();
printf("\n\n\nThe list after deleting the first node");
printf("\n---------------------------------------\n\t");
show();
printf("\n\nThe deleted data %d",del);
getch();
}
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page91
Output:
Creating the list
**************
Enter the data:5
Any more data(Y/N)?:y
Enter the data:34
Any more data(Y/N)?:y
Enter the data:23
Any more data(Y/N)?:y
Enter the data:1
Any more data(Y/N)?:n
Displaying the list
-------------------5---->34---->23---->1---->NULL
Viva Questions:
1) What is data structure?
An organization and representation of data is called data structure.
2) What are the two types of data structure?
Data structures can be classified into two types
a) Linear data structures
b) Non-linear data structures
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page92
Array
Linked list
Stack
Queue
Insertion
Deletion
Searching
6) What are the possible locations where the data can be inserted into a
linked list?
Data can be inserted into the linked list in the beginning, in the
middle and at the end.
7) What are the possible locations where the data can be deleted in a
linked list?
Data can be deleted from the first, from the last and from the
middle.
8) What is a doubly linked list or two way list?
The linked list which has two pointer which points to the previous node
and the next node is called a doubly linked list.
When we use doubly linked lilst we can traverse the node in both the
directions.
9) What is a circular list?
The linked list in which the last node points back to the first node is called
circular list.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page93
12 ToperformstackoperationsinStackusingarray
Aim:
To write a C program to perform operations in stack using array.
Algorithm:
1. Declare the structure of stack with an array of size 20 to hold the stack
and the initialize top =-1
2. Define a function push( ) to add the data to the stack as
Check if the stack is full if so display Stack Full and return.
Otherwise
Increment the top value.
Store the data in the stack[top] and return
3. Define a function pop( ) that deletes the value in the top of the stack
as
If top=-1 print Stack Empty and return
Otherwise Print the element at stack[top] and decrement top
value and return
4.
6. Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page94
Flow chart:
Start
Switch
Choice
Choice=1
Read X
Print
Stack
Choice=2
B
Choice=3
Choice=4
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page95
Push:
If
top=20
Top=top+1
Stack[top]=X
Print Stack
Full
Pop
B
If
top=1
Print
stack[top]
Top=top-1
Print Stack
Emptyl
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page96
Program:
/* stack using array */
#include<stdio.h>
#include<conio.h>
/*Structure to hold the stack*/
struct stack
{
int a[20];
int top;
}s;
/*Function to add element to the stack*/
void push(int x)
{
if(s.top==20)
printf("Stack full");
else
{
s.top++;
s.a[s.top]=x;
printf("\n\tData is added to stack\n");
}
}
/*Function to delete element from the stack*/
void pop()
{
int x;
if(s.top==-1)
{
printf("\n\tStack empty");
}
else
{
printf("\n\tThe deleted data is %d",s.a[s.top]);
s.top--;
}
}
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page97
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page98
switch(ch)
{
case 1:
scanf("%d",&data);
push(data);
break;
case 2: pop();
break;
case 3: show();
break;
case 4: exit(0);
}
}while(ch<4);
getch();
}
Output:
Menu
1->Push
2->Pop
3->List stack
4->Exit
Enter your choice:1
Enter the data:67
Data is added to stack
Menu
1->Push
2->Pop
3->List stack
4->Exit
Enter your choice:1
Enter the data:11
Data is added to stack
Menu
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page99
1->Push
2->Pop
3->List stack
4->Exit
Enter your choice:3
The stack elements
------------------------67
11
<---top
Menu
1->Push
2->Pop
3->List stack
4->Exit
Enter your choice:2
The deleted data is 11
Menu
1->Push
2->Pop
3->List stack
4->Exit
Enter your choice:3
The stack elements
-----------------------67
<---top
Menu
1->Push
2->Pop
3->List stack
4->Exit
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page100
13Toconvertinfixtopostfixusingstack
Aim:
To write a C program to convert an infix expression into post fix
expression.
Algorithm:
1. Define a stack of to hold the characters.
2. Initialize stack top = -1.
3. Read the infix expression.
4. Add ) to the end of the infix expression.
5. Push ( to the stack.
6. Scan the infix expression from left to right and repeat the step 7 for all
the characters in the infix expression.
If the character is (
If the character is )
Pop )
is lesser than or
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page101
Flow chart:
Start
Declarethestack
Top=1
Read infix
expression
False
For each
character in
Print Postfix
Expression
True
Switch
Character
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page102
Character=Operand
Character = (
Add to postfix
expression
Push the
character to the
t k
Character = )
Character is an
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page103
Program:
/* Program to convert infix to postfix using stack */
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<ctype.h>
#include<string.h>
/*Stack declaration*/
struct stack
{
char a[20];
int top;
}s;
/*Function to push the data into stack*/
void push(char c)
{
if(s.top==20)
printf("Stack full");
else
{
s.top++;
s.a[s.top]=c;
}
}
/*Function to pop the data from the stack*/
char pop()
{
char x;
if(s.top==-1)
{
return '0';
}
else
{
x=s.a[s.top];
s.top--;
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page104
return x;
}
}
char tops()
{
if(s.top==-1)
return '#';
else
return(s.a[s.top]);
}
int preced(char c)
{
if(c=='+' || c=='-')
return 1;
else if(c=='*' || c=='/')
return 2;
else
return 3;
}
/*Function to check the operator precendence*/
int islow (char c,char d)
{
if(preced(c)<=preced(d))
return 1;
else
return 0;
}
/*Function check whether the character is an operator*/
int isoperator(char c)
{
if(c=='+' || c=='-' || c=='*' || c=='/' || c=='^')
return 1;
else
return 0;
}
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page105
/*Main function*/
void main()
{
char infix[20],post[20],c;
int len,i,j;
clrscr();
s.top=-1;
printf("Enter the infix expression:");
gets(infix);
len=strlen(infix);
infix[len]=')';
infix[++len]='\0';
i=j=0;
push('(');
do
{
c=infix[i];
if(isalpha(c)) //Check whether the character is an alphabet
{
post[j]=c;
j++;
}
else if(c=='(')
{
push(c);
}
else if(isoperator(c))
{
while(isoperator(tops()) && islow(c,tops()))
{
post[j]=pop();
j++;
}
push(c);
}
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page106
else if(c==')')
{
while (tops()!='(')
{
post[j]=pop();
j++;
}
pop();
}
i++;
}while(tops()!='#');
post[j]='\0';
printf("\nPostfix form is %s",post);
getch();
}
Output 1:
Enter the infix expression:(a+b)*(c+d)
Postfix form is ab+cd+*
Output 2:
Enter the infix expression:a+b/c+d
Postfix form is abc/+d+
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page107
14EvaluationofPostfixExpression
Aim:
To write a C program to evaluate a postfix expression.
Algorithm:
1. Declare the structure for the stack.
2. Read the postfix expression.
3. Repeatedly execute the following for all the characters in the
expression from left to right
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page108
Flowchart
Start
Declare the
k
Read the
infix
For each
character in infix
i
True
If
Character
False
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page109
Program:
/* Evaluation of postfix expression */
#include<stdio.h>
#include<math.h>
#include<ctype.h>
#include<conio.h>
/* Declaration of stack */
struct stack
{
int top;
float a[20];
}s;
/* Main Function */
void main()
{
int i,n;
float op1,op2,op3;
char ex[20];
clrscr();
s.top=-1;
printf("\n\n\tEnter the postfix expression:");
gets(ex);
n=strlen(ex);
for (i=0;i<n;i++)
{
if (isdigit(ex[i]))
{
s.top++;
s.a[s.top]=ex[i]-'0';//To covert character into integer
}
else
{
op2=s.a[s.top--];
op1=s.a[s.top--];
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page110
switch(ex[i])
{
case '+':op3=op1+op2;
break;
case '-':op3=op1-op2;
break;
case '*':op3=op1*op2;
break;
case '/':op3=op1/op2;
break;
case '^':op3=pow(op1,op2);
break;
}
s.a[++s.top]=op3;
}
}
printf("\n\t The result of (%s) is %.2f",ex,s.a[s.top]);
getch();
}
Output 1:
Enter the postfix expression:34*78+*
The result of (34*78+*) is 180.00
Output 2:
Enter the postfix expression:145*+
The result of (145*+) is 21.00
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page111
Viva Questions
1) What is stack?
A stack is a Last-In-First-Out linear data structure in which insertion and
deletion takes place at only one end called the top of the stack.
2) What are the operations that can be performed on the stack?
PUSH To add a new element to the top of the stack
POP To remove an element at the top of the stack.
3) What are the applications of the stack?
The stack data structure is used in applications where Last-In-FirstOut operations are carried out.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page112
6) What is the infix, prefix , post fix form of the following expression?
a) A + B + C
Infix
b) (A+B) * (C+D)
c) A-B / C-D
Postfix
Prefix
A+B+ C
AB+C+
++ABC
(A+B) * (C+D)
AB+CD+*
*+AB+CD
A-B / C-D
ABC/-D-
--A/BCD
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page113
15
ImplementationofQueueusingarray
Aim:
To write a C program to perform operations in queue using array.
Algorithm:
1. Declare the array to hold the queue elements and the variables to hold
the front and rear index.
2. Define functions to insert data into the rear end of queue as
If front=rear
Print Queue Empty
Else
front=front+1
Print the deleted element and the queue
4.
5.
6. Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page114
Flow chart:
Start
Createaqueue
ofNelemnets
Displaythemenu
1Add
2Delete
3 Exit
C
Read users
choice
Switch
Choice
Choice=1
A
Choice=2
B
Choice=3
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page115
False
If
Read X
Rear=QSize1
True
Rear=rear+1
q[rear]=X
Print Stack
Full
Print Queue
DeleteElementsintheQueue
B
If
Front=rear
False
Front=front+1
True
Print
Queue
Printq[rear]
Print Queue
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page116
Program:
/* Inserting and deleting elements from the queue */
#include<stdio.h>
#include<conio.h>
#define Q_SIZE 20
/*Declaration of array for queue*/
struct queue
{
int a[Q_SIZE];
int front,rear;
}q;
/* Function to insert element into the queue */
void insert()
{
int x;
if (q.rear==Q_SIZE-1)
printf("\n\nQueue full. Insertion not possible");
else
{
printf("\n Enter data to insert:");
scanf("%d",&x);
q.rear++;
q.a[q.rear]=x;
}
}
/*Function to delete the elements in the queue */
void deleteq()
{
if(q.front==q.rear)
printf("\n\nQueue is empty. Deletion not possible:");
else
{
++q.front;
printf("\n\n The deleted element is %d",q.a[q.front]);
}
}
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page117
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page118
printf("\n\t2->Deletion");
printf("\n\t3->Exit");
printf("\n\nEnter your choice:");
scanf("%d",&ch);
switch (ch)
{
case 1:insert();
show();
break;
case 2:deleteq();
show();
break;
case 3:exit(0);
}
}
}
Output:
No. of elements initially in the queue:3
Enter the element:2
Enter the element:4
Enter the element:5
The elements in the queue:
***********************
Front--->2 4 5 <---Rear
Select your choice:
1->Insertion
2->Deletion
3->exit
Enter your choice:1
Enter data to insert:45
The elements in the queue:
***********************
Front--->2 4 5 45 <---Rear
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page119
Viva Questions:
1) What is a queue?
Queue is a linear data structure in which insertions are done end
one end called the Rear of the queue and Deletions are done at another
end called the Front. The queue is referred as First-In-First-Out data
structure.
2) What is a circular queue?
A queue in which both the front and the rear wrap around to the
beginning of the array when they reached the MAX size of the queue is
called circular queue.
3) What is a priority queue?
A queue where insertions and deletions are performed based on
some priority is called priority queue.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page120
16CreationbinaryTree
Aim:
To write a C program to create a binary tree.
Algorithm:
The following algorithm to create a binary using sequential representation.
the data field and sets the left and right pointer to NULL and returns
the address of the created node.
5. Define a function inorder() that prints the inorder list of the tree using
recursive call.
6. Define the main function that calls the functions create( ) and inoder to
create a tree and print the in order traversal of the tree.
7. Stop.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page121
Flow chart:
Start
While true
False
Exit
True
Display the menu
1-Create tree
2-Inorder List
3-Exit
Switch
Choice
Choice = 1
A
Choice = 2
Choice = 3
Stop
Exit
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page122
Creating a tree:
Read number of
nodes in the tree N
For i=2 to N
False
True
Read the data
If
i%2 = 0
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page123
Inorder (p)
True
If
P!=NUL
p=p llink
False
p=prlink
True
If
P!=NUL
False
Return
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page124
Program:
/* Creating a binary tree and inserting the elements */
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
/* Tree structure */
struct node
{
int data;
struct node *rlink;
struct node *llink;
};
/* Creating a tree */
struct node *maketree(int item)
{
struct node *p;
p=(struct node*) malloc(sizeof(struct node));
p->data=item;
p->llink=NULL;
p->rlink=NULL;
return p;
}
/* Inserting nodes into the tree */
struct node *create()
{
struct node *ptr,*t,*t1[100];
int n,i,item,k=1;
printf("\n Enter the number of data to insert..");
scanf("%d",&n);
printf("\n Enter the data one by one \n");
scanf("%d",&item);
ptr=maketree(item);
t1[k++]=ptr;
for(i=2;i<=n;i++)
{
scanf("%d",&item);
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page125
t1[i/2]->llink=t;
t->rlink=NULL;
t->llink=NULL;
}
else
{
t1[i/2]->rlink=t;
t->llink=NULL;
t->rlink=NULL;
}
}
return ptr;
}
/* In order traversal */
void inorder(struct node *p)
{
if(p!=NULL)
{
inorder(p->llink);
printf("%d\t",p->data);
inorder(p->rlink);
}
}
/* Main Function */
void main()
{
struct node *p;
int opt,pos,item;
clrscr();
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page126
while(1)
{
printf("\n\t\tMain Menu");
printf("\n\t\t----------");
printf("\n\t1.Create Tree");
printf("\n\t2.Inorder List");
printf("\n\t3.Exit\n");
printf("Select the option <1,2,3>...");
scanf("%d",&opt);
switch(opt)
{
case 1:p=create();
break;
case 2:printf("\n Inorder List \n");
inorder(p);
break;
case 3:exit(0);
}
printf("\n\n Press any key to continue...");
getch();
}
}
Output:
Main Menu
---------1.Create Tree
2.Inorder List
3.Exit
Select the option <1,2,3>...1
Enter the number of data to insert..5
Enter the data one by one
1
2
3
4
5
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page127
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page128
17PreorderTraversalusingrecursion
Aim:
To write a C program for pre -order traversal of a binary tree using
recursion.
Algorithm:
The following algorithm to create a binary using sequential representation.
1.
2.
3.
Define function maketree( ) to get a new node that stores the data in
the data field and sets the left and right pointer to NULL and returns
the address of the created node.
4.
5.
6.
First the root node is created and its address is stored at the first
index of the array.
7.
Then using for loop the data are read and stored in the data field
using the maketree( ) function.
a) If the array index i an even number then the node is
linked as the left child of the node (i/2).
b) If the array index i is an odd number then the node is
linked as the right child of the node (i/2).
8.
The leaf nodes left and right pointers are declared NULL.
9.
Define a function preorder() that prints the preorder list of the tree
using recursive call as
a) Visit the node
b) Traverse left subtree
c) Traverse right subtree
10.
Define the main function that calls the functions create( ) and
preorder to create a tree and print the in order traversal of the tree.
11.
Stop.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page129
Flow chart:
Start
While true
False
Exit
True
Display the menu
1-Create tree
2-Preorder List
3-Exit
Switch
Choice
Choice = 1
A
Choice = 2
Choice = 3
Stop
Exit
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page130
Creating a tree:
Read number of
nodes in the tree N
For i=2 to N
False
True
Read the data
If
i%2 = 0
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page131
Preorder (p)
True
If
P!=NUL
p=prlink
If
P!=NUL
Return
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page132
Program:
/* Pre-order Traversal using recursion */
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
/* Tree structure */
struct node
{
int data;
struct node *rlink;
struct node *llink;
};
/* Creating tree */
struct node *maketree(int item)
{
struct node *p;
p=(struct node*) malloc(sizeof(struct node));
p->data=item;
p->llink=NULL;
p->rlink=NULL;
return p;
}
/* Inserting elements into the tree */
struct node *create()
{
struct node *ptr,*t,*t1[100];
int n,i,item,k=1;
printf("\n Enter the number of data to insert..");
scanf("%d",&n);
printf("\n Enter the data one by one \n");
scanf("%d",&item);
ptr=maketree(item);
t1[k++]=ptr;
for(i=2;i<=n;i++)
{
scanf("%d",&item);
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page133
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page134
while(1)
{
printf("\n\t\t Main Menu");
printf("\n\t\t----------");
printf("\n\t1.Create");
printf("\n\t2.Preorder");
printf("\n\t3.Exit\n");
printf("Select the option <1,2,3>...");
scanf("%d",&opt);
switch(opt)
{
case 1:p=create();
break;
case 2:printf("\n\n Preorder List \n");
preorder(p);
break;
case 3:exit(0);
}
printf("\n Press any key to continue....");
getch();
}
}
Output:
Main Menu
---------------1.Create
2.Preorder
3.Exit
Select the option <1,2,3>...1
Enter the number of data to insert..5
Enter the data one by one
1
2
3
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page135
4
5
Press any key to continue....
Main Menu
--------------1.Create
2.Preorder
3.Exit
Select the option <1,2,3>...2
Preorder List
1
Viva Questions:
1) What is a tree?
T has two sets of nodes, LT and RT, called the left subtree and
right subtree of T, respectively.
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page136
If all levels except the last level have the maximum number of
possible nodes ( 2r-1).
In the last level the nodes can be left free only at the right end.
Inorder Traversal
Preorder Traversal
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page137
18ImplementationofLinearSearchandBinarySearch
Aim:
To write a C Program for linear searching and binary searching.
Algorithm:
1. Define function for linear search as
a) Read the data to be searched X.
b) Scan the array from left to right.
c) Compare X with the first element.
d) If equal then
Print SUCCESS and return
Else
Compare X with second element and so on
e) The above process is repeated for all the elements in the array.
f) If no value in the array matches with X then Print NO MATCH
and return.
2. Define function for Binary Search as
a) Sort the array in ascending order.
b) Let lb=0 and ub=n-1
c) Read the data to be searched X.
d) Find the mid position of the given array
Mid=(lb+ub)/ 2 (N --- No.of Elements in the array)
e) Compare X with a[mid]
If equal then
Goto step (g)
Else
If X less than a[mid] then ub=mid-1
If X greater than a[mid] then lb=mid+1
If lb<=ub
Repeat steps (d) and (e) for the sub array lb to ub
Else
Goto step (g)
g) If (lb>ub)
Print Search Success
Else
Print Search Failed
f) Return.
f)
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page138
Flow chart:
Start
ReadN
ReadArrayElements
Call
Linear
Search
A
Call
Binary
Search
B
stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page139
Binary Search
Binary
Search
Read X
Lb = 0
Ub = N-1
No
While lb <= ub
Print
FAILURE
Yes
Mid=(lb+ub) /2
If
X=a[mid]
True
Print SUCCESS
False
B
False
If
X<A[mid
Lb=mid+1
True
Ub = mid-1
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page140
Linear Search
Linear
Search
Read X
More elements
If
A[i]=X
Print
SUCCESS
Program:
/* Linear Search and Binary Search Program */
#include<stdio.h>
#include<conio.h>
/* Function for Linear search */
void linear(int a[],int n)
{
int data,i;
printf("\n\tEnter the item to be searched:");
scanf("%d",&data);
for(i=0;i<n;i++)
if(data= =a[i]) break;
if(i==n)
printf("\n\n\tThe search item is not present in the array\n");
else
printf("\n\n\tThe search item is present in the array\n");
}
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page141
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page142
else
lb=mid+1;
}
}
if(lb>ub)
printf("\n\n\tThe search item is not present in the array");
else
printf("\n\n\tThe search item is present in the array");
}
/* Main function */
void main()
{
int a[30],n,i;
clrscr();
printf("Enter the number of data :");
scanf("%d",&n);
printf("\nEnter the elements:\n");
for(i=0;i<n;i++)
{
printf("a[%d]:",i);
scanf("%d",&a[i]);
}
printf("\n\nUsing Linear search ");
printf("\n-------------------\n");
linear(a,n);
getch();
}
Output:
Enter the number of data :7
Enter the elements:
a[0]:8
a[1]:5
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page143
a[2]:9
a[3]:3
a[4]:7
a[5]:2
a[6]:7
Using Linear search
-------------------------Enter the item to be searched:5
The search item is present in the array
Using Binary search
--------------------------The array in sorted order
2
Viva Questions:
1) What is searching?
Searching means searching for an element in a given list.
2) Compare linear search and binary search.
Linear Search
Binary Search
to be checked is reduced by 2
Time Complexity
F(n) =O (n)
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page144
19
InsertionSort
Aim:
To write a C program to read 10 elements and sort the array using
insertion sort.
Algorithm:
1.
2.
Take the second element. Compare it with the first element. If the
second element less than the first element interchange them.
3.
Take the third element compare it first and second element and insert
it in the correct position by shifting the elements in the array. So that
the first, second and third elements are in sorted order.
4.
In general Take the ith element and compare it with the all the
elements before it and place it in the proper position by shifting the
elements one position right.
5.
When the ith element is placed, the elements in the array from the 0th
to the ith position will be in the sorted order.
6.
The above process is continued for all the elements in the array.
7.
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page145
Flow chart:
start
Read 10
elements
For i=1 to n-1
temp=a[i]
j=i-1
False
While ( temp<a[j]
and j>=0)
True
a[j+1]=a[j]
j=j-1
A[j+1]=temp
Print the
sorted array
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page146
Program:
/* Insertion sort
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,temp;
clrscr();
printf("\n Enter the array elements:\n");
for(i=0;i<10;i++)
{
printf("a[%d]:",i);
scanf("%d",&a[i]);
}
printf("\n Press any key to continue");
printf("\n\n\nUnsorted array:");
printf("\n~~~~~~~~~~~~~~~\n");
for (i=0;i<10;i++)
printf("%5d",a[i]);
/* Insertion sort procedure */
for(i=1;i<10;i++)
{
temp=a[i];
j=i-1;
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page147
Output:
Enter the array elements:
a[0]:454
a[1]:23
a[2]:7
a[3]:2
a[4]:8
a[5]:3
a[6]:87
a[7]:3
a[8]:7
a[9]:2
Press any key to continue
Unsorted array:
~~~~~~~~~~~~~
454
23
87
23
87 454
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page148
20
Aim:
ImplementationofQuickSort
Algorithm:
1. Define the array
2. Define the function sort( first, last) for partitioning and sorting the array is
a)
b)
c)
d)
Repeat
a. Increment up until a[up]<= pivot and up<last
b. Decrement down until a[down] >= pivot and down>first.
c. If up<down interchange a[up] and a[down].Until up<dow.
e)
f)
g)
If (first < last) The sorting is again continued for the arrays
a[first] to a[down-1] and a[down+1] to a[last].
b)
c)
d)
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page149
Flowchart
Start
Read N
Call
sort(0,n-1)
Sort
B
Print the
sorted array
Stop
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page150
B
Sort(first, last)
If
first<last
Pivot=a[first]
Up=first
Down=last
While (a[up]<pivot)
and ( up<last)
False
True
Up++
While (a[down>pivot)
and ( down>first)
False
True
Down--
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page151
True
If
up<dow
Interchange
a[up] and
False
Interchange a[first] and
a[down]
Program:
/* Quick sort Program */
#include<stdio.h>
#include<conio.h>
int a[50],n;
/* Function to print the array */
void display()
{
int i;
for(i=0;i<n;i++)
printf("%5d",a[i]);
}
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page152
// Recursive call
sort(down+1,last);
//Recursive call
}
}
/* Main function */
void main()
{
int i;
clrscr();
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page153
Output:
Enter number of terms:10
Enter the array elements:
a[0]:56
a[1]:2
a[2]:7
a[3]:2
a[4]:9
a[5]:0
a[6]:12
a[7]:6
a[8]:1
a[9]:7
Sorted array
**************
0
12
56
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page154
Viva Question:
1) What is sorting?
Sorting is the process of arranging the data in some order.
2) What are the various types of sorting?
Bubble sort
Insertion sort
Radix sort
Merge sort
Quick sort
3) What is merging?
Merging means sorting two sorted array into a single sorted array.
4) What are the sorting algorithms based on the technique of Divide
and Conquer?
Merge sort
Quick sort
M.S.P.V.LPolytechnicCollege,Pavoorchatram
Page155