0% found this document useful (0 votes)
66 views124 pages

Ii Ece CS3362 CP&DS Lab

Uploaded by

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

Ii Ece CS3362 CP&DS Lab

Uploaded by

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

4931_Grace College of Engineering, Thoothukudi

GRACE COLLEGE OF ENGINEERING


MULLAKKADU, THOOTHUKUDI -628005

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

CS3362 C PROGRAMMING AND DATA


STRUCTUIRES LABORATORY

LAB MANUAL

Prepared by

S. MANICKAM M.E.,
Assistant Professor /CSE

CS3362_CP&DS-Lab
S. MANICKAM M.E., (PHD), AP/CS GRACE COE |
4931_Grace College of Engineering, Thoothukudi
2

CS3362 C PROGRAMMING AND DATA STRUCTURES LABORATORY

OBJECTIVES:
 To develop applications in C
 To implement linear and non-linear data structures
 To understand the different operations of search trees
 To get familiarized to sorting and searching algorithms

LIST OF EXPERIMENTS

1. Practice of C programming using statements, expressions, decision making and iterative statements
2. Practice of C programming using Functions and Arrays
3. Implement C programs using Pointers and Structures
4. Implement C programs using Files
5. Development of real time C applications
6. Array implementation of List ADT
7. Array implementation of Stack and Queue ADTs
8. Linked list implementation of List, Stack and Queue ADTs
9. Applications of List, Stack and Queue ADTs
10.Implementation of Binary Trees and operations of Binary
Trees
11. Implementation of Binary Search Trees
12. Implementation of searching techniques
13. Implementation of Sorting algorithms: Insertion Sort, Quick Sort, Merge Sort
14. Implementation of Hashing – any two collision TOTAL: 45
PERIODS

OUTCOMES:

At the end of the course, the students will be able to:


CO1 Use different constructs of C and develop applications
CO2 Write functions to implement linear and non-linear data structure operations
CO3 Suggest and use the appropriate linear / non-linear data structure operations for a given problem
CO4 Apply appropriate hash functions that result in a collision free scenario for data storage and
Retrieval
CO5 Implement Sorting and searching algorithms for a given application

CS3362_CP&DS-Lab
S. MANICKAM M.E., (PHD), AP/CS GRACE COE |
4931_Grace College of Engineering, Thoothukudi
3

CS3362_CP&DS-Lab
S. MANICKAM M.E., (PHD), AP/CS GRACE COE |
4931_Grace College of Engineering, Thoothukudi
4

PRACTICE OF C PROGRAMMING USING


EX.NO: 1(A) STATEMENTS

AIM:

To check whether the given integer is PALINDROME or NOT.

ALGORITHM :

Steps:
1. [Initialize] Start
2. [Input the original number] read num
3. [Set number num to a variable n] n ← num
4. [Iterate until num is not equal to 0. If num value becomes 0, control comes out of the loop.
So num’s original value is lost. So, num value is stored in other variable n in step 3. In step
4, reverse of the number is calculated.] while ( num != 0) do remainder ← num mod 10 num
← num/10 rev ← rev * 10 +remainder 5. [Print reverse number] print rev
6. [Check if original number & reverse number are same. If it is, number is palindrome.
Otherwise, not palindrome] if (rev = n) then print palindrome else print not a
palindrome endif
7. [Finished]
End
PROGRAM
:
/* Program to calculate whether a given number is palindrome or not */
#include<stdio.h>
#include<conio.h>
int main()
{
int temp,rev=0,num,remainder ;
clrscr();
printf("Enter the number\n");
scanf("%d",&num);
temp=num;
while(num!=0) //Reversing the number
4931_Grace College of Engineering, Thoothukudi
5

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
6

{
remainder = num%10;
num = num/10;
rev = rev*10+ remainder;
}
printf("The reverse number is %d",rev);
if(rev == temp)
printf("\n%d is a
palindrome",temp); else
printf("\n%d is not a palindrome", temp); getch(); }

OUTPUT:

RESULT:

Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
7

EX.NO: 1(B) PRACTICE OF C PROGRAMMING USING


EXPRESSIONS

Program:

Write a program to take input of name, rollno and marks obtained by a student in 4 subjects of
100 marks each and display the name, rollno with percentage score secured.

AIM:

To Write a program to take input of name, rollno and marks obtained by a student in 4 subjects
of 100 marks each and display the name, rollno with percentage score secured.

Algorithm:

1. Start
2. Define variables: name, rollno, sub1, sub2, sub3, sub4, sum, score
3. Take input from keyboard for all the input variables
4. Calculate the sum of marks of 4 subjects and also calculate the percentage score as: sum
= sub1 + sub2 + sub3 + sub4; score = (sum/400) * 100
5. Display the name, roll number and percentage score.
6. Stop

PROGRAM :

#include<stdio.h>
#include<conio.h>
void main()
{
char name[20];
int rollno;
float sub1, sub2, sub3, sub4, , sum, score;
printf("Enter name of student: ");
scanf(“%s”,&name[]);
printf ("\n Enter Roll Number: ");
scanf("%d", &rollno);
printf ("\n Enter Marks in 4 Subjects:\n"); scanf("%f%f%f
%f", &sub1, &sub2, &sub3, &sub4);

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
8

sum=sub1+sub2+sub3+sub4;
score = (sum/500)*100;
printf("\n Name of student: %s", name[]);
printf("\n Roll Number: %d", rollno);
printf ("\nPercentage score secured: %2.2f%c", score,'%');
getch();
}
OUTPUT:

RESULT:
Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
9

EX.NO: 1(C) Practice of C programming using decision


making

AIM:
To find the roots of the quadratic equation (ax2+bx+c=0) with different possible input
values for a, b and c. (DECISION MAKING)

ALGORITHM :
Quadratic Equation [This algorithm takes three coefficients as input and computes the roots]
Steps:
1. [Initialize] Start
2. [Input coefficients of quadratic equation] read a ,b, c
3. [Check for valid coefficients] If a =0 and b= 0 then print “Roots cannot be determined”
4. [Check for linear equation] else a=0then root1 ← (-c/b) print “Linear equation”,root1 goto
step
5. [Compute discriminate value] disc ← b*b-4*a*c
6. [Based on discriminate value, classify and calculate all possible roots and print them]
5.1 [If discriminate value is 0, roots are real &
equal.] if disc=0 then
root1← root2 ← (-b/2*a)
` print “Real & equal roots”, root1, root2
5.2 [ If discriminate value is >0, roots are real & distinct.]
else if disc>0then
root1← (-b+√disc)/(2*a) root2 ← (-b-√disc)/(2*a)
print “Real & distinct roots”, root1, root2
5.3 [ If discriminate value is <0 ,roots are
imaginary.] else
real ← -b/(2*a)
imag ← √(fabs(disc))/(2*a)
root1 ← (real) + i (imag)
root2 ← (real) - i (imag)
print “Imaginary roots”, root1, root2
endif
endif
6. [Finished] End

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
10

PROGRAM :
/* Program to calculate all possible roots of a quadratic equation
*/ #include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
float a, b, c, disc;
float root1,root2,real,imag;
clrscr();
printf("Enter a,b,c values\n");
scanf("%f%f%f",&a,&b,&c);
if( (a == 0) && (b == 0) &&(c==0))
{
printf("Invalid coefficients\n");
printf(" Try Again with valid inputs !!!!\
n"); getch();
}
disc = b*b - 4*a*c;
if(disc == 0)
{
printf("The roots are real and equal\n");
root1 = root2 = -b/(2*a);
printf("Root1 = %.3f \nRoot2 = %.3f", root1,root2);
}
else if(disc>0)
{
printf("The roots are Real and Distinct\n");
root1 = (-b+sqrt(disc)) / (2*a);
root2 = (-b-sqrt(disc)) / (2*a);
printf("Root1 = %.3f \nRoot2 = %.3f",root1,root2);
}
else
{
printf("The roots are Real and Imaginary\n");
real = -b / (2*a);
imag = sqrt(fabs(disc)) / (2*a);//fabs() returns only numberignoring sign
printf("Root1 = %.3f + i %.3f \n",real,imag);
printf("Root2 = %.3f - i %.3f",real,imag);

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
11

}
getch();
}

OUTPUT

RESULT:
Thus the C programs can be executed and the output was verified successfully.
4931_Grace College of Engineering, Thoothukudi
12

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
13

EX.NO: 1(D) Practice of C programming using Iterative


statements

There are three types of looping statements:


 For Loop(Evaluation of Polynomial)
 While Loop
 Do-while loop
AIM:
To find the value of the polynomial Design and develop an algorithm for evaluating the
polynomial f(x) = a4 x4 + a3 x3 + a2 x2+ a1 x + a0, for a given value of x and its coefficients
using Horner’s method.
ALGORITHM :
ALGM: EVAL_POLYNOMIAL f(x) = a4x4+ a3x3+ a2x2+ a1x+ a0using Horner’s method
Steps:
1. [Initialize]
Start
2. [Input the number of coefficients n] read n
3. Set sum to 0
4. [Read all coefficients a1, a2, a3, a4and constanta0]
For each value i in array a(i)do
read n+1 coefficients
endfor 5.
[Input variable x]
read x
6. [Iterate from n to 0. Calculate each term a4x4, a3x ,a2x2,a1x, a0 . ]
For each value iin array a(i) do
sum ← sum * x + a[i]
endfor
7. Print sum
8. [Finished
] End

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
14

PROGRAM :
/* Evaluating the polynomial f(x) = a4x4+ a3x3+ a2x2+ a1x+ a0 using Horner’s method (n, i,
sum, a[], x) */
#include <stdio.h>

int main()
{
float a[100],sum=0,x;
int n,i;
printf("\nEnter degree of the polynomial X :: ");
scanf("%d",&n);
printf("\nEnter coefficient's of the polynomial X :: \n");
for(i=n;i>=0;i--)
{
printf("\nEnter Coefficient of [ X^%d ] :: ",i);
scanf("%f",&a[i]);
}

printf("\nEnter the value of X :: ");


scanf("%f",&x);

for(i=n;i>0;i--)
{
sum=(sum+a[i])*x;
}

sum=sum+a[0];

printf("\nValue of the polynomial is = [ %f ]\n",sum);

return 0;
}

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
15

OUTPUT:

AIM: (USING DO While)


To compute Sin(x) using Taylor series approximation given by

ALGORITHM:
SINE SERIES[this algorithm takes degree as an input to print the sine function value]
Input : Degree of polynomial
Output : Sine function value
Step 1: start Step
2: enter the degree
Step 3: convert degree into radian
X <- degree*(PI/180)
Step 4: check the given number is odd/not
If(it is a odd number)
Then
{
term = nume/deno;
nume = -nume*x*x;
deno = deno*i*(i+1);
}
else

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
16

{
{
If(term<0.001)
{
Print the sine value
}
else
{
Check the number
}
}
Step 5: stop
PROGRAM:
/* Program to calculate sine value of given angle */
#include<stdio.h>
#include<math.h>
#define PI 3.142
int main()
{
int i, degree;
float x,
sum=0,term,nume,deno;
clrscr();
printf("Enter the value of degree");
scanf("%d",&degree);
x = degree * (PI/180); //converting degree into radian
nume = x;
deno = 1;
i=2;
do
{ //calculating the sine value.
term = nume/deno;
nume = -nume*x*x;
deno = deno*i*(i+1);
sum=sum+term;
i=i+2;
}
while (fabs(term) >= 0.00001); // Accurate to 4
digits printf("The sine of %d is %.3f\n", degree, sum);
printf("The sine function of %d is %.3f", degree, sin(x));
getch();
4931_Grace College of Engineering, Thoothukudi
17

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
18

}
OUTPUT:

RESULT:
Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
19

EX.NO: 2(A) Practice of C programming using Functions

AIM: (USING Functions)


To compute two integer number addition.
ALGORITHM:
Step 1: start
Step 2: enter the two numbers
Step 3: sum value is the sction of function call
Step 4: addNumbers takes as a part of function definition and their prototype
Step 5: stop
PROGRAM:
#include <stdio.h>
int addNumbers(int a, int b); // function
prototype int main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum =
%d",sum); return 0;
}
int addNumbers(int a, int b) // function definition
{
int result;
result = a+b;
return result; // return statement
}

OUTPUT

RESULT:
Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
20

EX.NO: 2(B) Practice of C programming using Arrays

AIM: (USING Arrays)


To 5 values from the user and store them in an array.
ALGORITHM:
Step 1: start
Step 2: enter the 5 integer values from user
Step 3: Store the values in Array
Step 4: Then displaying the values in an array
Step 5: stop

// Program to take 5 values from the user and store them in an array
// Print the elements stored in the array
Program:
#include <stdio.h>
int main() {
int values[5];
printf("Enter 5 integers: ");
// taking input and storing it in an array
for(int i = 0; i < 5; ++i)
{
scanf("%d", &values[i]);
}
printf("Displaying integers: ");
// printing elements of an array
for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
21

OUTPUT:

Example 2: Pass Arrays to Functions


#include <stdio.h>

float calculateSum(float num[]);

int main()

float result, num[] = {23.4, 55.8, 22.6, 333.8, 40.5, 18};

// num array is passed to

calculateSum() result =

calculateSum(num); printf("Result =

%.2f", result);

return 0;

float calculateSum(float num[])

int i;

float sum =

0.0;

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

{
4931_Grace College of Engineering, Thoothukudi
22

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
23

sum += num[i];

return sum;

OUTPUT

RESULT:
Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
24

EX.NO: 3(A) Implement C programs using Pointers

AIM:
To understand programming with Pointer, String and Function call by reference.
Program: Write a program to find biggest among three numbers using pointer.
#include <stdio.h>
int main()
{
int a,b,c;
int*ptra=&a,*ptrb=&b,*ptrc=&c;
printf("enter three values");
scanf("%d%d%d",ptra,ptrb,ptrc);
printf("a=%d\n b=%d\n c=%d\n",*ptra,*ptrb,*ptrc);
if((*ptra>*ptrb && *ptra>*ptrc))
printf("biggest number=%d",*ptra);
else if((*ptrb>*ptra && *ptrb>*ptrc))
printf("biggest number =%d",*ptrb);
else
printf("biggest number=%d",*ptrc);
return 0;
}

OUTPUT

RESULT:
Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
25

EX.NO: 3(B) Implement C programs using Structures

AIM
To understand programming with Structure.
Program 1: Write a C program to create, declare and initialize structure.

PROGRAM:
#include <stdio.h>
/*structure declaration*/
struct employee
{
char
name[30]; int
empId; float
salary;
};
int main()
{
/*declare and initialization of structure variable*/
struct employee emp={"Manickam",001,80000.00};
printf("\n Name: %s" ,emp.name);
printf("\n Id: %d" ,emp.empId);
printf("\n Salary: %f\n",emp.salary);
return 0;
}

OUTPUT
4931_Grace College of Engineering, Thoothukudi
26

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
27

STUDENT RECORD USING ARRAY OF STRUCTURES


Write a C program to maintain a record of "n" student details sing an array of structures with
four fields (Roll number, Name, marks, and Grade). Each field is of an appropriate data type.
Print the marks of the student given name as input.
AIM
To writw Write a C program to maintain a record of "n" student details.
ALGORITHM:
Input: Enter the number of students
Output: print the marks of the student.
Step1: start
Step2: enter the num of students
Step3: if(strcmp(s[i].name,
sname==0) Then
{
Print the marks of students name & USN
}
Else
{
Print the given date is invaid
}
Step4: stop
Program:
/* program to maintain a record of student using structrue */
#include <stdio.h>
#include <conio.h>
struct student
{
int rollno, marks;
char name[20], grade;
};
void main()
{
int i,n,found=0;
struct student s[10];
char sname[20];

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
28

clrscr();
printf("Enter the number of student details n=");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nenter the %d student details \n",i+1);
printf("enter the roll number:");
scanf("%d",&s[i].rollno);
printf("enter the student name without white spaces:");
scanf("%s", s[i].name); printf("enter the marks : ");
scanf("%d", &s[i].marks);
printf("enter the grade : ");
fflush(stdin); scanf("%c",&s[i].grade);
}
printf("\nStudent details are \n"); printf("\nRollno\tName\t\t\tMarks\tGrade\
n");
for(i=0;i<n;i++)
printf("%d\t%s\t\t%d\t%c\n", s[i].rollno, s[i].name, s[i].marks, s[i].grade); printf("\nEnter the
student name to print the marks:");
scanf("%s", sname);
for(i=0;i<n;i++)
{
if(strcmp(s[i].name,sname)==0)
{
Printf(“\Marks of the student is : %d”,s[i].marks);
found=1;
}
}
if(found ==0)
printf(“ Given student name not found\n”);
getch();
}

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
29

Output:

RESULT:
Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
30

EX.NO: 4
Implement C programs using Files

A im:
To implement C programs using Files.
Program:
# includ e <st d io .
h> # includ e <st d l
ib . h> in t main()
{
in t num;
FILE *fptr;

/ / use appropriat e locat ion i f you are using Mac O S or L


inux f p t r = f open(" F : \ \ program. t x t ", " w ");

i f ( f p t r == N U L L )
{
print f (" E
rror!"); exit ( 1 ) ;
}

print f (" E n t er num: ");


scanf ("% d ",& num);

f print f ( f p t r , "% d ",


num); f c lose( f p t r);

ret urn 0 ;
}

O U TP U T:

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
31

P rogram 2
COPY THE CONTENTS OF FILE
Given two university information files "studentname.txt" and "usn.txt" that contains students
names and USN respectively. Write a C program to a new file called "output.txt" and copy the
content of files "studentname.txt" and "usn.txt" into output file in the sequence shows below.
Display the content of output file "output.txt" on to the screen.
Note : Students are required to create two files “Studname.txt” and “Studusn.txt” with the
Contents

ALGORITHM:
Input : Create the file fp1,fp2,fp3
Output : Print whether the files are found or not
step1:start
Step2: create the files (fp1,fp2, & fp3)
Step3: while(!feof((fp1)&&!feof(fp2))
Step4:Both files the not created the print the file not found
a). if only one file is created then print files not
found. b).if both files are created the print files are
found.
Step5: stop
Program
/* Program on merge two files */
#include<stdio.h>
int main()
{
FILE *fp1,*fp2,*fp3;
char usn[20], name[20];
fp1=fopen("studname.txt", "r");
if(fp1 == NULL)
printf(" File not found");
fp2=fopen("studusn.txt", "r");
if(fp2 == NULL)
printf(" File not found");
4931_Grace College of Engineering, Thoothukudi
32

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
33

fp3=fopen("output.txt","w");
while( !feof(fp1) && !feof(fp2) )
{
fscanf(fp1,"%s",name);
fscanf(fp2,"%s",usn);
fprintf(fp3,"%15s %10s\n", name,
usn);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
fp3=fopen("output.txt","r"); printf("\
n \
n");
printf(" Name USN \n");
printf("---------------------------\n");
while(!feof(fp3))
{
fscanf(fp3,"%s",name);
fscanf(fp3,"%s \n",usn);
printf("%-15s %10s \n", name,usn);
}
fclose(fp3);
getch();
}
4931_Grace College of Engineering, Thoothukudi
34

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
35

Output:

RESULT:
Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
36

EX.NO: 5 Development of real time C applications

A im:
To d evelop an calculat or app w i t h t he help of C programming.

Algorithm of Calculator Program

Step 1: Declare local variables n1, n2, res, opt. For example, where n1 and n2 take two
numeric values, res will store results and opt variable define the operator symbols.

Step 2: Print the Choice (Addition, Subtraction, multiplication, division, etc.

Step 3: Enter the Choice

Step 4: Takes two numbers, n1 and n2

Step 5: Switch case jump to an operator selected by the user

Step 6: Store result into res variable.

Step 7: Display the operation result

Step 8: Exit from the program.

Different ways to create a Calculator Program in C

Following are the different ways to write a Calculator Program in the C language.

1. Calculator Program in C using the switch statement


2. Calculator Program in C using if else if statement
3. Calculator Program in C using do-while loop and switch statement
4. Calculator Program in C using function and switch

statement Example 1: Calculator Program in C using the switch

statement

Let's write a program to create a Calculator program using switch statement


4931_Grace College of Engineering, Thoothukudi
37

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
38

1. #include <stdio.h>
2. int main()
3. {
4. // declare local variables
5. char opt;
6. int n1, n2;
7. float res;
8. printf (" Choose an operator(+, -, *, /) to perform the operation in C Calculator \n ");
9. scanf ("%c", &opt); // take an operator
10. if (opt == '/' )
11. {
12. printf (" You have selected: Division");
13. }
14. else if (opt == '*')
15. {
16. printf (" You have selected: Multiplication");
17. }
18.
19. else if (opt == '-')
20. {
21. printf (" You have selected: Subtraction");
22. }
23. else if (opt == '+')
24. {
25. printf (" You have selected: Addition");
26. }
27. printf (" \n Enter the first number: ");
28. scanf(" %d", &n1); // take fist number
29. printf (" Enter the second number: ");
30. scanf (" %d", &n2); // take second
number 31.
32. switch(opt)
33. {
34. case '+':
35. res = n1 + n2; // add two numbers
36. printf (" Addition of %d and %d is: %.2f", n1, n2, res);
37. break;
38.
39. case '-':

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
39

40. res = n1 - n2; // subtract two numbers


41. printf (" Subtraction of %d and %d is: %.2f", n1, n2, res);
42. break;
43.
44. case '*':
45. res = n1 * n2; // multiply two numbers
46. printf (" Multiplication of %d and %d is: %.2f", n1, n2, res);
47. break;
48.
49. case '/':
50. if (n2 == 0) // if n2 == 0, take another number
51. {
52. printf (" \n Divisor cannot be zero. Please enter another value ");
53. scanf ("%d", &n2);
54. }
55. res = n1 / n2; // divide two numbers
56. printf (" Division of %d and %d is: %.2f", n1, n2, res);
57. break;
58. default: /* use default to print default message if any condition is not satisfied */
59. printf (" Something is wrong!! Please check the options ");
}
return 0;
}

Ou tp u t

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
40

Example 2: Calculator Program in C using do while loop and switch statement


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

int main()
{
// declaration of local variable
op; int op, n1, n2;
float
res; char
ch; do
{
// displays the multiple operations of the C Calculator
printf (" Select an operation to perform the calculation in C Calculator: ");
printf (" \n 1 Addition \t \t 2 Subtraction \n 3 Multiplication \t 4 Division \n 5 Square \t \t 6
Square Root \n 7 Exit \n \n Please, Make a choice ");

scanf ("%d", &op); // accepts a numeric input to choose the operation

// use switch statement to call an operation


switch (op)
{
case 1:
// Add two numbers
printf (" You chose: Addition");
printf ("\n Enter First Number: ");
scanf (" %d", &n1);
printf (" Enter Second Number: ");
scanf (" %d", &n2);
res = n1 + n2; // Add two numbers
printf (" Addition of two numbers is: %.2f", res);
break; // break the function

case 2:
// Subtract two numbers
printf (" You chose: Subtraction");
printf ("\n Enter First Number: ");
scanf (" %d", &n1);
printf (" Enter Second Number: ");
scanf (" %d", &n2);
res = n1 - n2; // subtract two numbers
printf (" Subtraction of two numbers is: %.2f", res);
break; // break the function

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
41

case 3:
// Multiplication of the numbers
printf (" You chose: Multiplication");
printf ("\n Enter First Number: ");
scanf (" %d", &n1);
printf (" Enter Second Number: ");
scanf (" %d", &n2);
res = n1 * n2; // multiply two numbers
printf (" Multiplication of two numbers is: %.2f",
res); break; // break the function

case 4:
// Division of the numbers
printf (" You chose:
Division");
printf ("\n Enter First Number: ");
scanf (" %d", &n1);
printf (" Enter Second Number: ");
scanf (" %d", &n2);
if (n2 == 0)
{
printf (" \n Divisor cannot be zero. Please enter another value ");
scanf ("%d", &n2);
}
res = n1 / n2; // divide two numbers
printf (" Division of two numbers is: %.2f", res);
break; // break the function

case 5:
// getting square of a number
printf (" You chose: Square");
printf ("\n Enter First Number:
"); scanf (" %d", &n1);

res = n1 * n1; // get square of a number


printf (" Square of %d number is: %.2f", n1, res);
break; // break the function

case 6:
// getting the square root of the
number printf (" You chose: Square
Root"); printf ("\n Enter First
Number: "); scanf (" %d", &n1);

res = sqrt(n1); // use sqrt() function to find the Square


Root printf (" Square Root of %d numbers is: %.2f", n1,
res); break; // break the function
4931_Grace College of Engineering, Thoothukudi
42

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
43

case 7:
printf (" You chose: Exit");
exit(0);
break; // break the function

default:
printf(" Something is wrong!! ");
break;
}
printf (" \n \n ********************************************** \n ");
} while (op != 7);

return 0;
}
OU T P U T

RESULT: Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
44

EX.NO: 6 Array implementation of List ADT

AIM:
To implement array implementation of List ADT.
Algorithm:
structure could be used to create a struct
struct Node

{
int node ;

struct Node *next;


};

PROGRAM:
#include<stdio.h>
#include<conio.h>
#include <math.h>
#include
<stdlib.h> #define
MAX 10

void create();
void insert();
void deletion();
void search();
void display();
int a,b[20], n, p, e, f, i, pos;

void main()
{
//clrscr();
int ch;
char
g='y';
4931_Grace College of Engineering, Thoothukudi
45

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
46

do
{
printf("\n main Menu");
printf("\n 1.Create \n 2.Delete \n 3.Search \n 4.Insert \n 5.Display\n 6.Exit \n");
printf("\n Enter your Choice");
scanf("%d", &ch);

switch(ch)
{
case 1:
create();
break;

case 2:
deletion();
break;

case 3:
search()
; break;

case 4:
insert();
break;

case 5:
display();
break;
default:
printf("\n Enter the correct choice:");
}
printf("\n Do u want to
continue:::"); scanf("\n%c", &g);
}
while(g=='y'||g=='Y');

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
47

getch();
}

void create()
{
printf("\n Enter the number of nodes");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n Enter the Element:",i+1);
scanf("%d", &b[i]);
}

void deletion()
{
printf("\n Enter the position u want to
delete::"); scanf("%d", &pos);
if(pos>=n)
{
printf("\n Invalid Location::");
}
else
{
for(i=pos+1;i<n;i++)
{
b[i-1]=b[i];
}
n--;
}
printf("\n The Elements after deletion");
for(i=0;i<n;i++)
{

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
48

printf("\t%d", b[i]);
}
}

void search()
{
printf("\n Enter the Element to be searched:");
scanf("%d", &e);

for(i=0;i<n;i++)
{
if(b[i]==e)
{
printf("Value is in the %d Position", i);
}
else
{
printf("Value %d is not in the list::", e);
continue;
}
}
}

void insert()
{
printf("\n Enter the position u need to insert::");
scanf("%d", &pos);

if(pos>=n)
{
printf("\n invalid Location::");
}
else

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
49

{
for(i=MAX-1;i>=pos-1;i--)
{
b[i+1]=b[i];
}
printf("\n Enter the element to insert::\n");
scanf("%d",&p);
b[pos]=p;
n++;
}
printf("\n The list after insertion::\
n"); display();
}

void display()
{
printf("\n The Elements of The list ADT are:");
for(i=0;i<n;i++)
{
printf("\n\n%d", b[i]);
}
}

OUTPUT

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
50

main
Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit

Enter your Choice1

Enter the number of

nodes3 Enter the

Element:99 Enter the

Element:88 Enter the

Element:77

Do u want to continue:::y

main
Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit

Enter your Choice2

Enter the position u want to delete::0

The Elements after deletion 88


77 Do u
want to continue:::y

main
Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit

Enter your Choice4


4931_Grace College of Engineering, Thoothukudi
51

Enter the position u need to insert::1

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
52

Enter the element to insert::


11

The list after insertion::

The Elements of The list ADT are:

88

11

77
Do u want to continue:::y

main
Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit

Enter your Choice3

Enter the Element to be searched:77


Value 77 is not in the list::Value 77 is not in the list::Value is in the 2 Position
Do u want to continue:::

RESULT:
Thus the C programs can be executed and the output was verified successfully.
4931_Grace College of Engineering, Thoothukudi
53

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
54

EX.NO: 7(A) Array implementation of Stack ADTs

Aim:
To write a C program for Implementation of stack using array.
Algorithm:
Adding an element onto the stack (push operation)
Adding an element into the top of the stack is referred to as push operation. Push operation
involves following two steps.
1. Increment the variable Top so that it can now refere to the next memory location.
2. Add element at the position of incremented top. This is referred to as adding new
element at the top of the stack.
Stack is overflown when we try to insert an element into a completely filled stack therefore,
our main function must always avoid stack overflow condition.
begin
if top = n then stack full
top = top + 1
stack (top) : = item;
end
Deletion of an element from a stack (Pop operation)
Deletion of an element from the top of the stack is called pop operation. The value of the
variable top will be incremented by 1 whenever an item is deleted from the stack. The top most
element of the stack is stored in an another variable and then the top is decremented by 1. the
operation returns the deleted value that was stored in another variable as the result.
The underflow condition occurs when we try to delete an element from an already empty
stack
.
begin
if top = 0 then stack empty;
item := stack(top);
top = top - 1;
end;
Program:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAXSTK 100
int top=-1;
4931_Grace College of Engineering, Thoothukudi
55

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
56

int items[MAXSTK];
int Isempty();
int Isfull();
void Push(int);
int Pop();
void
Display();
void main()
{
int x;
char ch='1';
clrscr();
while(ch!
='4')
{
printf("\n 1-PUSH");
printf("\n 2-POP");
printf("\n 3-DISPLAY");
printf("\n 4-QUIT");
printf("\n Enter your
choice:"); fflush(stdin);
ch=getchar()
; switch(ch)
{
case '1':
printf("\n Enter the element to be
pushed:"); scanf("%d",&x);
Push(x);
break;
case '2':
x=Pop();
printf("\n Pop element is %d\n:",x);
break;
case '3':
4931_Grace College of Engineering, Thoothukudi
57

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
58

Display();
break;
case '4':
break;
default:
printf("\n Wrong choice!Try again:");
}
}
}
int Isempty()
{
if(top==-1)
return 1;
else return 0;
}
int Isfull()
{
if(top==MAXSTK-1)
return
1; else
return
0;
}
void Push(int x)
{
if(Isfull())
{
printf("\n Stack full");
return;
}
top++;
items[top]=x
;
}
4931_Grace College of Engineering, Thoothukudi
59

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
60

int Pop()
{
int x;
if(Isempty())
{
printf("\n Stack
empty"); exit(0);
}
x=items[top]
; top--;
return x;
}
void Display()
{
int i;
if(Isempty())
{
printf("\n Stack
empty"); return;
}
printf("\n Elements in the Stack are :\
n"); for(i=top;i>=0;i--)
printf("%d\n",items[i]);
}

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
61

Output:

1- PUSH
2- POP
3- DISPLAY
4- QUIT
Enter your choice:1

Enter the element to be


pushed:1001 1-PUSH
2- POP
3- DISPLAY
4- QUIT
Enter your choice:1

Enter the element to be pushed:2022

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
62

1- PUSH
2- POP
3- DISPLAY
4- QUIT
Enter your choice:1

Enter the element to be

pushed:4444 1-PUSH
2- POP
3- DISPLAY
4- QUIT
Enter your choice:2

Pop element is 4444


:
1- PUSH
2- POP
3- DISPLAY
4- QUIT
Enter your choice:3
Elements in the Stack are :
2022
1001
1- PUSH
2- POP
3- DISPLAY
4- QUIT
Enter your choice: 4

RESULT:
Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
63

EX.NO: 7(B) Array implementation of Queue ADTs

Aim:
To write a C program for Implementation of queue using array.
Algorithm:
Step 1: IF REAR = MAX – 1
Write OVERFLOW
Go to step
[END OF IF]
Step 2: IF FRONT = -1 and REAR = -1
SET FRONT = REAR = 0
ELSE
SET REAR = REAR + 1
[END OF IF]
Step 3: Set QUEUE[REAR] = NUM
Step 4: EXIT
Program:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>#define MAXQ 100
int front=0,rear=-1;
int
items[MAXQ];
int Isempty();
int Isfull();
void Insert(int);
int Delete();
void Display();
void main()
{
int x;
char ch='1';
clrscr();
while(ch!
='4')
4931_Grace College of Engineering, Thoothukudi
64

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
65

{
printf("\n 1-INSERT");
printf("\n 2-DELETE");
printf("\n 3-DISPLAY");
printf("\n 4-QUIT");
printf("\n Enter your
choice:"); fflush(stdin);
ch=getchar()
; switch(ch)
{
case '1':
printf("\n Enter the element to be inserted:");
scanf("%d",&x);
Insert(x);
break;
case '2':
x=Delete();
printf("\n Delete element is %d\n:",x);
break;
case '3':
Display();
break;
case '4':
break;
default:
printf("\n Wrong choice!Try again:");
}
}
getch();
}
int Isempty()
{

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
66

if(rear<front)
return 1;
else return 0;
}
int Isfull()
{
if(rear==MAXQ-1)
return 1;
else
return
0;
}
void Insert(int x)
{
if(Isfull())
{
printf("\n Queue
full"); return;
}
rear++;
items[rear]=x;
}
int Delete()
{
int x;
if(Isempty())
{
printf("\n Queue is empty");
exit(0);
}
x=items[front];
front++;
return x;
4931_Grace College of Engineering, Thoothukudi
67

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
68

}
void Display()
{
int i;
if(Isempty())
{
printf("\n Queue is empty");
return;
}
printf("\n Elements in the Queue are :\n");
for(i=front;i<=rear;i++)
printf("%d\n",items[i]);
}
Output:

1- INSERT
2- DELETE

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
69

3- DISPLAY
4- QUIT
Enter your choice:1

Enter the element to be


inserted:001 1-INSERT
2- DELETE
3- DISPLAY
4- QUIT
Enter your choice:1
Enter the element to be
inserted:002 1-INSERT
2- DELETE
3- DISPLAY
4- QUIT
Enter your choice:1
Enter the element to be
inserted:003 1-INSERT
2- DELETE
3- DISPLAY
4- QUIT
Enter your choice:2

Delete element is 1
:
1- INSERT
2- DELETE
3- DISPLAY
4- QUIT
Enter your choice:3

Elements in the Queue are :


2
3

1- INSERT
2- DELETE
3- DISPLAY
4- QUIT
Enter your choice:

RESULT:
Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
70

EX.NO: 8(A) Linked list implementation of List ADTs

Aim:
Write a C program that uses functions to perform the following on Singly Linked List:
i) Creation ii) Insertion iii) Deletion iv) Traversal
P rogram:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int count=0;
struct node
{
int data;
struct node *next;
}*head,*newn,*trav;
//
void create_list()
{
int value;
struct node *temp;
temp=head;
newn=(struct node *)malloc(sizeof (struct node));
printf("\nenter the value to be inserted");
scanf("%d",&value);
newn->data=value;
if(head==NULL)
{
head=newn;
head->next=NULL;
count++;
}
Else
{
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newn;
newn->next=NULL;
count++;

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
71

}
}
//
void insert_at_begning(int value)
{
newn=(struct node *)malloc(sizeof (struct
node)); newn->data=value;
if(head==NULL)
{
head=newn;
head->next=NULL;
count++;
}
Else
{
newn->next=head;
head=newn; count+
+;
}
}
//
void insert_at_end(int value)
{
struct node *temp;
temp=head;
newn=(struct node *)malloc(sizeof (struct
node)); newn->data=value;
if(head==NULL)
{
head=newn;
head->next=NULL;
count++;
}
Else
{
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newn;
newn->next=NULL;
count++;
}
}
//
int insert_at_middle()

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
72

{
if(count>=2)
{
struct node *var1,*temp;
int loc,value;
printf("\n after which value you want to insert : ");
scanf("%d",&loc);
printf("\nenter the value to be inserted");
scanf("%d",&value);
newn=(struct node *)malloc(sizeof (struct
node)); newn->data=value;
temp=head;
/* if(head==NULL)
{
head=newn;
head->next=NULL;
count++;
return 0;
}
Else
{*/
while(temp->data!=loc)
{
temp=temp->next;
if(temp==NULL)
{
printf("\nSORRY...there is no %d element",loc);
return 0;
}
}
//var1=temp->next;
newn->next=temp->next;//var1;
temp->next=newn;
count++;
//}
}
Else
{
printf("\nthe no of nodes must be >=2");
}
}
//
int delete_from_middle()
{
if(count==0)
printf("\n List is Empty!!!! you can't delete elements\n");

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
73

else if(count>2)
{
struct node *temp,*var;
int value;
temp=head;
printf("\nenter the data that you want to delete from the list shown above");
scanf("%d",&value);
while(temp->data!=value)
{
var=temp;
temp=temp->next;
if(temp==NULL)
{
printf("\nSORRY...there is no %d element",value);
return 0;
}
}
if(temp==head)
{
head=temp->next;
}
Else
{
var->next=temp->next;
temp->next=NULL;
}
count--;
if(temp==NULL)
printf("Element is not avilable in the list \n**enter only middle elements..**");
else
printf("\ndata deleted from list is %d",value);
free(temp);
}
Else
{
printf("\nthere no middle elemts..only %d elemts is avilable\n",count);
}
}
//
int delete_from_front()
{
struct node *temp;
temp=head;
if(head==NULL)
{
printf("\nno elements for deletion in the list\n");

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
74

return 0;
}
Else
{
printf("\ndeleted element is :%d",head-
>data); if(temp->next==NULL)
{
head=NULL;
}
else{
head=temp->next;
temp->next=NULL;
}
count--;
free(temp)
;
}}
//
int delete_from_end()
{ struct node
*temp,*var; temp=head;
if(head==NULL)
{
printf("\nno elemts in the list");
return 0;
}
else{
if(temp->next==NULL )
{
head=NULL;//temp->next;
}
else{
while(temp->next != NULL)
{
var=temp;
temp=temp->next;
}
var->next=NULL;
}
printf("\ndata deleted from list is %d",temp->data);
free(temp);
count--;
}
return 0;}
//
int display()
{
4931_Grace College of Engineering, Thoothukudi
75

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
76

trav=head;
if(trav==NULL)
{
printf("\nList is Empty\n");
return 0;}
else
{
printf("\n\nElements in the Single Linked List is %d:\n",count); while(trav!
=NULL)
{
printf(" -> %d ",trav-
>data); trav=trav->next;
}
printf("\n");
}
}
//
int main()
{
int ch=0;
char ch1;
head=NULL;
while(1)
{
printf("\n1.create linked list"); printf("\
n2.insertion at begning of linked list"); printf("\
n3.insertion at the end of linked list");
printf("\n4.insertion at the middle where you want");
printf("\n5.deletion from the front of linked list");
printf("\n6.deletion from the end of linked list ");
printf("\n7.deletion of the middle data that you
want"); printf("\n8.display the linked list"); printf("\
n9.exit\n");
printf("\nenter the choice of operation to perform on linked list");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
do{ create_li
st();
display();
printf("do you want to create list ,y / n");
getchar();
scanf("%c",&ch1);
}while(ch1=='y');

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
77

break;
}
case 2:
{
int value;
printf("\nenter the value to be inserted");
scanf("%d",&value);
insert_at_begning(value);
display();
break;
}
case 3:
{
int value;
printf("\nenter value to be inserted");
scanf("%d",&value);
insert_at_end(value);
display();
break;
}
case 4:
{
insert_at_middle();
display();
break;
}
case 5:
{
delete_from_front();
display();
}break
; case
6:
{
delete_from_end();
display();
break;
}
case 7:
{
display();
delete_from_middle();
display();
break;
}
case 8:
{
4931_Grace College of Engineering, Thoothukudi
78

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
79

display();
break;
}
case 9:
{
exit(1);
}
default:printf("\n****Please enter correct choice****\n");
}
}
getch();
}

OUTPUT

1. create l in k ed l ist
2. in sertion at b egn in g of l in k ed l ist
3. in sertion at th e en d of l in k ed l ist

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
80

4. in sertion at th e mid d le w h ere you w an t


5. d e letion f rom th e f ron t of l in k ed l ist
6. d e letion f rom th e en d of l in k ed l ist
7. d e letion of th e mid d le d ata th at you w an t
8. d isp lay th e l in k ed l ist
9. exit

en ter th e ch o ice of op eration to p erf orm on l in k ed l

ist 1 en ter th e valu e to b e in serted 1001

E lemen ts in th e S in g le L in k ed L ist is 1 :
- > 1001
d o you w an t to create l ist , y / n y

en ter th e valu e to b e in serted 1002

E lemen ts in th e S in g le L in k ed L ist is 2 :
- > 1001 - > 1002
d o you w an t to create l ist , y / n y

en ter th e valu e to b e in serted 1003

E lemen ts in th e S in g le L in k ed L ist is 3 :
- > 1001 - > 1002 - > 1003
d o you w an t to crea te l ist , y / n n

1. create l in k ed l ist
2. in sertion at b egn in g of l in k ed l ist
3. in sertion at th e en d of l in k ed l ist
4. in sertion at th e mid d le w h ere you w an t
5. d e letion f rom th e f ron t of l in k ed l ist
6. d e letion f rom th e en d of l in k ed l ist
7. d e letion of th e mid d le d ata th at you w an t
8. d isp lay th e l in k ed l ist
9. exit

en ter th e ch o ice of op eration to p erf orm on l in k ed l ist 7

E lemen ts in th e S in g le L in k ed L ist is 3 :
- > 1001 - > 1002 - > 1003

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
81

en ter th e d ata th at you w an t to d e lete f rom th e l ist sh ow n ab ove

1002 d ata d e leted f rom l ist is 1002

E lemen ts in th e S in g le L in k ed L ist is 2 :
- > 1001 - > 1003

1. create l in k ed l ist
2. in sertion at b egn in g of l in k ed l ist
3. in sertion at th e en d of l in k ed l ist
4. in sertion at th e mid d le w h ere you w an t
5. d e letion f rom th e f ron t of l in k ed l ist
6. d e letion f rom th e en d of l in k ed l ist
7. d e letion of th e mid d le d ata th at you w an t
8. d isp lay th e l in k ed l ist
9. exit

en ter th e ch o ice of op eration to p erf orm on l in k ed l ist 9

RESULT:
Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
82

EX.NO: 8(B) Linked list implementation of Stack ADTs

Aim:
Write a program that implement Stack (its operations) using Arrays
P r ogr am:
#include<stdio.h>
#include<conio.h>
#define max 5
int st[max],top=-1;
void push()
{
int x;
if(top==max-1)
{
printf("stack is
full"); return;
}
printf("enter
element");
scanf("%d",&x); top+
+;
st[top]=x;
}
void pop()
{
int x;
if(top==-1)
{
printf("stack is
empty"); return;
}
printf("enter element");
scanf("%d",&x);
top--;
printf("enter deleted element=%d",x);
}
void display()
{
int i;
if(top==-1)
{
printf("stack is
empty"); return;}
for(i=top;i>=0;i--)
4931_Grace College of Engineering, Thoothukudi
83

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
84

{
printf("%d",st[i]);}}
int main()
{
int ch;
while(1)
{
printf("enter \n1.push\n2.pop\n3.display\n4.exit");
scanf("%d",&ch);
switch(ch)
{
case 1:push();break;
case 2:pop();break;
case 3:display();break;
case 4:exit(1);break;
}}
return 1;
}
OU T P U T :

en ter
1 . p u sh
2 . p op
3. d isp lay
4. exit 1
en ter e lemen t
44 en ter
1 . p u sh

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
85

2 . p op
3. d isp lay
4. exit 1
en ter e lemen t
55 en ter
1 . p u sh
2 . p op
3. d isp lay
4. exit 1
en ter e lemen t
66 en ter
1 . p u sh
2 . p op
3. d isp lay
4. exit 2
en ter e lemen t 55
en ter d e leted e lemen t= 55 en ter
1 . p u sh
2 . p op
3. d isp lay
4. exit 3
5544 en ter
1 . p u sh
2 . p op
3. d isp lay
4. exit

RESULT:
Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
86

EX.NO: 8(C) Linked list implementation of Queue ADTs

Aim:
Write a program that implement Queue (its operations) using Arrays
Program:
#include<stdio.h>
#include<conio.h>
#define SIZE 5
int queue[SIZE], front = -1, rear = -1;
void enQueue(int value){
if(rear == SIZE-1)
printf("\nQueue is Full!!! Insertion is not
possible!!!"); else{
if(front == -1)
front = 0; rear+
+;
queue[rear] = value; printf("\
nInsertion success!!!");
}
}
void deQueue()
{ if(front ==
rear)
printf("\nQueue is Empty!!! Deletion is not possible!!!");
else{
printf("\nDeleted : %d", queue[front]);
front++;
if(front ==
rear)
front = rear = -1;
}
}
void display(){
if(rear == -1)
printf("\nQueue is Empty!!!");
4931_Grace College of Engineering, Thoothukudi
87

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
88

else
{ int
i;
printf("\nQueue elements are:\n");
for(i=front; i<=rear; i++)
printf("%d\t",queue[i]);
}
}
void main()
{
int value, choice;
while(1){
printf("\n\n***** MENU *****\n");
printf("1. Insertion\n2. Deletion\n3. Display\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
enQueue(value)
; break;
case 2: deQueue();
break;
case 3:
display(); break;
case 4: exit(0);
default: printf("\nWrong selection!!! Try again!!!");
}}}
4931_Grace College of Engineering, Thoothukudi
89

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
90

OU T P U T :

***** MENU *****


1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 2001

Insertion success!!!

***** MENU *****


1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 1

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
91

Enter the value to be insert: 2002

Insertion success!!!

***** MENU *****


1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 2003

Insertion success!!!

***** MENU *****


1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 2

Deleted : 2001

***** MENU *****


1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 3

Queue elements are:


2002 2003

***** MENU *****


1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice:
RESULT:
Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
92

EX.NO: 9(A) Applications of Stack ADTs

Aim:
Write a program that implement Applications of Stack ADTs
Applications of stacks
Stacks are used in a variety of applications. While some of these applications are "natural",
most other are essentially "pedantic". Here is a list anyway.
For processing nested structures, like checking for balanced parentheses, evaluation of postfix
expressions.
For handling function calls and, in particular, recursion.
For searching in special data structures (depth-first search in graphs and trees), for example, for
implementing backtracking.
Implementations of the stack ADT
A stack is specified by the ordered collection representing the content of the stack together with
the choice of the end of the collection to be treated as the top. The top should be so chosen that
pushing and popping can be made as far efficient as possible
Program:
#define MAXLEN 100
typedef struct {
char element[MAXLEN];
int top;
} stack;
stack init ()
{
stack S;
S.top = -1;
return S;
}
int isEmpty ( stack S )
{
return (S.top == -1);
}
int isFull ( stack S )
{
return (S.top == MAXLEN - 1);
}
char top ( stack S )
{
if (isEmpty(S)) {

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
93

fprintf(stderr, "top: Empty stack\n");


return '\0';
}
return S.element[S.top];
}
stack push ( stack S , char ch )
{
if (isFull(S)) {
fprintf(stderr, "push: Full stack\n");
return S;
}
++S.top;
S.element[S.top] = ch;
return S;
}
stack pop ( stack S )
{
if (isEmpty(S)) {
fprintf(stderr, "pop: Empty stack\n");
return S;
}
--S.top;
return
S;
}
void print ( stack S )
{
int i;
for (i = S.top; i >= 0; --i) printf("%c",S.element[i]);
}
Here is a possible main() function calling these routines:
int main ()
{
stack S;
S = init(); printf("Current stack : "); print(S); printf(" with top = %c.\n", top(S));
S = push(S,'a'); printf("Current stack : "); print(S); printf(" with top = %c.\n", top(S));
S = push(S,'b'); printf("Current stack : "); print(S); printf(" with top = %c.\n", top(S));
S = push(S,'c'); printf("Current stack : "); print(S); printf(" with top = %c.\n", top(S));
S = pop(S); printf("Current stack : "); print(S); printf(" with top = %c.\n", top(S));
S = push(S,'x'); printf("Current stack : "); print(S); printf(" with top = %c.\n", top(S));
S = pop(S); printf("Current stack : "); print(S); printf(" with top = %c.\n", top(S));
S = pop(S); printf("Current stack : "); print(S); printf(" with top = %c.\n",
top(S)); S = pop(S); printf("Current stack : "); print(S); printf(" with top = %c.\
n", top(S)); S = pop(S); printf("Current stack : "); print(S); printf(" with top =
%c.\n", top(S));
}
4931_Grace College of Engineering, Thoothukudi
94

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
95

Output:

RESULT:
Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
96

EX.NO: 9(B) Applications of Queue ADTs

Aim:
Write a program that implement Applications of Queue ADTs.
Implementations of the queue ADT
Continuing with our standard practice followed so far, we are going to provide two
implementations of the queue ADT, the first using static memory, the second using dynamic
memory. The implementations aim at optimizing both the insertion and deletion operations.
Program:
#define MAXLEN 100
typedef struct {
char element[MAXLEN];
int front;
int back;
} queue;
queue init ()
{
queue Q;
Q.front = 0;
Q.back = MAXLEN - 1;
return Q;
}
int isEmpty ( queue Q )
{
return (Q.front == (Q.back + 1) % MAXLEN);
}
int isFull ( queue Q )
{
return (Q.front == (Q.back + 2) % MAXLEN);
}
char front ( queue Q )
{
if (isEmpty(Q)) {
fprintf(stderr,"front: Queue is empty\n");
return '\0';
}
return Q.element[Q.front];
}
queue enqueue ( queue Q , char ch )
{
if (isFull(Q)) {
fprintf(stderr,"enqueue: Queue is full\n");

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
97

return Q;
}
++Q.back;
if (Q.back == MAXLEN) Q.back = 0;
Q.element[Q.back] = ch;
return Q;
}
queue dequeue ( queue Q )
{
if (isEmpty(Q)) {
fprintf(stderr,"dequeue: Queue is empty\n");
return Q;
}
++Q.front;
if (Q.front == MAXLEN) Q.front = 0;
return Q;
}
void print ( queue Q )
{
int i;
if (isEmpty(Q))
return; i = Q.front;
while (1) {
printf("%c", Q.element[i]);
if (i == Q.back) break;
if (++i == MAXLEN) i = 0;
}
}
int main ()
{
queue Q;
Q = init(); printf("Current queue : "); print(Q); printf("\n");
Q = enqueue(Q,'a'); printf("Current queue : "); print(Q); printf("\n");
Q = enqueue(Q,'b'); printf("Current queue : "); print(Q); printf("\n");
Q = enqueue(Q,'c'); printf("Current queue : "); print(Q); printf("\n");
Q = dequeue(Q); printf("Current queue : "); print(Q); printf("\n");
Q = dequeue(Q); printf("Current queue : "); print(Q); printf("\n");
Q = enqueue(Q,'c'); printf("Current queue : "); print(Q); printf("\n");
Q = dequeue(Q); printf("Current queue : "); print(Q); printf("\n");
Q = dequeue(Q); printf("Current queue : "); print(Q); printf("\n");
Q = dequeue(Q); printf("Current queue : "); print(Q); printf("\n");
}

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
98

Output:

RESULT:
Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
99

EX.NO: 10 Implementation of Binary Trees and operations


of Binary Trees

Aim:
To Write a program that Implementation of Binary Trees and operations of Binary Trees.

Binary Tree: A tree whose elements have at most 2 children is called a binary tree. Since each
element in a binary tree can have only 2 children, we typically name them the left and right
child.
Binary Tree Representation: A tree is represented by a pointer to the topmost node of the tree.
If the tree is empty, then the value of the root is NULL.
A Tree node contains the following parts.
1. Data
2. Pointer to the left child
3. Pointer to the right child
4. // Structure of each node of the tree
5.
6. struct node
7. {
8. int data;
9. struct node* left;
10. struct node* right;
11. };
Basic Operation On Binary Tree:
 Inserting an element.
 Removing an element.
 Searching for an element.
 Traversing an element. There are three types of traversals in a binary tree which will be
discussed ahead.
Program:
#include<stdio.h>
#include<stdlib.h>
struct node
{ int value;
struct node *left_child, *right_child;
};
struct node *new_node(int value)

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
10
0

{
struct node *tmp = (struct node *)malloc(sizeof(struct
node)); tmp->value = value;
tmp->left_child = tmp->right_child = NULL;
return tmp;
}
void print(struct node *root_node) // displaying the nodes!
{
if (root_node != NULL)
{
print(root_node->left_child);
printf("%d \n", root_node-
>value); print(root_node-
>right_child);
}
}
struct node* insert_node(struct node* node, int value) // inserting nodes!
{
if (node == NULL) return new_node(value);
if (value < node->value)
{
node->left_child = insert_node(node->left_child, value);
}
else if (value > node->value)
{
node->right_child = insert_node(node->right_child, value);
}
return node;
}
int main()
{
printf("Diaplay: Implementation of a Binary Tree in C!\n\n");
struct node *root_node = NULL;
root_node = insert_node(root_node, 10);
insert_node(root_node, 10);
insert_node(root_node, 30);
insert_node(root_node, 25);
insert_node(root_node, 36);
insert_node(root_node, 56);
insert_node(root_node,
78); print(root_node);
4931_Grace College of Engineering, Thoothukudi
10
1
CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |
4931_Grace College of Engineering, Thoothukudi
10
2

return 0;
}

Output:-

RESULT:
Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
10
3

EX.NO: 11 Implementation of Binary Search Trees

Aim:
To Write a program that Implementation of Binary Search Trees.
Algorithm:

If root==Null
return Null;
If number==root->data
return root->data
If number<root->data
return search(root->left)
If number>root->data
return search(root->right)

Program:
# includ e <st d io .
h> # includ e <st d l
ib . h> s t ruct nod e {
in t key;
s t ruct nod e * lef t , * r ight ;
};
/ / C reat e a nod e
s t ruct nod e * new N od e( in t i t em) {
s t ruct nod e * t emp = ( s t ruct nod e *) malloc( s izeof ( s t ruct nod e));
t emp - >key = i t em;
t emp - >lef t = t emp - >right = N U L L
; ret urn t emp;
}
/ / I nord er Traversal
void inord er( s t ruct nod e * root )
{ i f ( root ! = N U L L ) {
/ / Traverse lef t
inord er( root - >lef t ) ;
/ / Traverse root
print f ("% d - > ", root - >key);
/ / Traverse r ight
inord er( root - >right ) ;
}
}

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
10
4

/ / I nsert a nod e
s t ruct nod e * insert ( s t ruct nod e * nod e , in t key) {
/ / R e t urn a new nod e i f t he t ree is empt y
i f ( nod e == N U L L ) ret urn new N o d e( key);
/ / Traverse t o t he r ight p lace and insert t he nod
e i f ( key < nod e - >key)
nod e - >lef t = insert ( nod e - >lef t ,
key); e lse
nod e - >right = insert ( nod e - >right ,
key); ret urn nod e ;
}
/ / F ind t he inord er successor
s t ruct nod e * min V a lue N od e( s t ruct nod e * nod
e) { s t ruct nod e * current = nod e ;
/ / F ind t he lef t most leaf
w h i le ( current && current - >lef t ! = N U L L )
current = current - >lef t ;
ret urn current ;
}
/ / D e le t ing a nod e
s t ruct nod e * d e le t e N od e( s t ruct nod e * ro o t , in t key) {
/ / R e t urn i f t he t ree is empt y
i f ( root == N U L L ) ret urn root ;
/ / F ind t he nod e t o be d e le t
ed i f ( key < root - >key)
root - >lef t = d e le t e N od e( root - >lef t ,
key); e lse i f ( key > root - >key)
root - >right = d e le t e N od e( root - >right ,
key ); e lse {
/ / I f t he nod e is w i t h only one child or no
child i f ( root - >lef t == N U L L ) {
s t ruct nod e * t emp = root -
>right ; f ree( root ) ;
ret urn t emp;
} e lse i f ( root - >right == N U L L
) { s t ruct nod e * t emp = root -
>lef t ; f ree( root ) ;
ret urn t emp;
}
/ / I f t he nod e has t w o child ren
s t ruct nod e * t emp = min V a lue N od e( root - >right ) ;
/ / P lace t he inord er successor in posit ion of t he nod e t o be d e le t ed
root - >key = t emp - >key;
/ / D e le t e t he inord er successor
root - >right = d e le t e N od e( root - >right , t emp - >key);
}

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
10
5

ret urn root ;


}
/ / D r iver cod
e in t main() {
s t ruct nod e * root = N U L L
; root = insert ( root , 9 );
root = insert ( root , 3 )
; root = insert ( root , 1
) ; root = insert ( root ,
6 ) ; root = insert ( root
, 7);
root = insert ( root , 1 1 );
root = insert ( root , 14 ) ;
root = insert ( root , 4 ) ;
print f (" I nord er t raversal: ");
inord er( root ) ;
print f ("\ n A f t er d e le t ing 10 \
n"); root = d e le t e N ode( root , 10
);
print f (" I nord er t raversal: ");
inord er( root ) ;
}
Ou tp u t:

RESULT:
Thus the C programs can be executed and the output was verified successfully.
4931_Grace College of Engineering, Thoothukudi
10
6
CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |
4931_Grace College of Engineering, Thoothukudi
10
7

EX.NO: 12
Implementation of searching techniques
DATE:

Aim:
To Write a program that Implementation of searching techniques.
Linear Search
Algorithm Algorithm:
Linear_Search ( Array X, Value i)
Set j to 1
If j > n, jump to step 7
If X[j] == i, jump to step 6
Then, increment j by 1 i.e. j = j+1
Go back to step 2
Display the element i which is found at particular index i, then jump to step
8 Display element not found in the set of input elements.
Exit/End
Procedure:
proced ure L I N E A R _S E AR CH ( array, key)

f or each i t em in t he array
i f mat ch e lement ==
key
ret urn e lement ' s ind
ex end i f
end f or

end proced ure

Implementation of Linear Search in C

 Initially, we need to mention or accept the element to be searched from the user.
 Then, we create a for loop and start searching for the element in a sequential fashion.
 As soon as the compiler encounters a match i.e. array[element] == key value, return the
element along with its position in the array.
 If no values are found that match the input, it returns -1.
4931_Grace College of Engineering, Thoothukudi
10
8
CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |
4931_Grace College of Engineering, Thoothukudi
10
9

P rogram:
# includ e <st d io . h>
in t L I N E A R _S E AR CH( in t inp_arr[], in t s ize, in t val)
{
in t i ;
f or ( i = 0 ; i < s ize; i++)
i f ( inp_arr[ i ] ==
val) ret urn i ;
ret urn - 1 ;
}
in t main( void )
{
in t arr[] = { 1000 , 2000 , 3000 , 4000 , 5000 , 100 , 0 } ;
in t key = 1000 ;
in t s ize = 10 ;
in t res = L I N E A R _S EA RC H( arr, s ize,
key); i f ( res == - 1)
print f (" E L E ME N T N O T F O U N D !!");
e lse
print f (" I t em is present a t ind ex % d ", res);

ret urn 0 ;
}

Ou tp u t:

RESULT:
Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
11
0

EX.NO: 13 Implementation of Sorting algorithms : Insertion Sort

Write a program to explain insertion sort .

Aim:
To Write a program that Implementation of Sorting algorithms : Insertion Sort.
Algorithm:
Step 1 − If it is the first element, it is already sorted. return 1;
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted

Program:

/*Program to sort elements of an array using insertion sort method*/


#include<stdio.h>
#include<stdlib.h>
void main( )
{
int a[10],i,j,k,n;
clrscr( );
printf("How many elements you want to sort?\n");
scanf("%d",&n);
printf("\nEnter the Elements into an array:\n");
for (i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<n;i++)
{
k=a[i];
for(j= i-1; j>=0 &&
k<a[j];j--) a[j+1]=a[j];
a[j+1]=k;
}
printf("\n\n Elements after sorting: \n");
for(i=0;i<n;i++)

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
11
1

printf("%d\n", a[i]);
getch( );
}

OUTPUT:

RESULT:
Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
11
2

EX.NO: 13(B) Implementation of Sorting algorithms : Quick Sort

Aim:
To Write a program that Implementation of Sorting algorithms : Quick Sort.
Algorithm:
/* low –> Starting index, high –> Ending index */
quickSort(arr[], low, high) {
if (low < high) {
/* pi is partitioning index, arr[pi] is now at right place */
pi = partition(arr, low, high);
quickSort(arr, low, pi – 1); // Before pi
quickSort(arr, pi + 1, high); // After pi
}}
Program:
/* program to sort elements of an array using Quick Sort */
#include<stdio.h>
void quicksort(int[ ],int,int);
void main( )
{
int low, high, pivot, t, n, i, j, a[10];
clrscr( );
printf("\nHow many elements you want to sort ? ");
scanf("%d",&n);
printf("\Enter elements for an array:");
for(i=0; i<n;i++)
scanf("%d",&a[i]);
low=0;
high=n-1;
quicksort(a,low,high);
printf("\After Sorting the elements are:");
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch( );
}
void quicksort(int a[ ],int low,int high)
{

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
11
3

int
pivot,t,i,j;
if(low<high)
{
pivot=a[low]
; i=low+1;
j=high;
while(1)
{
while(pivot>a[i]&&i<=high)
i++;
while(pivot<a[j]&&j>=low)
j--;
if(i<j)
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
else
break
;
}
a[low]=a[j];
a[j]=pivot;
quicksort(a,low,j-1);
quicksort(a,j+1,high)
;
}
}
OUTPUT:

RESULT:
Thus the C programs can be executed and the output was verified successfully.
4931_Grace College of Engineering, Thoothukudi
11
4

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
11
5

EX.NO: 13(C) Implementation of Sorting algorithms : Merge Sort

Aim:
To Write a program that Implementation of Sorting algorithms : Merge Sort.
Algorithm:
step 1: start
step 2: declare array and left, right, mid variable
step 3: perform merge function.
if left > right
return
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
step 4: Stop
Program:
/* program to sort elements of an array using Merge Sort */
#include <stdio.h>
void disp( );
void mergesort(int,int,int);
void msortdiv(int,int);
int a[50],n;
void main(
)
{
int i;
clrscr( );
printf("\nEnter the n
value:"); scanf("%d",&n);
printf("\nEnter elements for an array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nBefore Sorting the elements are:");
4931_Grace College of Engineering, Thoothukudi
11
6
CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |
4931_Grace College of Engineering, Thoothukudi
11
7

disp( );
msortdiv(0,n-1);
printf("\nAfter Sorting the elements are:");
disp( );
getch( );
}
void disp( )
{
int i; for(i=0;i<n;i+
+) printf("%d
",a[i]);
}
void mergesort(int low,int mid,int high)
{
int t[50],i,j,k;
i=low;
j=mid+1;
k=low;
while((i<=mid) && (j<=high))
{
if(a[i]>=a[j])
t[k++]=a[j++];
else t[k+
+]=a[i++];
}
while(i<=mid) t[k+
+]=a[i++];
while(j<=high)
t[k++]=a[j++];
for(i=low;i<=high;i++)
a[i]=t[i];
}
void msortdiv(int low,int high)
{
int mid;

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |


4931_Grace College of Engineering, Thoothukudi
11
8

if(low!=high)
{
mid=((low+high)/2);
msortdiv(low,mid);
msortdiv(mid+1,high);
mergesort(low,mid,high)
;
}
}

OUTPUT:

RESULT:
Thus the C programs can be executed and the output was verified successfully.
4931_Grace College of Engineering, Thoothukudi
11
9
CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |
4931_Grace College of Engineering, Thoothukudi
12
0

EX.NO: 14 Implementation of Hashing – any two collision


techniques

Aim:
To Write a program that Implementation of Hashing – any two collision techniques.

P rogram:
# includ e<st d io .
h> # d ef ine s ize 7
in t arr[ s ize];
void in i t ()
{
in t i ;
f or( i = 0 ; i < s ize; i++)
arr[ i ] = - 1;
}

void insert ( in t value)


{
in t key = value % s ize;

i f ( arr[ key] == - 1)
{
arr[ key] = value;
print f ("% d insert ed a t arr[% d ] \ n", value, key);
}
e lse
{
print f (" C o l l is ion : arr[% d ] has e lement % d a l read y! \ n", key, arr[
key]); print f (" U nable t o insert % d \ n", value);
}
}

void d e l ( in t valu e)
{
in t key = value % s
ize; i f ( arr[ key] ==
value)
arr[ key] = - 1;
e lse
print f ("% d not present in t he hash t able \ n", value);
}
4931_Grace College of Engineering, Thoothukudi
12
1
CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |
4931_Grace College of Engineering, Thoothukudi
12
2

void search( in t value)


{
in t key = value % s
ize; i f ( arr[ key] ==
value)
print f (" S earch F ound \
n"); e lse
print f (" S earch N o t F ound \ n");
}

void print ()
{
in t i ;
f or( i = 0 ; i < s ize; i++)
print f (" arr[% d ] = % d \ n", i , arr[ i ]);
}

in t main()
{
in i t ();
insert ( 10 ) ; / / k ey = 10 % 7 ==>
3 insert ( 4 ) ; / / key
= 4 % 7 ==> 4 insert ( 2 ) ; //
key = 2 % 7 ==> 2
insert ( 3 ) ; / / key = 3 % 7 ==> 3 ( collision)

print f (" H ash t able \ n");


print ();
print f ("\ n");

print f (" D e le t ing value 10 . . \


n"); d e l ( 10 ) ;
print f (" A f t er t he d e le t ion hash t able \
n"); print ();
print f ("\ n");

print f (" D e le t ing value 5 . . \


n"); d e l ( 5 ) ;
print f (" A f t er t he d e le t ion hash t able \
n"); print ();
print f ("\ n");

print f (" S earching value 4 . . \


n"); search( 4 ) ;
print f (" S earching value 10 . . \ n");
search( 10 ) ;
ret urn 0 ;
}
4931_Grace College of Engineering, Thoothukudi
12
3
CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |
4931_Grace College of Engineering, Thoothukudi
12
4

Ou tp u t:

RESULT:
Thus the C programs can be executed and the output was verified successfully.

CS3362_CP&DS-Lab S. MANICKAM M.E., (PHD), AP/CS GRACE COE |

You might also like