You are on page 1of 155

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

114.00 Fahrenheit=45.56 Centigrade

1B
Aim:

SimpleInterestandCompoundInterestCalculation

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

C and Data Structures Lab Manual

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(); } // For pow function

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

C and Data Structures Lab Manual

1C
Aim:

Toperformarithmeticoperationoftwonumbers

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

C and Data Structures Lab Manual

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 printf("\n\tThe product of %.2f and %.2f printf("\n\tThe quotient of %.2f by %.2f getch(); } = %.2f",a,b,sum); = %.2f",a,b,pro); = %.2f",a,b,quo); printf("\n\tThe difference of %.2f and %.2f= %.2f",a,b,diff);

Output:
Enter the value for A:7 Enter the value for B(B<>0):5 The sum of 7.00 and 5.00 The product of 7.00 and 5.00 The quotient of 7.00 by 5.00 = 12.00 = 35.00 = 1.40

The difference of 7.00 and 5.00= 2.00

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page7

C and Data Structures Lab Manual

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

>= Greater than or equal to <= Lesser than or equal to 4) What are the various logical operators? && || ! - Logical AND - Logical OR - Logical NOT

5) Explain the ternary operator. The ternary opearor is also known as Conditional opearator. Syntax:

(expr 1) ? (expr-2) : expr-3)

The expr-1 is evaluated first. If it is true, the expr-2 is evaluated and it is the value of expr-1 . If expr-1 is false, expr-3 is evaluated and it is the value for expr-1 Example: A=10 B= 15 Max =(A>B )? A : B

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page8

C and Data Structures Lab Manual

Ex2AIdentificationofEvenandOddnumber
Aim:
To write a program to find whether the given number is even or odd.

Flowchart:

Start

Read N

R=N%2

True If R=0

False

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

2B
Aim:

TodisplaystudentsGrade

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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 If ..else ladder 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

C and Data Structures Lab Manual

Aim: 3A Aim:

TocheckforperfectNumber

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

C and Data Structures Lab Manual

Flowchart:

Start

Read N

If N>0

Sum=1 I=2

If N % i=0 False i = i+1

True

Sum=Sum + i

True

If i <= N/2 False If Sum=N True Print Perfect Number False Print NonPerfect Number

Stop

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page15

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

3B
Aim:

TodesignsimpleCalculator

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

C and Data Structures Lab Manual

Flowchart: Start

Read A, B

Display the Menu 1 Add 2 Subtract 3 Multiply 4 - Divide

Read Choice

Switch Choice

Choice=1

Res = A + B
Choice=2

A A A A

Res = A - B
Choice=3

Res = A * B
Choice=4

Res = A / B

Print Res

Stop M.S.P.V.LPolytechnicCollege,Pavoorchatram Page18

C and Data Structures Lab Manual

Program:
/* To design simple calculator */ #include<stdio.h> #include<conio.h> void main() { float 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(); } a,b,res;

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page19

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

4B
Aim:

ToprintFibonaccinumbers

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

C and Data Structures Lab Manual

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 1 1 2 3 5 8 13 21 34

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page24

C and Data Structures Lab Manual

4C
Aim:

Tofindnumberofpositive,negativeandzeroinNelements

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 If i=0 True Ze = ze + 1 If i >0 True pos = pos + 1 False neg = neg + 1

Stop

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page25

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

printf("\n\tNumber of positive numbers=%d",pos); printf("\n\tNumber of negative number=%d",neg); printf("\n\tNumber of zeros=%d",ze); getch(); }

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

False For i=0 to 3 True Print Regno[i],

False For j=0 to 3

True Print mark[i][j]

Print sum[i], avg[i]

Stop

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page34

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

printf("%d",mark[i][j]); } printf("%n"); printf("\n\tTotal Marks printf("%d",sum[i]); printf("\n\tAverage } getch(); } : %.2f",avg[i]); : ");

Output:
Student Detail No : 0 Enter the Student Rno Enter the Mark 0 89 Enter the Mark 1 78 Enter the Mark 2 82 Student Detail No : 1 Enter the Student Rno Enter the Mark 0 76 Enter the Mark 1 80 Enter the Mark 2 83 Student Detail No : 2 Enter the Student Rno Enter the Mark 0 89 Enter the Mark 1 90 Enter the Mark 2 91 Student Detail No : 3 Enter the Student Rno Enter the Mark 0 86 1004 Enter the Student Name NanthaKumar 1003 Enter the Student Name RamKumar 1002 Enter the Student Name ShivaKumar 1001 Enter the Student Name MuthuKumar

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page36

C and Data Structures Lab Manual

Enter the Mark 1 56 Enter the Mark 2 73 --------------OUTPUT-----------------Student No 0 Rno Sub0 Sub1 Sub2 Total Marks Average Student No 1 Rno Name Sub0 Sub1 Sub2 Total Marks Average Student No 2 Rno Name Sub0 Sub1 Sub2 Total Marks Average Student No 3 Rno Name Sub0 Sub1 Sub2 Total Marks Average : 1004 : NanthaKumar 86 56 73 :215 :71.66 : 1003 : RamKumar 89 90 91 :270 :90.00 : 1002 : ShivaKumar 76 80 83 :239 :79.66 : 1001 89 78 82 :249 :83.00 Name : MuthuKumar

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page37

C and Data Structures Lab Manual

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? One dimensional array Two dimensional array Multidimensional array. 4) What is a two dimensional array? Two dimensional is n array of one dimensional array. The elements in the array are referenced with the help of its row and column index. 5) What are the advantages of the functions? Debugging is easier It is easier to understand the logic involved in the program Testing is easier Recursive call is possible Irrelevant details in the user point of view are hidden in functions Functions are helpful in generalizing the program

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page38

C and Data Structures Lab Manual

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) If (X<Y) B

False
Return Y

True
Return X

Print mm

Stop Algorithm:
1. 2. 3. 4.

Define main Function & Declare all variables required. Define a function prototype called double min(double,double). Read two values X,Y. Call Function min(X,Y) and store the return value in a variable.

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page39

C and Data Structures Lab Manual

5. Print the result. 6. In Function Definition Check the smallest number by using a relational Operator(<). Return the smallest value to step 6.

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

C and Data Structures Lab Manual

6BTocalculatefactorialusingrecursivefunction
Aim:
To calculate the factorial of given number using recursive function.

Flow chart:

Start

Read N
Factorial (N)

Call F=Factorial(N)

False If (N<2) B True Return N Print f Return N*Factorial(N 1)

Stop

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page41

C and Data Structures Lab Manual

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) Calculate the value for given number. N*factorial(N - 1); Repeat step A until n becomes 0 or 1.

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); getch(); } /* Recursive factorial function */ long factorial(long N) { if(N<2) return N; else return N*factorial(N-1); } /* Recursive call */ /* Terminating Condition */ /* Calling Function */ printf("\nThe Factorial of %ld is %ld\n",number,f);

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page42

C and Data Structures Lab Manual

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 } Function-name: any valid identifier Return-value-type: data type of the result (default int) void indicates that the function returns nothing A type must be listed explicitly for each parameter unless, the parameter is of type int 3) What is a recursive function? A function that calls itself is called a recursive function. 4) How the functions can be called? 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 5) What is the use of return statement? The return statement is used to exit from the function and return a value. Parameter-list: comma separated list, declares parameters

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page43

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

Flow chart:

Start

Leta[]={aeiouAEIOU}

Count=0

Read string str

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 ++

Print the count

Stop M.S.P.V.LPolytechnicCollege,Pavoorchatram Page45

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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 True Print Palindrome Print Not Palindrome

Stop

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page48

C and Data Structures Lab Manual

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); for(i=0;i<n/2;i++) if(toupper(str[i])!=toupper(str[n-1-i])) { flag=1; break; } /* Check the result*/ if(flag==0) printf("\n\tThe string %s is a palindrome",str); else printf("\n\tThe string %s is not a palindrome",str); getch(); } //calculate string length /* Loop to check the characters*/

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

Flow chart:

Start

Read string str

len=strlen(str) False For i=0 to len-1 True If (str[i]>=65 &&str[i]<=90) False

True A Str[i]=str[i]+32 If (str[i]>=97 &&str[i]<=122 True Str[i]=str[i]-32

False

Print the string

Stop

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page51

C and Data Structures Lab Manual

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(); }
/* Checking for lowercase letters */

/* Checking for upper case letters */

Output:
--------INPUT--------Enter any string->jAVAiNTERFACE ---------OUTPUT-------The Entered string is---->jAVAiNTERFACE The Converted string is---->JavaInterface

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page52

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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 9. Repeat step 8 until N number of values. 10. Display the students detail by structure referencing operator (.). 11. Repeat step 10 for N times.

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page54

C and Data Structures Lab Manual

Flow chart:

Start
structstudent { intrno;
char name[10]; struct dob { int day; int year; char mon[10]; }d; struct address { char * st,*city; }ad; };

Define the nested structure

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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 } getch(); } \t%s\n",stu[i].ad.city);

Output:
Enter No of Students....2 Student Detail No 0 Enter The Student Rno... Enter the Student Name... Enter the Date of Birth... Day Month Year 06 11 1979 552001 ArunKumar

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page57

C and Data Structures Lab Manual

Enter The Address... Enter the Street Name SakthiNagar Enter the City Name Student Detail No 1 Enter The Student Rno... Enter the Student Name... Enter the Date of Birth... Day Month Year 07 November 1979 552002 BanuMathi.K Tenkasi

Enter The Address... Enter the Street Name FirstStreet Enter the City Name ----------OUTPUT---------Student No 0 Student RNo Student Name Date of Birth Address... Street City Student No 1 Student RNo Student Name Date of Birth Address... Street City FirstStreet Madurai 27714 BanuMathi. 7- November - 1979 SakthiNagar Tenkasi 27713 ArunKumar 6- 11 - 1979 Madurai

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page58

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

Flow Chart: Start


unionstudent { intrno; char*name; intmark[10]; }stu;

Define the union

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

C and Data Structures Lab Manual

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 scanf("%d",&stu.mark[i]); } printf("\n--------OUTPUT-----------\n"); printf("Students Record:"); printf("\n\t\tRno printf("%d",stu.rno); printf("\n\t\tName for(i=0;i<3;i++) { printf("\n\t\tMark%d :",i); printf("%d",stu.mark[i]); } getch(); } :"); printf("%s",stu.name); :"); :\t",i);

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page61

C and Data Structures Lab Manual

Output:
Enter the Student Rno : Enter the Student Name : Enter the Mark0 Enter the Mark1 Enter the Mark2 : 87 : 78 : 90 100 Shiva

--------OUTPUT----------Students Record: Rno Name Mark0 Mark1 Mark2 :87 :Shiva :87 :78 :90

Viva Questions:
1) What is a structure? Structure is a collections of related variables under one name and Can contain variables of different data types Commonly used to define records to be stored in files Combined with pointers, can create linked lists, stacks, queues, and trees 2) What is an union? Memory that contains a variety of objects over time Only contains one data member at a time Members of a union share space Conserves storage Only the last data member defined can be accessed. 3) How the members of structures and unions can be accessed? The Members of structures and unions can be accessed with the help of dot operator as Structure variablename . structure member 4) What is a nested structure? Defining a structure within structure is called nested structure.

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page62

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

7. Function call by passing the address using referencing operator (&). 8. Print two numbers after swapping process. 9. Function Definition * Assign the first value to a temporary variable (temp) * Change the pointer value of first number to second number. * Now change the temp value to the first value.

Program:
/* Program to Swap two Numbers Using Pointers */

#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); printf("A=== %d\n",a); printf("B=== %d\n",b); getch(); } /* Function Definition */ void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; } /* contents of pointer */ /* Call of Function */ printf(" Result After Swapping...\n");

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page64

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

9BToreadastringusepointer
Aim:

Read a string. Print the above string such that each line contains a single

character. ( Use pointers)

Flow chart:

Start

Declare char*ptr,*str,c

Read str

ptr=str; len=strlen(ptr)

For i=0 to len1 Print *ptr

ptr++

Stop

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page66

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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 8

The Array Numbers are... 23 78 45 23 8

Reversed Array List ... 8 23 45 78 23

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page71

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

Flowchart

Start

Define a string pointer array

Read the string using while loop

Print the array

Call read Return

If flag=0 True Print String Found

False

PrintStringNot Found

Stop

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page73

C and Data Structures Lab Manual

Read

Read the string to be searched (Temp)

For all elements in string array Yes

No

If (strcmp(str[ i] , temp)

True Flag=0

False Flag=1

return

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

4. Read the String. 5. Increase the pointer value of the variable using increment operator. 6. The count variable is incremented by 1. 7. Repeat step 5 and step until the string pointer is NULL. 8. Print the counted numbers which is the length of the string.

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

Flow Chart: Start

Declare char*s1,*s2,*temp

Read s1,s2

temp=s1 False

While (*temp!=\0)

True temp++;

While (*s2!=\0)

False

True
*temp=*s2 temp++ s2++

Print s1

Stop

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page80

C and Data Structures Lab Manual

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(); } /* Add second string to the end of string2 */

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

C and Data Structures Lab Manual

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? As pointer enables us to access a variable that is defined outside the function. Pointers are more efficient in handling arrays. Pointers reduce the program length and complexity of the program. Pointers increase the execution speed. Use of pointers to character strings results in saving of data storage space in memory. 4) What is the use of void pointer? Void pointer is used to point a variable of any data type. 5) What is the relationship between arrays and pointer? The arrays can be easily manipulated with the help of the pointers of appropriate type. The array name can be assigned to a pointer and the elements in the array can be accessed by incrementing the pointer. For example: int a[5]= {2,3,6,7,1}; int *p=a; Then *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

C and Data Structures Lab Manual

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 Get a new node newnode newnode data=X newnode next= prenode prenode next=newnode Return the address of the new node 4. Define the function to create the list. Store the vowels in a character array. Get a new node and save its address. Store the first data. Let the next field be NULL. Store the remaining data in the link list by using the function insafter( ) that inserts a node after the given node. 5. Define a function Show to print the linked list. 6. Define the main function that calls the function to create the list and to print the list. 7. Stop. next

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page83

C and Data Structures Lab Manual

Flow Chart: Start

Define Array vowels { a, e, i, o, u}

i=0

Get a new node

Store the data vowel[i] in the data field

Set the link field as NULL

Add the node to the list

i = i +1

True If i<6 False Print the List

Stop

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page84

C and Data Structures Lab Manual

Program:
/* To create and print linked list */ #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; } /* { nodeptr newnode; if (p==NULL) { printf("\n Void insertion:"); exit(1); } newnode=getnode(); newnode->data=x; newnode->next=prenode->next; prenode->next=newnode; return newnode; } Function for insertion after a node */ nodeptr insafter(nodeptr p,char x)

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page85

C and Data Structures Lab Manual

void createlist() {

/* Function for creation */

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() { clrscr(); createlist(); printf("\nThe created List"); printf("\n*****************\n\n"); show(); getch(); } /* Main Function */ /* Function for displaying the list */

Output:
The created List ************** a---->e---->i---->o---->u---->NULL

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page86

C and Data Structures Lab Manual

11B
Aim:

Todeletethefirstnodeinthelinkedlistofintegers

To write a C program to delete the first node that contains an integer

data item of a single linked list.

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. Store the data pointed by the first node in a variable. Make first pointer to point the next node as first=first next. Return the address of the new first node. 4. Define a function show to print the linked list. 5. Define the main function as Create the linked list using the function createlist(). Print the list using the function show(). Delete the first node using the function delfirst(). Print the list using the function show(). 6. Stop.

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page87

C and Data Structures Lab Manual

Flow Chart: Start

Read the data

Get a new node

Store the data in the data field

Set the link field as NULL

Add the node to the list

More data? No Print the List

Yes

Delete the first node by adjusting the first i Print the

Stop M.S.P.V.LPolytechnicCollege,Pavoorchatram Page88

C and Data Structures Lab Manual

Program:
/* To create and print linked list */

#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; } /* { nodeptr newnode; if (prenode==NULL) { printf("\n Void insertion:"); exit(1); } newnode=getnode(); newnode->data=x; newnode->next=prenode->next; prenode->next=newnode; return newnode; } Function for insertion after a node */ nodeptr insafter(nodeptr p,int x)

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page89

C and Data Structures Lab Manual

/* Function for creation */ void createlist() { int no; char ans='y'; prenode=first=getnode(); printf("\n Enter the data:"); scanf("%d",&no); prenode->data=no; prenode->next=NULL; fflush(stdin); while(ans=='y' || ans=='Y') { printf("\n Any more data(Y/N)?:"); fflush(stdin); ans=getchar(); if(ans=='Y' || ans=='y') { printf("\n Enter the data:"); scanf("%d",&no); prenode=insafter(prenode,no); } else break; } } /* Function to delete the first node */ int delfirst() { int x; x=first->data; first=first->next; return x; }

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page90

C and Data Structures Lab Manual

/* {

Function for displaying the list

*/

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

C and Data Structures Lab Manual

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

The list after deleting the first node --------------------------------------34---->23---->1---->NULL The deleted data 5

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

C and Data Structures Lab Manual

3) What is the linear structure? In linear data structure the elements are stored in sequential order. The linear data structures are Array Linked list Stack Queue 4) What is a linked list? Linked list: Linked list is a collection of data of same data type but the data items need not be stored in consecutive memory locations.

A Linked list with 3 Nodes 5) What are the operations that can be performed on a linked list? 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

C and Data Structures Lab Manual

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. Define a function show that prints the elements in the stack. Display the menu to the user 1 - Push 2 - Pop 3 List the stack 4 Exit Get the choice from the user If choice =1 read the data and add it to the stack using push( ) function. If the choice = 2 delete the data from the stack using pop ( ) function. If the choice is 3 display the data in the stack. If choice = 4 exit from the program Else repeat the above steps. 6. Stop 5. Define the main function as

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page94

C and Data Structures Lab Manual

Flow chart:

Start

Declare stack array Top=-1

Display the menu 1 Push 2 Pop 3 List the stack 4 Exit C Read users choice

Switch Choice

Choice=1 Choice=2 B Choice=3 Choice=4

Read X

Print Stack

Stop

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page95

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

/*Function to display the stack data*/ void show() { int i; if(s.top==-1) { printf("\nStack Empty"); } else { printf("\nThe stack elements"); printf("\n-------------------\n\t"); for(i=0;i<=s.top;i++) printf("%d\t",s.a[i]); printf("<---top\n"); } } /*Main function*/ void main() { int ch,data; clrscr(); s.top=-1; do { printf("\n\t\t\t Menu"); printf("\n\t\t1->Push"); printf("\n\t\t2->Pop"); printf("\n\t\t3->List stack"); printf("\n\t\t4->Exit"); printf("\nEnter your choice:"); scanf("%d",&ch);

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page98

C and Data Structures Lab Manual

switch(ch) { case 1: printf("Enter the data:"); 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

C and Data Structures Lab Manual

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 Enter your choice:4

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page100

C and Data Structures Lab Manual

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.

7. If the character is an operand


Add it to the postfix expression If the character is ( Push it to the stack If the character is ) Repeatedly Pop the characters from the stack and add it to the postfix expression until ) is encountered. Pop ) If the character is an operator If the precedence of the character is lesser than or equal to the precedence of the operator in the top of the stack repeatedly pop the characters from the stack and add it to the post fix expression till an operator of higher precedence is encountered. Push the operator to the top of the stack.

8. Print the postfix expression. 9. Stop.

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page101

C and Data Structures Lab Manual

Flow chart:

Start

Declarethestack Top=1

Read infix expression

Add ) to the end of infix expression

Push ( to the stack

For each character in True


Switch Character

False

Print Postfix Expression

Stop

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page102

C and Data Structures Lab Manual

Character=Operand Add to postfix expression X

Character = (

Push the character to the t k

Character = )

Repeatedly Pop the characters fromthestackandaddittothe postfix expression till stack[top]=(. Pop(

Character is an

If the precedence of the character less than or equal to the precedence of the operator on stack top Pop the character from the stack and add it to the postfix expression till operator of higher precedenceisreached. P h h h k

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page103

C and Data Structures Lab Manual

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--; //Array to hold the stack // Top pointer

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page104

C and Data Structures Lab Manual

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; } /*Function that returns the precedence of operator*/ /*Function that returns top of the stack*/

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page105

C and Data Structures Lab Manual

/*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); } //Push '(' to the stack //Add ')' at the end

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page106

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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 If the character is a number Then convert the character to integer by subtracting 0 from the character. Push the integer value into the stack. If the character is a operator Pop two values from the stack and perform the operation and store the result to stack. 4. The stack top has the result. Pop it and Print. 5. Stop.

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page108

C and Data Structures Lab Manual

Flowchart Start Declare the k Read the infix False

For each character in infix i True If Character

Pop two operands from the stack. Perform the operation. Store the result in the stack

Push (character -0 ) into the stack

Pop the top of the stack and print the result

Stop

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page109

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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. Stack is used in implementing subroutine calls, recursion, evaluation of arithmetic expression, compilers etc. 4) What is an arithmetic expression? An arithmetic expression is a collection of operators and operands. 5) What is infix, postfix, prefix notation? Infix Notation: If the operator appears between the operands is called infix notation Example: A+B Postfix Notation ( Reverse Polish notation):If the operator comes after the operand then the notation is called postfix notation. Example: AB+ Prefix Notation(Polish notation): If the operator comes before the operand then the notation is called prefix notation. Example: +AB

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page112

C and Data Structures Lab Manual

6) What is the infix, prefix , post fix form of the following expression? a) A + B + C Infix A+B+ C (A+B) * (C+D) A-B / C-D b) (A+B) * (C+D) Postfix AB+C+ AB+CD+* ABC/-Dc) A-B / C-D Prefix ++ABC *+AB+CD --A/BCD

7) Features of Prefix and Postfix expression: The operands are in the same order as the infix notation. Parenthesis is not needed to represent the precedence of operation The priority of operators is irrelevant.

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page113

C and Data Structures Lab Manual

15
Aim:

ImplementationofQueueusingarray

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 the rear=Q-SIZE-1 then Print Queue Full Else Rear=Rear+1. Store the s=date in the rear position Print the queue 3. Define functions to delete the data from the queue If front=rear Print Queue Empty Else front=front+1 Print the deleted element and the queue 4. 5. Define function to print the elements in the queue. Define main function Initialize front = rear =-1 Create a queue with elements Display the menu to the user 1->Insertion 2->Deletion 3->Exit Get the users choice If choice = 1 call the function to add element If choice = 2 call the function to delete the element If choice = 3 then Exit the program Repeat the step 5 till choice = 3. 6. Stop

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page114

C and Data Structures Lab Manual

Flow chart: Start

Declare Queue array Front=Rear=-1

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

C and Data Structures Lab Manual

Add element in a queue: A

If
Rear=QSize1

False Read X

True Print Stack Full

Rear=rear+1 q[rear]=X

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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

/*Function to display the elements in the queue*/ void show() { int i; if (q.front==q.rear) printf("\n\nQueue Empty\n"); else { printf("\n\n The elements in the queue:\n"); printf("******************************\n"); printf("\tFront--->"); for(i=q.front+1;i<=q.rear;i++) printf("%d ",q.a[i]); printf("<---Rear\n"); } } /* Main program*/ void main() { int n,i,ch; clrscr(); q.front=q.rear=-1; printf("\n No. of elements initially in the queue:"); scanf("%d",&n); /* Creating a queue with n elements */ for (i=0;i<n;i++) { q.rear++; printf("\n\tEnter the element:"); scanf("%d,",&q.a[i]); } show(); while(1) { printf("\n\n\t\t Select your choice:"); printf("\n\t1->Insertion");

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page118

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

Select your choice: 1->Insertion 2->Deletion 3->exit Enter your choice:2 The deleted element is 2 The elements in the queue: *********************** Front--->4 5 45 <---Rear Select your choice: 1->Insertion 2->Deletion 3->Exit Enter your choice:3

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

C and Data Structures Lab Manual

16CreationbinaryTree

Aim:
To write a C program to create a binary tree.

Algorithm:
The following algorithm to create a binary using sequential representation.

1. Define the structure of a node. 2. Read number of data in the binary tree. 3. Define function maketree( ) to get
the address of the created node. a new node that stores the data in the data field and sets the left and right pointer to NULL and returns

4. Define a function create( ) for creating the tree as


a) Declare a pointer array that stores the address of the node. b) First the root node is created and its address is stored at the first index of the array. c) Then using for loop the data are read and stored in the data field using the maketree( ) function. If the array index i an even number then the node is linked as the left child of the node (i/2). If the array index i is an odd number then the node is linked as the right child of the node (i/2). d) The leaf nodes left and right pointers are declared NULL.

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

C and Data Structures Lab Manual

Flow chart: Start

While true True Display the menu 1-Create tree 2-Inorder List 3-Exit

False Exit

Read users Choice

Switch Choice

Choice = 1 A Choice = 2 B X

Choice = 3 Stop

Exit

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page122

C and Data Structures Lab Manual

Creating a tree:

Read number of nodes in the tree N

Read the data

Create the root node. Store its address in the first index of the array

For i=2 to N True Read the data

False

Store data in the data field

If

i%2 = 0

Insert the new node as the right child of the node (i/2)

Insert the new node as the left child of the node (i/2)

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page123

C and Data Structures Lab Manual

Inorder Traversal using Recursion

Inorder (p)

True If P!=NUL

p=p

llink

False

Print data in the node

p=p rlink

True If P!=NUL False Return

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page124

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

t=(struct node*) malloc(sizeof(struct node)); t->data=item; t1[k++]=t; if(i%2==0) { 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

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

Press any key to continue... Main Menu ---------1.Create Tree 2.Inorder List 3.Exit Select the option <1,2,3>...2 Inorder List 4 2 5 1 3 Press any key to continue... Main Menu ---------1.Create Tree 2.Inorder List 3.Exit Select the option <1,2,3>...3

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page128

C and Data Structures Lab Manual

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 the structure of a node. Read number of data in the binary tree. 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. 7. Define a function create( ) for creating the tree as Declare a pointer array that stores the address of the node. First the root node is created and its address is stored at the first index of the array. 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. 9. The leaf nodes left and right pointers are declared NULL. 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. 11. Define the main function that calls the functions create( ) and preorder to create a tree and print the in order traversal of the tree. Stop.

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page129

C and Data Structures Lab Manual

Flow chart: Start

While true True Display the menu 1-Create tree 2-Preorder List 3-Exit

False Exit

Read users Choice

Switch Choice

Choice = 1 A Choice = 2 B

Choice = 3 Stop

Exit

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page130

C and Data Structures Lab Manual

Creating a tree:

Read number of nodes in the tree N

Read the data

Create the root node. Store its address in the first index of the array

For i=2 to N True Read the data

False

Store data in the data field

If

i%2 = 0

Insert the new node as the right child of the node (i/2)

Insert the new node as the left child of the node (i/2)

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page131

C and Data Structures Lab Manual

Pre order traversal using recursion

Preorder (p)

Print data in the node False p=p llink

True If P!=NUL

p=p rlink

If P!=NUL

Return

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page132

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

t=(struct node*) malloc(sizeof(struct node)); t->data=item; t1[k++]=t; if(i%2==0) { 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; } /* Pre_order traversal using recursion */ void preorder(struct node *p) { if(p!=NULL) { printf("%d\t",p->data); preorder(p->llink); preorder(p->rlink); } } /* Main function */ void main() { struct node *p; int opt,pos,item; clrscr();

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page134

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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 2 4 5 3 Press any key to continue.... Main Menu --------------1.Create 2.Preorder 3.Exit Select the option <1,2,3>...3

Viva Questions:
1) What is a tree? Trees are collection of items or elements along with the relationship with one another. Trees are used to represent hierarchical relationship. 2) What is a root node? The node without parent is called a root node. 3) What is a leaf node? The nodes without children are called leaves 4) What is a binary tree? A binary tree, T, is either empty, or is such that: T has a special node called the root node. 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

C and Data Structures Lab Manual

LT and RT are binary trees. Every node in a binary tree can have atmost two children. 5) What is a complete binary tree? A binary tree is complete binary tree if 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. 6) What is a full binary tree? A binary tree is full if it contains maximum possible number of nodes at all the levels. 7) What are the three types of traversal in binary tree? Inorder Traversal Preorder Traversal Post order traversal 8) What is a binary search tree? A binary tree is said to be binary search tree if for every node N 1. All the elements in its left subtree are smaller than the value of N. 2. All the elements in its right subtree are larger than the value of N.

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page137

C and Data Structures Lab Manual

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 f) 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.

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page138

C and Data Structures Lab Manual

3. Define the main function. a) Read the number of elements in array. b) Read the array elements c) Call Linear search d) Call Binary search 4. Stop

Flow chart:

Start

ReadN ReadArrayElements

Call Linear Search

A Call Binary Search B stop

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page139

C and Data Structures Lab Manual

Binary Search

Binary Search

Read X

Lb = 0 Ub = N-1

While lb <= ub

No
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

C and Data Structures Lab Manual

Linear Search Linear Search

Read X

For each element in the array

All elements processed Print FAILURE

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

C and Data Structures Lab Manual

/* Function for binary search */ void binary(int a[],int n) { int data,lb,ub,mid,i,j,temp; /* Sorting the Array */ for(i=0;i<n;i++) { for(j=0;j<n-1;j++) { if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } printf("\n\tThe array in sorted order\n\n\t"); for(i=0;i<n;i++) printf("%5d",a[i]); lb=0; ub=n-1; printf("\n\n\tEnter the item to search:"); scanf("%d",&data); while(lb<=ub) { mid=(lb+ub)/2; if(data==a[mid]) break; else { if( data<a[mid]) ub=mid-1;

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page142

C and Data Structures Lab Manual

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); printf("\n\nUsing Binary search "); printf("\n-------------------\n"); binary(a,n); getch(); } //Call Binary Search //Call Linear search

Output:
Enter the number of data :7 Enter the elements: a[0]:8 a[1]:5

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page143

C and Data Structures Lab Manual

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 3 5 7 7 8 9 Enter the item to search:67 The search item is not present in the array

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
Linear search can be performed in sorted and unsorted data If an data is not present in the array we have to search the entire list from the first to last Time complexity F(n) =O (n)

Binary Search
Binary search can be performed only in sorted data At each scan the number elements to be checked is reduced by 2 Time Complexity F(n) ==[ log 2n ]+ 1

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page144

C and Data Structures Lab Manual

19
Aim:

InsertionSort

To write a C program to read 10 elements and sort the array using insertion sort.

Algorithm:
1. 2. 3. Read the elements into the array. Take the second element. Compare it with the first element. If the second element less than the first element interchange them. 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. 6. 7. When the ith element is placed, the elements in the array from the 0th to the ith position will be in the sorted order. The above process is continued for all the elements in the array. Stop

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page145

C and Data Structures Lab Manual

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

C and Data Structures Lab Manual

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]; { a[j+1]=a[j]; j--; } a[j+1]=temp; } printf("\n\n\nThe sorted array"); printf("\n~~~~~~~~~~~~~~~~~\n"); for (i=0;i<10;i++) printf("%5d",a[i]); getch(); } j=i-1; while(temp<a[j] && j>=0) */

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page147

C and Data Structures Lab Manual

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 7 2 8 3 87 3 7 2

The sorted array ~~~~~~~~~~~~~ 2 2 3 3 7 7 8 23 87 454

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page148

C and Data Structures Lab Manual

20
Aim:

ImplementationofQuickSort

Write a C program to read 10 elements and sort the above numbers

using quick sort. The recursive algorithm consists of four steps A. If there are one or less elements in the array to be sorted, return immediately. B. Pick an element in the array as a "pivot" element. (Usually the leftmost element in the array is used.) C. Split the array into two parts - one with elements larger than the pivot and the other with elements smaller than the pivot. D. Recursively repeat the algorithm for both halves of the original array

Algorithm:
1. Define the array 2. Define the function sort( first, last) for partitioning and sorting the array is a) b) c) d) If (first < last) continue else the array is sorted return Let the pivot element be A[first]. Initialize up=first and down=last 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) Interchange a[first] and a[down]. The pivot element is fixed at the index down. If (first < last) The sorting is again continued for the arrays a[first] to a[down-1] and a[down+1] to a[last]. 3. The main function is defined as a) b) c) d) Read the number of terms N. Read the array elements. Call the sort function with sort(0,n-1). Print the array.

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page149

C and Data Structures Lab Manual

Flowchart

Start

Read N

Read the array elements

Call sort(0,n-1)

Sort

B Print the sorted array

Stop

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page150

C and Data Structures Lab Manual

Partitioning and sorting Sort

B Sort(first, last)

If first<last

Pivot=a[first] Up=first Down=last

While (a[up]<pivot) and ( up<last) True Up++

False

While (a[down>pivot) and ( down>first) True Down--

False

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page151

C and Data Structures Lab Manual

True If up<dow False Interchange a[first] and a[down] Interchange a[up] and

Call sort(first, down-1) Call sort(down+1,last)

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

C and Data Structures Lab Manual

/* Recursive function to partition and sort the array */ void sort(int first,int last) { int temp,pivot,up,down; if(first<last) { pivot=a[first]; up=first; down=last; /* Partitioning */ while(up<down) { while(a[up]<=pivot && up<last) up++; while(a[down]>=pivot && down>first) down--; if(up<down) { temp=a[up]; a[up]=a[down]; a[down]=temp; } } temp=a[first]; a[first]=a[down]; a[down]=temp; sort(first,down-1); sort(down+1,last); } } /* Main function */ void main() { int i; clrscr(); // Recursive call //Recursive call

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page153

C and Data Structures Lab Manual

printf("Enter number of terms:"); scanf("%d",&n); printf("Enter the array elements:\n"); for(i=0;i<n;i++) { printf("a[%d]:",i); scanf("%d",&a[i]); } sort(0,n-1); printf("\nSorted array\n"); printf("**************\n"); display(); getch(); }

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 1 2 2 6 7 7 9 12 56

M.S.P.V.LPolytechnicCollege,Pavoorchatram

Page154

C and Data Structures Lab Manual

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

You might also like