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
{
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.
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();
}
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()
result = calculateSum(num);
return 0;
int i;
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
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 imp le me n t C programs using Files.
Program:
# in c lu d e < s t d io . h >
# in c lu d e < s t d lib . h >
in t ma in ( )
{
in t n u m;
FI L E *f pt r;
// u s e a p p r o p r ia t e lo c a t io n if y o u a r e u s in g M a c O S o r L in u x
f p t r = f o p e n ( "F : \\p r o g r a m. t x t ", "w ") ;
if ( f p t r = = N U L L )
{
p r in t f ( "E r r o r ! ") ;
e x it ( 1 ) ;
}
p r in t f ( "E n t e r n u m: ") ;
s c a n f ( "% d ", &n u m) ;
f p r in t f ( f p tr , "% d ", n u m) ;
f c lo s e ( f p t r ) ;
ret urn 0;
}
O U TP U T:
Program 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");
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();
}
Output:
RESULT:
Thus the C programs can be executed and the output was verified successfully.
A im :
To d e v e lo p a n c a lc u la t o r a p p w it h t h e h e lp o f C p r o g r a mmin g .
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.
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 t p 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';
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
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.
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;
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':
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;
}
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
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')
{
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;
}
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()
{
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_list();
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:
{
display();
break;
}
case 9:
{
exit(1);
}
default:printf("\n****Please enter correct choice****\n");
}
}
getch();
}
OUTPUT
1 . c r e a t e lin k e d lis t
2 . in s e r t io n a t b e g n in g o f lin k e d lis t
3 . in s e r t io n a t t h e e n d o f lin k e d lis t
4 . in s e r t io n a t t h e m id d le w h e r e y o u w a n t
5 . d e le t io n f r o m t h e f r o n t o f lin k e d lis t
6 . d e le t io n f r o m t h e e n d o f lin k e d lis t
7 . d e le t io n o f t h e m id d le d a t a t h a t y o u w a n t
8 . d is p la y t h e lin k e d lis t
9 . e x it
e n t e r t h e c h o ic e o f o p e r a t io n t o p e r f o r m o n lin k e d lis t 1
e n t e r t h e v a lu e t o b e in s e r t e d 1 0 0 1
E le m e n t s in t h e S in g le L in k e d L is t is 1 :
-> 1001
d o y o u w a n t t o c r e a t e lis t , y / n y
e n t e r t h e v a lu e t o b e in s e r t e d 1 0 0 2
E le m e n t s in t h e S in g le L in k e d L is t is 2 :
-> 1001 -> 1002
d o y o u w a n t t o c r e a t e lis t , y / n y
e n t e r t h e v a lu e t o b e in s e r t e d 1 0 0 3
E le m e n t s in t h e S in g le L in k e d L is t is 3 :
-> 1001 -> 1002 -> 1003
d o y o u w a n t t o c r e a t e lis t , y / n n
1 . c r e a t e lin k e d lis t
2 . in s e r t io n a t b e g n in g o f lin k e d lis t
3 . in s e r t io n a t t h e e n d o f lin k e d lis t
4 . in s e r t io n a t t h e m id d le w h e r e y o u w a n t
5 . d e le t io n f r o m t h e f r o n t o f lin k e d lis t
6 . d e le t io n f r o m t h e e n d o f lin k e d lis t
7 . d e le t io n o f t h e m id d le d a t a t h a t y o u w a n t
8 . d is p la y t h e lin k e d lis t
9 . e x it
e n t e r t h e c h o ic e o f o p e r a t io n t o p e r f o r m o n lin k e d lis t 7
E le m e n t s in t h e S in g le L in k e d L is t is 3 :
-> 1001 -> 1002 -> 1003
e n t e r t h e d a t a t h a t y o u w a n t t o d e le t e f r o m t h e lis t s h o w n a b o v e 1 0 0 2
d a t a d e le t e d f r o m lis t is 1 0 0 2
E le m e n t s in t h e S in g le L in k e d L is t is 2 :
-> 1001 -> 1003
1 . c r e a t e lin k e d lis t
2 . in s e r t io n a t b e g n in g o f lin k e d lis t
3 . in s e r t io n a t t h e e n d o f lin k e d lis t
4 . in s e r t io n a t t h e m id d le w h e r e y o u w a n t
5 . d e le t io n f r o m t h e f r o n t o f lin k e d lis t
6 . d e le t io n f r o m t h e e n d o f lin k e d lis t
7 . d e le t io n o f t h e m id d le d a t a t h a t y o u w a n t
8 . d is p la y t h e lin k e d lis t
9 . e x it
e n t e r t h e c h o ic e o f o p e r a t io n t o p e r f o r m o n lin k e d lis t 9
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 rogram:
#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--)
{
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 :
enter
1.push
2.pop
3 . d is p la y
4 . e x it 1
e n t e r e le m e n t 4 4
enter
1.push
2.pop
3 . d is p la y
4 . e x it 1
e n t e r e le m e n t 5 5
enter
1.push
2.pop
3 . d is p la y
4 . e x it 1
e n t e r e le m e n t 6 6
enter
1.push
2.pop
3 . d is p la y
4 . e x it 2
e n t e r e le m e n t 5 5
e n t e r d e le t e d e le m e n t = 5 5 e n t e r
1.push
2.pop
3 . d is p l a y
4 . e x it 3
5544enter
1.push
2.pop
3 . d is p la y
4 . e x it
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!!!");
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!!!");
} }}
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);
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:
# in c lu d e < s t d io . h >
# in c lu d e < s t d lib . h >
st ruct nod e {
in t k e y ;
s t r u c t n o d e * le f t , * r ig h t ;
};
// C r e a t e a n o d e
s t r u c t n o d e * n e w N o d e ( in t it e m) {
s t r u c t n o d e * t e mp = ( s t r u c t n o d e * ) ma llo c ( s iz e o f ( s t r u c t n o d e ) ) ;
t e mp - > k e y = it e m;
t e mp - > le f t = t e mp - > r ig h t = N U L L ;
r e t u r n t e mp ;
}
// I n o r d e r Tr a v e r s a l
v o id in o r d e r ( s t r u c t n o d e * r o o t ) {
if ( r o o t ! = N U L L ) {
// Tr a v e r s e le f t
in o r d e r ( r o o t - > le f t ) ;
// Tr a v e r s e r o o t
p r in t f ( "% d - > ", r o o t - > k e y ) ;
// Tr a v e r s e r ig h t
in o r d e r ( r o o t - > r ig h t ) ;
}
}
// I n s e r t a n o d e
s t r u c t n o d e * in s e r t ( s t r u c t n o d e * n o d e , in t k e y ) {
// R e t u r n a n e w n o d e if t h e t r e e is e mp t y
if ( n o d e = = N U L L ) r e t u r n n e w N o d e ( k e y ) ;
// Tr a v e r s e t o t h e r ig h t p la c e a n d in s e r t t h e n o d e
if ( k e y < n o d e - > k e y )
n o d e - > le f t = in s e r t ( n o d e - > le f t , k e y ) ;
e ls e
n o d e - > r ig h t = in s e r t ( n o d e - > r ig h t , k e y ) ;
ret urn nod e;
}
// F in d t h e in o r d e r s u c c e s s o r
s t r u c t n o d e * min V a lu e N o d e ( s t r u c t n o d e * n o d e ) {
st ruct nod e *current = nod e;
// F in d t h e le f t mo s t le a f
w h ile ( c u r r e n t && c u r r e n t - > le f t ! = N U L L )
c u r r e n t = c u r r e n t - > le f t ;
ret urn current ;
}
// D e le t in g a n o d e
s t r u c t n o d e * d e le t e N o d e ( s tr u c t n o d e * r o o t , in t k e y ) {
// R e t u r n if t h e t r e e is e mp t y
if ( r o o t = = N U L L ) r e t u r n r o o t ;
// F in d t h e n o d e t o b e d e le t e d
if ( k e y < r o o t - > k e y )
r o o t - > le f t = d e le t e N o d e ( r o o t - > le f t, k e y ) ;
e ls e if ( k e y > r o o t - > k e y )
r o o t - > r ig h t = d e le t e N o d e ( r o o t - > r ig h t , k e y ) ;
e ls e {
// I f t h e n o d e is w it h o n ly o n e c h ild o r n o c h ild
if ( r o o t - > le f t = = N U L L ) {
s t r u c t n o d e * t e mp = r o o t - > r ig h t ;
f ree(root );
r e t u r n t e mp ;
} e ls e if ( r o o t - > r ig h t = = N U L L ) {
s t r u c t n o d e * t e mp = r o o t - > le f t ;
f ree(root );
r e t u r n t e mp ;
}
// I f t h e n o d e h a s t w o c h ild r e n
s t r u c t n o d e * t e mp = min V a lu e N o d e ( r o o t - > r ig h t ) ;
// P la c e t h e in o r d e r s u c c e s s o r in p o s it io n o f t h e n o d e t o b e d e le t e d
r o o t - > k e y = t e mp - > k e y ;
// D e le t e t h e in o r d e r s u c c e s s o r
r o o t - > r ig h t = d e le t e N o d e ( r o o t - > r ig h t , t e mp - > k e y ) ;
}
RESULT:
Thus the C programs can be executed and the output was verified successfully.
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:
p r o c e d u r e L I N E A R _S E AR CH ( a r r a y , k e y )
f o r e a c h it e m in t h e a r r a y
if ma t c h e le me n t = = k e y
r e t u r n e le me n t ' s in d e x
e n d if
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.
P rogram:
# in c lu d e < s t d io . h >
in t L I N E A R _ S E AR CH( in t in p _ a r r [ ] , in t s iz e , in t v a l)
{
in t i;
f o r ( i = 0 ; i < s iz e ; i+ + )
if ( in p _ a r r [ i] = = v a l)
r e t u r n i;
ret urn -1;
}
in t ma in ( v o id )
{
in t a r r [ ] = { 1 0 0 0 , 2 0 0 0 , 3 0 0 0 , 4 0 0 0 , 5 0 0 0 , 1 0 0 , 0 } ;
in t k e y = 1 0 0 0 ;
in t s iz e = 1 0 ;
in t r e s = L I N E A R _ S EA RC H( a r r , s iz e , k e y ) ;
if ( r e s = = - 1 )
p r in t f ( "E L E M E N T N O T F O U N D ! ! ") ;
e ls e
p r in t f ( "I t e m is p r e s e n t a t in d e x % d ", r e s ) ;
ret urn 0;
}
Ou t p 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.
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:");
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.
Aim:
To Write a program that Implementation of Hashing – any two collision techniques.
P rogram:
# in c lu d e < s t d io . h >
# d e f in e s iz e 7
in t a r r [ s iz e ] ;
v o id in it ( )
{
in t i;
f o r ( i = 0 ; i < s iz e ; i+ + )
a r r [ i] = - 1 ;
}
v o id in s e r t ( in t v a lu e )
{
in t k e y = v a lu e % s iz e ;
if ( a r r [ k e y ] = = - 1 )
{
a r r [ k e y ] = v a lu e ;
p r in t f ( "% d in s e r t e d a t a r r [ % d ] \n ", v a lu e , k e y ) ;
}
e ls e
{
p r in t f ( "C o llis io n : a r r [ % d ] h a s e le me n t % d a lr e a d y ! \n ", k e y , a r r [ k e y ] ) ;
p r in t f ( "U n a b le t o in s e r t % d \n ", v a lu e ) ;
}
}
v o id d e l( in t v a lu e )
{
in t k e y = v a lu e % s iz e ;
if ( a r r [ k e y ] = = v a lu e )
arr[key] = -1;
e ls e
p r in t f ( "% d n o t p r e s e n t in t h e h a s h t a b le \n ", v a lu e ) ;
}
v o id s e a r c h ( in t v a lu e )
{
in t k e y = v a lu e % s iz e ;
if ( a r r [ k e y ] = = v a lu e )
p r in t f ( "S e a r c h F o u n d \n ") ;
e ls e
p r in t f ( "S e a r c h N o t F o u n d \n ") ;
}
v o id p r in t ( )
{
in t i;
f o r ( i = 0 ; i < s iz e ; i+ + )
p r in t f ( "a r r [ % d ] = % d \n ", i, a r r [ i] ) ;
}
in t ma in ( )
{
in it ( ) ;
in s e r t ( 1 0 ) ; //k e y = 1 0 % 7 ==> 3
in s e r t ( 4 ) ; //k e y = 4 % 7 ==> 4
in s e r t ( 2 ) ; //k e y = 2 % 7 ==> 2
in s e r t ( 3 ) ; //k e y = 3 % 7 = = > 3 ( c o llis io n )
p r in t f ( "H a s h t a b le \n ") ;
p r in t ( ) ;
p r in t f ( " \n ") ;
p r in t f ( "D e le t in g v a lu e 1 0 . . \n ") ;
d e l( 1 0 ) ;
p r in t f ( "A f t e r t h e d e le t io n h a s h t a b le \n ") ;
p r in t ( ) ;
p r in t f ( " \n ") ;
p r in t f ( "D e le t in g v a lu e 5 . . \n ") ;
d e l( 5 ) ;
p r in t f ( "A f t e r t h e d e le t io n h a s h t a b le \n ") ;
p r in t ( ) ;
p r in t f ( " \n ") ;
p r in t f ( "S e a r c h in g v a lu e 4 . . \n ") ;
search(4);
p r in t f ( "S e a r c h in g v a lu e 1 0 . . \n ") ;
search(10);
ret urn 0;
}
Ou t p u t :
RESULT:
Thus the C programs can be executed and the output was verified successfully.