Ii Ece CS3362 CP&DS Lab
Ii Ece CS3362 CP&DS Lab
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
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:
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
AIM:
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
{
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.
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);
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.
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
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);
}
getch();
}
OUTPUT
RESULT:
Thus the C programs can be executed and the output was verified successfully.
4931_Grace College of Engineering, Thoothukudi
12
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]);
}
for(i=n;i>0;i--)
{
sum=(sum+a[i])*x;
}
sum=sum+a[0];
return 0;
}
OUTPUT:
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
{
{
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",°ree);
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
}
OUTPUT:
RESULT:
Thus the C programs can be executed and the output was verified successfully.
OUTPUT
RESULT:
Thus the C programs can be executed and the output was verified successfully.
// 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;
}
OUTPUT:
int main()
calculateSum() result =
calculateSum(num); printf("Result =
%.2f", result);
return 0;
int i;
float sum =
0.0;
{
4931_Grace College of Engineering, Thoothukudi
22
sum += num[i];
return sum;
OUTPUT
RESULT:
Thus the C programs can be executed and the output was verified successfully.
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.
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
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();
}
Output:
RESULT:
Thus the C programs can be executed and the output was verified successfully.
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;
i f ( f p t r == N U L L )
{
print f (" E
rror!"); exit ( 1 ) ;
}
ret urn 0 ;
}
O U TP U T:
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
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
Output:
RESULT:
Thus the C programs can be executed and the output was verified successfully.
A im:
To d evelop an calculat or app w i t h t he help of C programming.
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.
Following are the different ways to write a Calculator Program in the C language.
statement
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 '-':
Ou tp u t
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 ");
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
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);
case 6:
// getting the square root of the
number printf (" You chose: Square
Root"); printf ("\n Enter First
Number: "); scanf (" %d", &n1);
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.
AIM:
To implement array implementation of List ADT.
Algorithm:
structure could be used to create a struct
struct Node
{
int node ;
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
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');
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++)
{
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
{
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
main
Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit
Element:77
Do u want to continue:::y
main
Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit
main
Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit
88
11
77
Do u want to continue:::y
main
Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit
RESULT:
Thus the C programs can be executed and the output was verified successfully.
4931_Grace College of Engineering, Thoothukudi
53
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
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
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
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]);
}
Output:
1- PUSH
2- POP
3- DISPLAY
4- QUIT
Enter your choice:1
1- PUSH
2- POP
3- DISPLAY
4- QUIT
Enter your choice:1
pushed:4444 1-PUSH
2- POP
3- DISPLAY
4- QUIT
Enter your choice:2
RESULT:
Thus the C programs can be executed and the output was verified successfully.
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
{
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()
{
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
}
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
3- DISPLAY
4- QUIT
Enter your choice:1
Delete element is 1
:
1- INSERT
2- DELETE
3- DISPLAY
4- QUIT
Enter your choice: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.
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++;
}
}
//
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()
{
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");
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");
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
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');
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
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
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
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
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
E lemen ts in th e S in g le L in k ed L ist is 3 :
- > 1001 - > 1002 - > 1003
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
RESULT:
Thus the C programs can be executed and the output was verified successfully.
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
{
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
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.
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
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
OU T P U T :
Insertion success!!!
Insertion success!!!
Insertion success!!!
Deleted : 2001
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)) {
Output:
RESULT:
Thus the C programs can be executed and the output was verified successfully.
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");
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");
}
Output:
RESULT:
Thus the C programs can be executed and the output was verified successfully.
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)
{
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.
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 ) ;
}
}
/ / 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);
}
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
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.
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:
printf("%d\n", a[i]);
getch( );
}
OUTPUT:
RESULT:
Thus the C programs can be executed and the output was verified successfully.
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)
{
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
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;
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
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;
}
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 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)
Ou tp u t:
RESULT:
Thus the C programs can be executed and the output was verified successfully.