Fods in C Lab Manual
Fods in C Lab Manual
N
PROGRAM NAME Page No.
O
1 Basic c programs – looping, data manipulations, arrays
a) Armstrong number (using while loop)
b) Sum of digits, reverse, palindrome (using while loop)
c) Factorial of a number (using for loop)
d) Prime numbers ( using for loop)
e) Fibonacci series ( do while loop)
f) Area and circumference of the circle
g) Ternary operator
h) Finding the roots of quadratic equation
i) File operations
k) Total of even integers in an array of n numbers.
l) Matrix multiplication
2 String functions
a) String concatenation
b) String comparison
c) String copy
d) Length of the string
3 Structure, union , pointers
a) Employee details using structure
b) Payroll processing using union
c) Print the elements of array using pointers
4 Dynamic memory allocations
5 Using array
a) Implementation of stack using array
b) Implementation of queue using array
6 Using linked list
a) Stack using linked list
b) Queue using linked list
7 Application of stack and queue
a) Convert infix to postfix expression
b) Breadth first search
8 Implementation of tree and tree traversals
9 Implement binary search tree
10 Search
a) Linear search
b) Binary search
11 Sorting
a) Insertion sort
b) Bubble sort
c) Quick sort
d) Merge sort
12a) Hashing techniques
b) Implement Hash Tables with linear Probing
c) Implement Hash Tables with Quadratic Probing
Om Sakthi
LAB MANUAL
FOR
Objective:
To understand and implement basic data structures using C.
To mapply linear and non-linear data structure in problem solving.
To learn to implement functions and recursive functions by means of data structures.
To implement searching and sorting algorithms.
LIST OF EXERCISES
AIM: To Write a C program to check whether the given number is Armstrong or not.
ALGORITHM:
Step 1: Start the program
Step2: Read the variable N
Step 3: Assign N1=N;
Step 4: Create Set a loop using the condition WHILE(N1!=0), if the condition true
REM=N1%10;
NUM=NUM+REM*REM*REM;
N1=N1/10;
Step 5: Else, check the condition IF(NUM=N), if the condition true
Step6: PRINT “Armstrong Number”
Step 7: Else PRINT “Not Armstrong Number”
Step 8: Stop the program
PROGRAM: /*program to check whether the given number is Armstrong or not.*/
#include <stdio.h>
#include <conio.h>
void main()
{ int n, n1, rem, num=0;
clrscr();
printf("\nCHECK WHETHER A GIVEN NO. IS ARMSTRONG NO. OR NOT");
printf("Enter a positive integer: ");
scanf("%d", &n);
n1=n;
while(n1!=0)
{ rem=n1%10;
num=num+(rem*rem*rem);
n1=n1/10;
}
if(num==n)
printf("%d is an Armstrong number",n);
else
printf("%d is not an Armstrong number",n);
getch();
}
OUTPUT:
RESULT
Thus the C program to check whether the given number is Armstrong or not was
executed and the output was obtained.
Ex. No: 1b) Sum of digits, Reverse, Palindrome (using while loop)
Date :
AIM: To write a C program to find the sum & reverse of digits and Check is Palindrome or not.
ALGORITHM:
Step 1. Start the program
Step 2. Enter the number.
Step 3. Set a loop upto the number is not equal to zero .
Rem num%10 Sum Sum+rem Rnum rnum *10 +rem Num num/10
Step 4. After the end of the loop print the sum and reverse no of the digit.
Step 5. Find whether the reverse no is equal to the input number. If equal, then it is
Palindrome.
PROGRAM : /* program to find the sum & reverse of digits and Check is Palindrome or not.*/
#include<stdio.h>
#include<conio.h>
void main()
{
unsigned long int a,num,sum=0,rnum=0,rem;
clrscr();
printf("\n Enter the No:");
scanf("%ld",&num);
a=num;
while(num!=0)
{
rem=num%10;
sum=sum+rem;
rnum=rnum*10+rem;
num=num/10;
}
printf("\n The Sum of Digits %ldis=%ld\n",a,sum);
printf("\n The Reverse %ld is=%ld\n",a,rnum);
if(a==rnum)
printf("\n The Given number is a Palindrome");
else
printf("\n The Given number is not a Palindrome");
getch();
}
OUTPUT:
RESULT: Thus the C program to find the sum & reverse of digits and to check whether it is
Palindrome or not was executed and verified successfully
Ex. No: 1c) Factorial of a number (using for loop)
Date :
AIM: To write a program to calculate the factorial of the given number using functions.
ALGORITHM:
Step 1: Start the program
Step2: Enter a number.
Step 3: Set a loop to find the factorial of the given no using Fact=fact*i
Step 4: Print the factorial of the given number.
Step 5: Stop the program
PROGRAM: /* program to calculate the factorial of the given number using functions.*/
#include<stdio.h>
void main()
{
int fact=1,i,num;
printf("Enter the number");
scanf("%d",&num);
for(i=1;i<=num;i++)
{
fact=fact*i;
}
printf("the factorial of %dis %d",num,fact); getch();
}
OUTPUT:
RESULT:
Thus the C program to calculate factorial of the given number using function is
ALGORITHM :
Step 1: start
Step 2: read n
Step 3: set i=1
Step 4: if (i<=n) go to step 5 otherwise got to step 13
Step 5: set factr = 0
Step 6: set j = 1
Step 7: if(j<=i) go to step 8 otherwise go to step 11
Step 8: if( i mod j ==0) go to step 9 otherwise go to step 10
Step 9 factr =factr+1
Step 10: j=j+1,go to step 7
Step 11: if factr = 2, print i as prime number
Step 12: i=i+1 ,goto step 4
Step 13: stop
Input Output
RESULT: Thus the C program to generate prime numbers till nth number is calculated successfully
and verified
Ex. No: 1e) Fibonacci Series ( do while loop)
Date :
AIM: To write a C program to find the Fibonacci series of the given number.
ALGORITHM:
Step 1: start
Step 2: set f=0,f1=0,f2=1,i=1
Step 3: read n
Step 4: Print f
Step 5: f=f1+f2
Step 6: Print f
Step 7:f2=f1; f1=f; i=i+1
Step 5: if (i<n) ,go to step 5 otherwise go to step10
Step 10: stop
void main()
{
int i=1,n,f,f1,f2;
printf("enter the number");
scanf("%d",&n);
f=0;
f1=0;
f2=1;
printf(“FIBONACCI SERIES\n”);
do
{ i++;
printf("%d\n",f);
f=f1+f2;
f2=f1;
f1=f;
}while(i<=n);
}
OUTPUT:
RESULT: Thus the C program to find Fibonacci series of the given number was executed and
verified successfully.
Ex. No : 1f) DATA MANIPULATIONS
Area and Circumference of the Circle
Date :
AIM: To write a C program to find the area and circumference of the circle
ALGORITHM:
Step 1: Start the program.
Step 2: Input the radius of the Circle.
Step 3: Find the area and circumference of the circle using the formula
Area =3.14*r*r
Circum=2*3.14*r
Step 4: Print the area and Circumference
Step 5: Stop the Program
PROGRAM: /*program to find the area and circumference of the circle*/
#include<stdio.h>
#include<conio.h>
void main()
{
float r,area,circum;
clrscr();
printf("\n Enter the radius of the Circle");
scanf("%f",&r);
area=3.14*r*r;
circum=2*3.14*r;
printf("\n Area=%f",area);
printf("\n Circumference=%f",circum);
getch();
}
RESULT: Thus the C program to find the area and circumference of the circle has been created
successfully and verified.
Ex. No : 1g) Ternary Operator
Date :
AIM: To write a C program to check the largest number among given two numbers.
ALGORITHM:
#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b,big; clrscr( );
printf("Enter the value of a: ");
scanf("%d",&a);
printf("Enter the value of b");
scanf(“%d”,&b);
big=(a>b)?a:b;
printf("Biggest of the given numbers is %d",big);
getch();
}
OUTPUT:
RESULT: Thus the program for Conditional Statements has been executed successfully and the output
was verified.
Ex. No : 1h) Finding the Roots of Quadratic Equation
Date :
ALGORITHM:
Step 1: Start
Step 7: Stop
#include <stdio.h>
#include <math.h>
#include <conio.h>
void main()
{
float a, b, c, d, r1,r2, real, imag; clrscr();
printf("\nTO FIND THE ROOTS OF A QUADRATIC EQUATION");
printf("\nEnter the coefficients a, b and c: ");
scanf("%f%f%f",&a,&b,&c);
d=b*b-4*a*c;
if (d>0)
{
r1= (-b+sqrt(d))/(2*a);
r2= (-b-sqrt(d))/(2*a);
printf("Roots are: %.2f and %.2f.They are real and distinct.", r1 , r2);
}
else if (d==0)
{
r1 = r2 = -b/(2*a);
printf("Roots are: %.2f and %.2f. They are real and equal.", r1, r2);
}
else
{
real= -b/(2*a);
imag = sqrt(-d)/(2*a);
printf("Roots are: %.2f+%.2fi and %.2f-%.2fi. They are complex.", real, imag,
real, imag);
}
getch();
}
OUTPUT:
RESULT:
Thus the C program for finding roots of quadratic equation was executed and output was
obtained.
Ex. No : 1i) File operations
Date :
AIM: To write a C program to writing some of the characters (without taking input from the keyboard)
and reading, printing, written characters
ALGORITHM:
PROGRAM: /* program to writing some of the characters (without taking input from the
keyboard) and reading, printing, written characters */
#include< stdio.h >
int main()
{
FILE *fp; /* file pointer*/
char fName[20];
printf("\nEnter file name to create :");
scanf("%s",fName);
fp=fopen(fName,"w"); /*creating (open) a file*/
if(fp==NULL) /*check file created or not*/
{
printf("File does not created!!!");
exit(0); /*exit from program*/
}
printf("File created successfully.");
putc('A',fp); /*writting into file*/
putc('B',fp);
putc('C',fp);
printf("\nData written successfully.");
fclose(fp);
fp=fopen(fName,"r"); /*again open file to read data*/
if(fp==NULL)
{
printf("\nCan't open file!!!");
exit(0);
}
printf("Contents of file is :\n");
printf("%c",getc(fp));
printf("%c",getc(fp));
printf("%c",getc(fp));
fclose(fp);
return 0;
}
OUTPUT:
RESULT: Thus the C program to writing some of the characters (without taking input from the
keyboard) and reading, printing, written characters was executed and output was obtained.
Ex. No : 1j) File Operations
Date :
AIM: To write a C program to writing characters (by taking input from the keyboard) to the file until
new line is not pressed and reading, printing the file.
PROGRAM: /* program to writing characters (by taking input from the keyboard) to the file
until new line is not pressed and reading, printing the file.*/
RESULT: Thus the C program to writing characters (by taking input from the keyboard) to the file until
new line is not pressed and reading, printing the file was executed and output was obtained.
Ex. No: 1k) ONE DIMENSIONAL ARRAY
Total of even Integers in an Array of N Numbers.
Date :
ALGORITHM
step1: start
Step 2: Read n and , n values to array A[]
Step3: initialize sum=0,i=0
Step 4: if(i<n) go to next step otherwise go to step 8
Step 5: if(A[i]%2==0) go to next step otherwise go to step 7
Step 6: sum=sum+A[i]
Step 7: i=i+1, go to step 4
Step8: print sum
Step 9 :stop
#include<stdio.h>
main()
{
int a[20],i,sum=0;
printf("enter5 integers");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
for(i=0;i<5;i++)
{
if(a[i]%2==0)
sum=sum+a[i];
}
prinf("sum =%d",sum);
getch();
}
OUTPUT :
Entger 5 integers
24782
Sum = 16
else
{
printf("\nEnter the First matrix-->");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter the Second matrix-->");
for(i=0;i<o;i++)
{
for(j=0;j<p;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("\n\nThe First matrix is\n"); for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
}
printf("\n\nThe Second matrix is\n");
for(i=0;i<o;i++)
{
printf("\n");
for(j=0;j<p;j++)
{
printf("%d\t",b[i][j]);
}
}
for(i=0;i<m;i++) //row of first matrix
{
for(j=0;j<p;j++) //column of second matrix
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]= c[i][j]+a[i][k]*b[k][j];
}
}
}
}
printf("\n\nThe multiplication of two matrix is\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<p;j++)
{
printf("%d\t",c[i][j]);
}
}
getch();
}
OUTPUT:
RESULT: Thus the C program to perform Matrix Multiplication was executed successfully and the output
was verified.
Ex. No: 2a) STRING FUNCTIONS IMPLEMENTATION
String Concatenation
Date :
OUTPUT:
RESULT: Thus the C program to perform String Concatenation is created successfully and the
output was verified.
Ex. No: 2b) String Comparison
Date :
AIM: To write a program to perform the string Comparison using C.
ALGORITHM:
Step 1: Start the program
Step 2: Declare the variables.
Step 3: Read input str1 and str2.
Step 4: Compare the two strings using for loop..
Step5: If the strings are equal then print “Strings are equal”.
Step 6: If the strings are not equal then print “Strings are not equal”.
Step 7: Stop the program
PROGRAM: /* program to perform the string Comparison using C*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
char str1[10],str2[10];
printf("\n Enter the String1:");
gets(str1);
printf("\n Enter the String2:");
gets(str2);
for(i=0;str1[i]!='\0'||str2[i]!='\0';i++)
if(str1[i]!=str2[i])
{ printf("\n Strings are not equal");
break;
}
else
{ printf("\n Strings are equal");
break;
}
getch();
}
OUTPUT:
RESULT: Thus the C program to perform String Comparison is created successfully and the output
was verified.
Ex. No: 2c) String Copy
Date :
ALGORITHM:
OUTPUT:
RESULT: Thus the C program to perform String Copy is created successfully and the output was
verified.
Ex. No: 2d) Length of the String
Date :
AIM: To write a program to find the length of the string using C.
ALGORITHM:
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
char str[20];
clrscr();
printf("\n Enter the String");
gets(str);
for(i=0;str[i]!='\0';++i);
printf("\n The no of characters in the String is %d",i);
getch();
}
OUTPUT:
RESULT: Thus the C program to find length of the string was created successfully and the output was
verified.
Ex. No: 3a) STRUCTURE IN C PROGRAM
Employee Details Using Structure
Date :
AIM: To write a C program to print the employee details of employees using structure.
ALGORITHM:
void main()
{
int i,n; clrscr();
printf("Enter Upper limit:");
scanf("%d",&n);
printf("Enter employee details:\n");
printf("Enter the EmployeeNo,Name and Salary:\n");
for(i=0;i<n;i++)
scanf("%d%s%d",&e[i].eno,e[i].ename,&e[i].salary);
printf("\n");
printf("Employee details are \n\n");
printf("Employee Id \t Employee Name \t Salary\n");
for(i=0;i<n;i++)
printf("%d\t\t%s\t\t%d\n",e[i].eno,e[i].ename,e[i].salary);
getch();
}
OUTPUT:
RESULT: Thus the program to print the employee details using structure is created
successfully and the output was verified.
Ex. No: 3b) UNION IN C PROGRAM
Date : Payroll Processing using Union
AIM: To write a C Program to create payroll processing using union.
ALGORITHM:
#include<stdio.h>
#include<string.h>
#include<conio.h>
union employee
{
char ename[30];
int eno;
float bsal;
};
void main()
{
union employee emp; char name[30];
int id;
float basic,hra,da,tds,net,gross;
clrscr();
printf("\EMPLOYEE PAYROLL PROCESSING\n");
printf("\----------------------------------\n");
printf("\nDETAILS OF THE EMPLOYEE\n\n");
printf("\nEnter the Employee Name: ");
scanf("%s",emp.ename);
strcpy(name,emp.ename);
printf("\nEnter the Employee Id: ");
scanf("%d",&emp.eno);
id=emp.eno;
OUTPUT:
RESULT: Thus a C program to implement the payroll processing using union was executed and
the output was obtained.
Ex. No: 3c) POINTERS IN C PROGRAM
Date: Print the elements of Array using Pointers
ALGORITHM:
step1: start
step2: Read array a[] with n elements
Step 3: initialize pointer p=&a[0] [or p=a]
Step 4:if i<n go to next step otherwise go to step 7
Step 5: print *(p+i)
Step 6:i=i+1 go to step 4
Step 7: stop
#include<stdio.h>
main()
{
int a[5]={5,4,6,8,9};
int *p=&a[0];
int i;
clrscr();
for(i=0;i<5;i++)
printf("%d ",*(p+i));
getch();
}
OUTPUT :
54689
RESULT: The program was compiled, executed and the output was verified
Ex. No: 4 DYNAMIC MEMORY ALLOCATIONS
Date:
AIM: To write a C program to create memory for int, char and float variable at run time.
ALGORITHM:
Step 2: Declare the variable under int, char and float data type.
Step 3: create memory for int, char and float variables at run time using malloc()function
Step 4: release the memory allocated at run time by using free() function.
PROGRAM: /* program to create memory for int, char and float variable at run time.*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *iVar;
char *cVar;
float *fVar;
iVar=(int*)malloc(1*sizeof(int));
cVar=(char*)malloc(1*sizeof(char));
fVar=(float*)malloc(1*sizeof(float));
printf("Enter integer value: ");
scanf("%d",iVar);
printf("Enter character value: ");
scanf(" %c",cVar);
printf("Enter float value: ");
scanf("%f",fVar);
printf("Inputted value are: %d, %c, %.2f\n",*iVar,*cVar,*fVar);
free(iVar);
free(cVar);
free(fVar);
return 0;
}
OUTPUT:
Enter integer value: 100
Enter character value: x
Enter float value: 123.45
Inputted value are: 100, x, 123.45
RESULT: Thus a C program to implement the Dynamic memory allocation was executed and the
output was obtained.
Note: create memory for text string at run time using malloc() function, text string will be inputted
by the user and displayed. Using free() function we will release the occupied memory.
PROGRAM: /*C program to input and print text using Dynamic Memory Allocation.*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
char *text;
printf("Enter limit of the text: ");
scanf("%d",&n);
text=(char*)malloc(n*sizeof(char)); /*allocate memory dynamically*/
printf("Enter text: ");
scanf(" "); /*clear input buffer*/
gets(text);
printf("Inputted text is: %s\n",text);
free(text); /*Free Memory*/
return 0;
}
OUTPUT:
RESULT: Thus a C program to implement the Dynamic memory allocation was executed and the
output was obtained.
Ex. No: 5a) IMPLEMENTATION OF STACK USING ARRAY
Date:
AIM: To write a program to create a Stack and manipulate it using one dimensional Array
ALGORITHM:
1. Start
2. Declare an one dimensional array variable
3. Using Switch case statement select one appropriate operation
a. PUSH:
i. Read an element
ii. Store it at the top of the stack
iii. Increment the TOS
b. POP
i. Read the element from the top of the stack
ii. Display it
iii. Decrement the TOS
c. PEEK
i. Read the element from the top of the stack
ii. Display it
4. Stop
#include<stdio.h>
#include<conio.h>
#define SIZE 4
int a[SIZE],top=0,ch=1,i,n;
void display();
void create();
void push();
void pop();
void peek();
void main()
{
clrscr();
printf("\n\t\tStack Using Arrays");
printf("\n\t\t------------------");
printf("\n\t\t 1.Create");
printf("\n\t\t 2.Push");
printf("\n\t\t 3.Pop");
printf("\n\t\t 4.Peek");
printf("\n\t\t 5.Exit\n");
do
{
printf("\t\tEnter Your Choice :");
scanf("%d",&ch);
switch(ch)
{
case 1: create();break;
case 2: push();break;
case 3: pop();break;
case 4: peek();break;
default: printf("\t\tExit");
break;
}
}while(ch!=5);
getch();
}
void create()
{
if(top==0)
{
printf("\t\tNumber of Element:");
scanf("%d",&n);
if(n>SIZE)
printf("\t\tSize of Stack is Large\n");
else
{
printf("\t\tPushing Element :");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
top=n;
display();
}
}
else
{
printf("\tStack Already Exists");
}
}
void push()
{
if(top==SIZE)
printf("\t\tStack Overflow\n");
else
{
printf("\t\tPushing Element :");
scanf("%d",&a[++top]);
display();
}
}
void pop()
{
if(top==0)
printf("\t\tStack Underflow\n");
else
{
printf("\t\tPop Element :%d\n",a[top--]);
display();
}
}
void display()
{
if(top==0)
printf("\t\tStack is Empty");
else
{
printf("\t\tStack Contains :");
for(i=top;i>=1;i--)
printf("%d ",a[i]);
}
printf("\n");
}
void peek()
{
if(top==0)
printf("\t\tStack Empty\n");
else
printf("\t\tTop Element is %d\n",a[top]);
}
OUTPUT:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
1. Push
2. Pop
3. Peek
4. Display
5. Exit
1. Push
2. Pop
3. Peek
4. Display
5. Exit
1. Push
2. Pop
3. Peek
4. Display
5. Exit
1. Push
2. Pop
3. Peek
4. Display
5. Exit
1. Push
2. Pop
3. Peek
4. Display
5. Exit
RESULT: Thus a C program to implement Stack using Array was executed and the output was
obtained.
Ex. No: 5b) IMPLEMENTATION OF QUEUE USING ARRAY
Date:
AIM: To write a program to create a Queue and manipulate it using one dimensional array
ALGORITHM:
1. Start
2. Read ch and n value
3. check (ch!=4) and if (rear =n) then read value
4. Assign value to q(rear) and increment the rear, else Display as queue if full
5. if (front=rear) then print front value of queue and increment front
Else Display as queue is empty
6. if (rear=0) then assign front to I and write q[i].
Else Display as queue is empty
7. Go to step 3
8. stop
PROGRAM : /* program to create a Queue and manipulate it using one dimensional array*/
#include<stdio.h>
#include<conio.h>
void main()
{
int q[50],i,j,n,op,front,rear,no;
clrscr();
printf("Enter the size of the queue:");
scanf("%d",&n);
printf("QUEUE OPERATIONS:\n1.Insert\n2.Delete\n3.Display\n4.Exit\n");
printf("Enter the operation to be performed:");
scanf("%d",&op);
front=0;rear=-1;
while(op!=4){
switch(op)
{
case 1:{
if(rear==n-1)
printf("\nQueue is full!\n");
else
{ printf("Enter the element to be inserted:");
scanf("%d",&no);
q[++rear]=no;
printf("\n%d is inserted!",no);
}
break; }
case 2: {
if(front==0 && rear==-1)
printf("\nQueue is empty!");
else
{ printf("\n%d is deleted!",q[front]);
q[front]=0;
for(j=front;j<rear;j++)
q[j]=q[j+1];
rear=rear-1;
}
break; }
case 3: {
printf("\nQueue is:\n");
for(i=front;i<=rear;i++)
printf("%d\t",q[i]);
break; }
}
printf("\nEnter the operation to be performed:");
scanf("%d",&op);
}
getch(); }
OUTPUT:
12 is inserted!
Enter the operation to be performed:1
Enter the element to be inserted:32
32 is inserted!
Enter the operation to be performed:3
Queue is:
12 32
Enter the operation to be performed:2
12 is deleted!
Enter the operation to be performed:3
Queue is:
32
Enter the operation to be performed:2
32 is deleted!
Enter the operation to be performed:2
Queue is empty!
Enter the operation to be performed:3
Queue is:
Ex. No : 6a)
STACK USING LINKED LIST
Date :
ALGORITHM :
1. Start
2. Read the value of ch
3. Allocate the malloc size to a variable
4. Get the item and store in data then link to Null value
5. Link the temp to top. Then check the top is Null then display as “ Stack is Empty”
6. If not as Null then print the top value
7. Print data as temp becomes Null
8. Stop
#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node* link;
}*head,*top,*curr;
void push(int data)
{
curr=(struct node*)malloc(sizeof(struct node));
curr->data=data;
curr->link=NULL;
if(top==NULL)
{
head=curr;
top=curr;
}
else
{
top->link=curr;
top=curr;
}
}
int pop()
{
int d=0;
d=top->data;
curr=head;
if(curr->link==NULL)
{
head=NULL;
top=NULL;
}
else
{
while(curr->link->link!=NULL)
{
curr=curr->link;
}
curr->link=NULL;
top=curr;
}
return d;
}
int peep()
{
return top->data;
}
void main()
{
int op,data;
clrscr();
do
{
printf("\nSTACK OPERATIONS:\n1.Push\n2.Pop\n3.Peep\n4.Exit\n");
printf("Enter the operation to be performed:");
scanf("%d",&op);
switch(op)
{
case 1:
{
printf("Enter the elemen to b pushed:");
scanf("%d",&data);
push(data);
break;
}
1 case 2:
{
printf("Popped element: %d",pop());
break;
}
case 3:
{
printf("Peeped element: %d",peep());
break;
}
case 4:
break;
default:
{
printf("\nEnter a proper option!\n");
}
}
}while(op!=4);
getch();
}
OUTPUT:
STACK OPERATIONS:
1.Push
2.Pop
3.Peep
4.Exit
Enter the operation to be performed:1
Enter the elemen to b pushed:12
STACK OPERATIONS:
1.Push
2.Pop
3.Peep
4.Exit
Enter the operation to be performed:1
Enter the elemen to b pushed:70
STACK OPERATIONS:
1.Push
2.Pop
3.Peep
4.Exit
Enter the operation to be performed:3
Peeped element: 70
STACK OPERATIONS:
1.Push
2.Pop
3.Peep
4.Exit
Enter the operation to be performed:2
Popped element: 70
STACK OPERATIONS:
1.Push
2.Pop
3.Peep
4.Exit
Enter the operation to be performed:3
Peeped element: 12
STACK OPERATIONS:
1.Push
2.Pop
3.Peep
4.Exit
Enter the operation to be performed:4
RESULT: Thus the program to implement stack using linked list has been successfully executed.
Ex. No : 6b)
QUEUE USING LINKED LIST
Date :
ALGORITHM:
1. Start
2. Read the value of ch
3. Get the variable temp and set malloc for size
4. Get item and store in data and link as Null
5. Get link of rear to temp. If front as Null and print Queue as Empty
6. Else print front element
7. print the data until the temp get Null
8. Stop
#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node* link;
}*head,*rear,*front,*curr;
void insert(int data)
{
curr=(struct node*)malloc(sizeof(struct node));
curr->data=data;
curr->link=NULL;
if(rear==NULL)
{
rear=curr;
front=curr;
}
else
{
rear->link=curr;
rear=curr;
}
}
int delete()
{
int d=0;
d=front->data;
curr=front;
front=front->link;
free(curr);
return d;
}
void display()
{
curr=front;
if(front==NULL)
printf("\nQueue empty!\n");
else if(front==rear)
printf("\nQueue is:%d",curr->data);
else
{
printf("\nQueue is:\n");
while(curr->link!=NULL)
{
printf("%d\t",curr->data);
curr=curr->link;
}
printf("%d\n",curr->data);
}
}
void main()
{
int op,data;
clrscr();
do
{
printf("\nQUEUE OPERATIONS:\n1.Insert\n2.Delete\n3.Exit\n");
printf("Enter the operation to be performed:");
scanf("%d",&op);
switch(op)
{
case 1:
{
printf("Enter the element to be inserted:");
scanf("%d",&data);
insert(data);
break;
}
case 2:
{
data=delete();
if(data)
printf("Deleted element: %d",data);
break;
}
case 3:
break;
default:
printf("\nEnter a proper option!\n");
}
display();
}while(op!=3);
getch();
}
OUTPUT:
QUEUE OPERATIONS:
1.Insert
2.Delete
3.Exit
Enter the operation to be performed:1
Enter the element to be inserted:34
Queue is:34
QUEUE OPERATIONS:
1.Insert
2.Delete
3.Exit
Enter the operation to be performed:1
Enter the element to be inserted:78
Queue is:
34 78
QUEUE OPERATIONS:
1.Insert
2.Delete
3.Exit
Enter the operation to be performed:1
Enter the element to be inserted:56
Queue is:
34 78 56
QUEUE OPERATIONS:
1.Insert
2.Delete
3.Exit
Enter the operation to be performed:2
Deleted element: 34
Queue is:
78 56
QUEUE OPERATIONS:
1.Insert
2.Delete
3.Exit
Enter the operation to be performed:3
RESULT: Thus the program to implement queue using linked list has been successfully executed.
Ex.NO.: 7a) APPLICATION OF STACK
Date: Convert Infix to Postfix Expression
AIM: To write a ‘C’ program to implement stack and use it to convert infix to postfix expression.
ALGORITHM:
character is an operator and if the stack is empty Push the character to stack.
5. If the scanned character is an Operand and the stack is not empty, compare the precedence of
the character with the element on top of the stack (topStack). If topStack has higher
precedence over the scanned character Pop the stack else Push the scanned character to stack.
Repeat this step as long as stack is not empty and topStack has precedence over the character.
6. (After all characters are scanned, we have to add any character that the stack may have to the
Postfix string.) If stack is not empty add topStack to Postfix string and Pop the stack. Repeat
this step as long as stack is not empty.
7. Return the Postfix string.
8. Terminate the program.
PROGRAM: // proram to implement stack and use it to convert infix to postfix expression.
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
char stack[100];
int top=0;
char exp[100];
struct table
{
char s[2];
int isp;
int icp;
}pr[7];
int isp(char c)
{
int i;
for(i=0;i<=6;i++)
if(pr[i].s[0]==c)
return(pr[i].isp);
return 0;
}
int icp(char c)
{
int i;
for(i=0;i<=6;i++)
if(pr[i].s[0]==c)
return(pr[i].icp);
return 0;
}
void main()
{
int i;
clrscr();
strcpy(pr[0].s,"^");
pr[0].isp=3;
pr[0].icp=4;
strcpy(pr[1].s,"*");
pr[1].isp=2;
pr[1].icp=2;
strcpy(pr[2].s,"/");
pr[2].isp=2;
pr[2].icp=2;
strcpy(pr[3].s,"+");
pr[3].isp=1;
pr[3].icp=1;
strcpy(pr[4].s,"-");
pr[4].isp=1;
pr[4].icp=1;
strcpy(pr[5].s,"(");
pr[5].isp=0;
pr[5].icp=4;
strcpy(pr[6].s,"=");
pr[6].isp=-1;
pr[6].icp=0;
clrscr();
stack[top]='=';
printf("enter the infix expression");
gets(exp);
i=0;
printf("the postfix expression is ")
while(i<strlen(exp))
{
if(isalpha(exp[i])==0)
{
if(exp[i]==')')
{
while(stack[top]!='(')
{
printf("%c",stack[top]);
top--;
}
top--;
}
else
{
while(isp(stack[top])>=icp(exp[i]))
{
printf("%c",stack[top]);
top--;
}
top++;
stack[top]=exp[i];
}
}
else
printf("%c",exp[i]);
i++;
}
while(top>0)
{
printf("%c",stack[top]);
top--;
}
getch();
}
OUTPUT:-
enter the infix expression a*(s+d/f)+c
the postfix expression is asdf/+*c+
RESULT:-
The given program was implemented, executed, tested and verified successfully.
Ex.NO.: 7b) APPLICATION OF QUEUE
Breadth First Search
Date:
AIM: To write a program to traverse the tree using breadth first search.
ALGORITHM:
1. Start
2. Read the size value in choice=1 and get the vertex value
3. Set for loop of condition i=1 and i<n
4. Read the number of edges
5. Set for loop of condition j<= no. of edges and j=1
6. Read the edge position
7. if Ch=2 then check a[i][j]==1
then check v[j]=0
printf v[j]
8. If ch==3 for display set for loop i<=n and print vt[i]
9. Set for loop j<=n and then print the a[i][j]
10. Stop
PROGRAM :
#include<stdio.h>
void insert(int c);
int del();
int front=-1,rear=-1;
int q[30],ans[10],k=0;
void main()
{
int i,j,n,no,a[10][10];
clrscr();
printf("\n Enter the number of Nodes: ");
scanf("%d",&n);
printf("\n Enter the adjacency matrix of the graph:\n ");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
printf("\n Adjacency is: \n ");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("\t %d",a[i][j]);
printf("\n");
}
insert(0);
printf("\bBreadth First Search of the nodes is:\n");
while(rear!=front)
{
i=del();
printf("\t:%d",i+1);
for(j=0;j<n;j++)
{
if (a[i][j]==1)
insert(j);}
}
getch();
}
int del()
{
return q[++front];
}
void insert(int c)
{
int i,count=0;
for(i=0;i<k;i++)
{
if(ans[i]==c)
{
count=1;
break;
}
}
if(count==0)
{
q[++rear]=c;
ans[k++]=c;
}
Expected Output
Adjacency is:
0 1 1 0
1 0 1 0
1 1 0 1
1 0 1 0
Breadth First Search of the nodes is:
:1 :2 :3 :4
RESULT: Thus the program for quick sort has been successfully executed
Ex.No.:8 IMPLEMENTATION OF TREE AND TREE TRAVERSALS
Date:
AIM:-
To write a ‘C’ program to implement an expression tree. Produce its pre-order, in-
order, and post-order traversals.
ALGORITHM:-
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct treenode
{
int data;
struct treenode *left;
struct treenode *right;
}tnode;
tnode *insertion(int,tnode*);
void preorder(tnode *);
void inorder(tnode *);
void postorder(tnode *);
void main()
{
tnode *T=NULL;
int ch1,n;
char ch2;
do
{
clrscr();
printf("\n\t\t****Operation With Tree****");
printf("\n\t1.Insertion");
printf("\n\t2.Inorder Traversal");
printf("\n\t3.Preorder Traversal");
printf("\n\t4.Postorder Traversal");
printf("\n\tEnter Your Choice :");
scanf("%d",&ch1);
switch(ch1)
{
case 1:
printf("\n\nenter the element to be inserted :");
scanf("%d",&n);
T=insertion(n,T);
break;
case 2:
inorder(T);
break;
case 3:
preorder(T);
break;
case 4:
postorder(T);
break;
default:
printf("\n\nInvalid Option");
break;
}
printf("\n\nDo you want to continue y/n : ");
scanf("%s",&ch2);
}while(ch2=='y');
getch();
}
tnode *insertion(int x,tnode *T)
{
if(T==NULL)
{
T=(tnode *)malloc(sizeof(tnode));
if(T==NULL)
printf("\nout of space");
else
{
T->data=x;
T->left=T->right=NULL;
}
}
else
{
if(x<(T->data))
T->left=insertion(x,T->left);
else
{
if(x>T->data)
T->right=insertion(x,T->right);
}
}
return T;
}
void preorder(tnode *T)
{
if(T!=NULL)
{
printf("\t%d",T->data);
preorder(T->left);
preorder(T->right);
}
}
RESULT:-
The given program was implemented, executed, tested and verified successfully
Date:
ALGORITHM:-
Step 4: Data values are given which we call a key and a binary search tree
Step 5: To search for the key in the given binary search tree, start with the root node and
Compare the key with the data value of the root node. If they match, return the
root pointer.
Step 6: If the key is less than the data value of the root node, repeat the process by using
the left subtree.
Step 7: Otherwise, repeat the same process with the right subtree until either a match is
found or the subtree under consideration becomes an empty tree.
Step 8: Terminate
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<alloc.h>
struct tree
{
int data;
struct tree *lchild;
struct tree *rchild;
}*t,*temp;
int element;
void inorder(struct tree *);
void preorder(struct tree *);
void postorder(struct tree *);
struct tree * create(struct tree *, int);
struct tree * find(struct tree *, int);
struct tree * insert(struct tree *, int);
struct tree * del(struct tree *, int);
struct tree * findmin(struct tree *);
struct tree * findmax(struct tree *);
void main()
{
int ch;
do
{
printf("\n\t\t\tBINARY SEARCH TREE");
printf("\n\t\t\t****** ****** ****");
printf("\nMain Menu\n");
printf("\n1.Create\n2.Insert\n3.Delete\n4.Find\n5.FindMin\n6.FindMax");
printf("\n7.Inorder\n8.Preorder\n9.Postorder\n10.Exit\n");
printf("\nEnter ur choice :");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter the data:");
scanf("%d",&element);
t=create(t,element);
inorder(t);
break;
case 2:
printf("\nEnter the data:");
scanf("%d",&element);
t=insert(t,element);
inorder(t);
break;
case 3:
printf("\nEnter the data:");
scanf("%d",&element);
t=del(t,element);
inorder(t);
break;
case 4:
printf("\nEnter the data:");
scanf("%d",&element);
temp=find(t,element);
if(temp->data==element)
printf("\nElement %d is at %d",element,temp);
else
printf("\nElement is not found");
break;
case 5:
temp=findmin(t);
printf("\nMax element=%d",temp->data);
break;
case 6:
temp=findmax(t);
printf("\nMax element=%d",temp->data);
break;
case 7:
inorder(t);
break;
case 8:
preorder(t);
break;
case 9:
postorder(t);
break;
case 10:
exit(0);
}
}while(ch<=10);
}
t->data=element;
t->lchild=NULL;
t->rchild=NULL;
return t;
}
else
{
if(element<t->data)
{
t->lchild=insert(t->lchild,element);
}
else
if(element>t->data)
{
t->rchild=insert(t->rchild,element);
}
else
if(element==t->data)
{
printf("element already present\n");
}
return t;
}
}
OUTPUT:
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :1
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :2
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :2
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :2
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :4
Element 25 is at 2216
BINARY SEARCH TREE
****** ****** ****
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :5
Max element=10
BINARY SEARCH TREE
****** ****** ****
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :6
Max element=30
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :7
10 20 25 30
BINARY SEARCH TREE
****** ****** ****
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :8
10 20 30 25
BINARY SEARCH TREE
****** ****** ****
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :9
25 30 20 10
BINARY SEARCH TREE
****** ****** ****
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :3
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
RESULT:-
The given program was implemented, executed, tested and verified successfully.
Ex.No. 10a) LINEAR SEARCH
Date:
ALGORITHM:
PROGRAM:
#include <stdio.h>
int main()
{
int array[100], search, c, n;
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter a number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);
return 0;
}
OUTPUT:
RESULT: The given program was implemented, executed, tested and verified successfully
Ex.No. 10b) BINARY SEARCH
Date:
ALGORITHM:
PROGRAM:
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d",&array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0;
` last = n - 1;
middle = (first+last)/2;
while (first <= last)
{
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search)
{
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
RESULT: The given program was implemented, executed, tested and verified successfully.
Ex.No. 11a) INSERTION SORT
Date:
AIM: To write a program to sort the given list of elements using Insertion Sort.
ALGORITHM:
OUTPUT:
RESULT: The given program was implemented, executed, tested and verified successfully.
Ex.No. 11b) BUBBLE SORT
Date:
AIM: To write a program to sort the given list of elements using BUBBLE Sort.
ALGORITHM:
OUTPUT:
RESULT: The given program was implemented, executed, tested and verified successfully.
Ex.No. 11c) QUICK SORT
Date:
AIM: To write a program to sort the given list of elements using quick Sort.
ALGORITHM:
OUTPUT:
QUICK SORT
Enter the number of elements:5
Enter the elements:7
9
4
3
1
RESULT: Thus the program for quick sort has been successfully executed.
Ex.No. 11d) MERGE SORT
Date:
AIM: To write a program to sort the given list of elements using MERGE Sort.
ALGORITHM:
include <stdio.h>
#define max 10
int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 };
int b[10];
for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++)
b[i] = a[l1++];
else
b[i] = a[l2++]; }
b[i++] = a[l1++];
b[i++] = a[l2++];
for(i = low; i <= high; i++)
a[i] = b[i];
{ int mid;
sort(low, mid);
sort(mid+1, high);
Else
{ return;
int main()
{ int i;
sort(0, max);
Date:
ALGORITHM:-
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a[125],key,size,i,h;
clrscr();
printf("\n Enter the array size:");
scanf("%d",&size);
printf("\n Enter the array element:");
for(i=0;i<size;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the key value");
scanf("%d",&key);
h=key%size;
while(h!=i)
i++;
printf("The element is %d",a[i]);
getch();
}
OUTPUT:
Enter the array size:4
RESULT: Thus the implementation of hashing technique has been successfully executed.
Ex.No. 12b) Implement Hash Tables with Linear Probing
Date:
ALGORITHM:
1. Create a structure, item having a key and value representing data to be inserted in hash table.
2. Create another structure, hash table_item with variable data (key and value) and flag as a status variable which
informs about the status of array index.
flag = 1 : presence of some data at the array index.
flag = 0 : data not present in array index even once
flag = 2 : data had been removed from array index at least once
3. Now create an array of structure (hashtable_item) of some certain size (10, in this case). This array will be our
hash table.
4. A menu is displayed on the screen.
5. User must choose one option from four choices given in the menu.
6. 1st choice: Inserting item into hash table
(a) Take a key and a value as input.
(b) Calculate index as per the given key (using hashcode() function).
(c) Access the element at this calculated index in array.
(d) If there is no element at that particular array index, add straight way.
(e) If an element is present, check whether the given key matches the element’s key. If yes, then update it’s value
and return. Otherwise probe through subsequent elements (looping back if necessary), to find free space. While
probing
* if given key matches the element’s key, update its value and return.
* if a free space is found, add the data at that position.
Probing will stop until we reach the same element from where we began probing. Until then, if no free space is
found, then add will fail.
7. 2nd choice: Removing a key from hash table
(a) Take a key as input which needs to be removed.
(b) Calculate index as per the given key (using hashcode() function).
(c) Access the element at the calculated array index.
(d) If an element is present, check whether the given key matches the element’s key. If yes, then delete the key and
return decrementing the size. Otherwise probe through subsequent elements (looping back if necessary), to find free
space with flag = 0. While probing
* if given key matches the element’s key, delete and return.
* if a free space is found (with flag = 2), continue to probe.
(e) If no free space (flag = 0) is found even after probing through all element it means, key does not exist in the hash
table.
8. 3rd choice: Size of hash table
(a) Each time we add a new data item into the hash table, we increment it’s size by 1.
(b) Each time we remove a data item from the hash table, we decrement it’s size by 1.
(c) The size of the hash table can be determined either by size variable or size_of_hashtable() method.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
struct item /* to store a data (consisting of key and value) in hash table array */
{
int key;
int value;
};
struct hashtable_item
{ /* each hash table item has a flag (status) and data (consisting of key and value) */
int flag;
/*
* flag = 0 : data does not exist
* flag = 1 : data exists
* flag = 2 : data existed at least once
*/
struct item *data;
};
struct hashtable_item *array;
int size = 0;
int max = 10;
void init_array() /* initializing hash table array */
{
int i;
for (i = 0; i < max; i++)
{
array[i].flag = 0;
array[i].data = NULL;
}
}
int hashcode(int key) /* to every key, it will generate a corresponding index */
{
return (key % max);
}
void insert(int key, int value) /* to insert an element in the hash table */
{
case 3: n = size_of_hashtable();
printf("Size of Hashtable is-:%d\n", n);
break;
case 4: display();
break;
default: printf("Wrong Input\n");
}
printf("\n Do you want to continue-:(press 1 for yes)\t");
scanf("%d", &c);
}while(c == 1);
getch();
OUTPUT:
MENU-:
1. Inserting item in the Hashtable
2. Removing item from the Hashtable
3. Check the size of Hashtable
4. Display Hashtable
RESULT: Thus the C Program to Implement Hash Tables with Linear Probing has been completed successfully
Ex.No. 12c) Implement Hash Tables with Quadratic Probing.
Date:
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
/* to store a data (consisting of key and value) in hash table array */
struct item
{
int key;
int value;
};
/* each hash table item has a flag (status) and data (consisting of key and value) */
struct hashtable_item
{
int flag;
/*
* flag = 0 : data does not exist
* flag = 1 : data exists at given array location
* flag = 2 : data was present at least once
*/
struct item *data;
};
struct hashtable_item *array;
int size = 0;
int max = 10;
/* this function returns corresponding index of the given key */
int hashcode(int key)
{
return (key % max);
}
/* this function initializes the hash table array */
void init_array()
{
int i;
for (i = 0; i < max; i++)
{
array[i].flag = 0;
array[i].data = NULL;
}
}
/* this function inserts an element in the hash table */
void insert(int key, int value)
{
int index = hashcode(key);
int i = index;
int h = 1;
struct item *new_item = (struct item*) malloc(sizeof(struct item));
new_item->key = key;
new_item->value = value;
/* probing through the array until an empty space is found */
while (array[i].flag == 1)
{
if (array[i].data->key == key)
{
/* case when already present key matches the given key */
printf("\n This key is already present in hash table, hence updating it's
value \n");
array[i].data->value = value;
return;
}
i = (i + (h * h)) % max;
h++;
if (i == index)
{
printf("\n Hash table is full, cannot add more elements \n");
return;
}
}
array[i].flag = 1;
array[i].data = new_item;
printf("\n Key (%d) has been inserted\n", key);
size++;
}
/* to remove an element form the hash table array */
void remove_element(int key)
{
int index = hashcode(key);
int i = index;
int h = 1;
/* probing through the hash table until we reach at location where there had not been an
element even once */
while (array[i].flag != 0)
{
if (array[i].flag == 1 && array[i].data->key == key)
{
/* case where data exists at the location and its key matches to the given
key */
array[i].flag = 2;
array[i].data = NULL;
size--;
printf("\n Key (%d) has been removed \n", key);
return;
}
i = (i + (h * h)) % max;
h++;
if (i == index)
{
break;
}
}
printf("\n Key does not exist \n");
}
/* to display the contents of hash table */
void display()
{
int i;
for(i = 0; i < max; i++)
{
if (array[i].flag != 1)
{
printf("\n Array[%d] has no elements \n", i);
}
else
{
printf("\n Array[%d] has elements \n %d (key) and %d (value) \n", i,
array[i].data->key, array[i].data->value);
}
}
}
int size_of_hashtable()
{
return size;
}
void main()
{
int choice, key, value, n, c;
clrscr();
array = (struct hashtable_item*) malloc(max * sizeof(struct hashtable_item*));
init_array();
do {
printf("Implementation of Hash Table in C with Quadratic Probing.\n\n");
printf("MENU-: \n1.Inserting item in the Hash table"
"\n2.Removing item from the Hash table"
"\n3.Check the size of Hash table"
"\n4.Display Hash table"
"\n\n Please enter your choice-:");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Inserting element in Hash table \n");
printf("Enter key and value-:\t");
scanf("%d %d", &key, &value);
insert(key, value);
break;
case 2:
printf("Deleting in Hash table \n Enter the key to delete-:");
scanf("%d", &key);
remove_element(key);
break;
case 3:
n = size_of_hashtable();
printf("Size of Hash table is-:%d\n", n);
break;
case 4:
display();
break;
default:
printf("Wrong Input\n");
}
printf("\n Do you want to continue-:(press 1 for yes)\t");
scanf("%d", &c);
}while(c == 1);
getch();
}
OUTPUT:
MENU-:
1. Inserting item in the Hash table
2. Removing item from the Hash table
3. Check the size of Hash table
4. Display Hash table
RESULT: Thus the C Program to Implement Hash Tables with Quadratic Probing has been completed
successfully
Ex. No : 13
Depth First Search
Date :
Aim: To write a program to traverse the tree using Depth first search.
Algorithm:
1. Start
2. Read the value of n
3. Set for loop as i<n as i=0
4. Set for loop as j>n as j=0
5. Read adjacency of adj[i][j]
Read dfs(s)
6. Set for loop i<n and execute check whether (!vis[i]) then
Dfs(i)
7. Stop
Program Code
#include<stdio.h>
#include<conio.h>
#define max 50
int adj[max][max];
int vertex[max];
int visited[max];
void creategraph(int);
void dfs(int,int);
void depthfirst(int);
void main()
{
int ch,n,v;
clrscr();
do
{
printf("\n1.create graph"
"\n2.dfs"
"\n3.exit"
"\n Enter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1:{ printf("\n Enter no. of vertices to be created");
scanf("%d",&v);
creategraph(v);
break; }
case 2: depthfirst(v);
break;
case 3:printf("end of the program");
break;
}
}while(ch!=3);
getch();
}
void creategraph(int v)
{
int i,j,n,m,k;
for(i=0;i<v;i++)
{
printf("\n Enter the node value");
scanf("%d",&vertex[i]);
visited[i]=0;
}
for(j=0;j<v;j++)
adj[i][j]=0;
printf("Enter the adjacency vertices list");
printf("for each vertex of the graph");
for(i=0;i<v;i++)
{
printf("\n Enter the no.of adjancey vertices for the vertex %d",vertex[i]);
scanf("%d",&n);
for(j=0;j<n;j++)
{
printf("\n Enter adjacency vertex");
scanf("%d",&m);
for(k=0;k<v;k++)
{
if(vertex[k]==m)
adj[i]]k]=1;
}
}
}
printf("\n graph created with no. of vertices");
printf("the adjacency matrix of graph\n");
for(i=0;i<v;i++)
{
for(j=0;j<v;j++)
printf("%d\t",adj[i][j]);
printf("\n");
}
}
void depthfirst(int v)
{
int i;
for(i=0;i<v;i++)
visited[i]=0;
visited[0]=1;
printf("Depth first serach \n");
printf("%d",vertex[0]);
dfs(0,v);
}
void dfs(int ad,int v)
{
int j,k;
for(k=ad;k<v;k++)
for(j=0;j<v;j++)
if(adj[k][j]==1)
{
if(visited[j]==0)
{
visited[j]=1;
printf("%d",vertex[j]);
dfs(j,v);
}
}
}
Expected Output
1.create graph
2.dfs
3.exit
Enter your choice1
Enter the adjacency vertices list for each vertex of the graph
Enter the no.of
adjancey vertices
for the vertex 1
RESULT: Thus the C Program depth first search has been completed successfully