0% found this document useful (0 votes)
5 views

Mukesh Ds Practical File

Uploaded by

anshigk13
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Mukesh Ds Practical File

Uploaded by

anshigk13
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

COCHIN UNIVERSITY OF SCIENCE AND TECHNOLOGY

DEPARTMENT OF COMPUTER APPLICATIONS


KOCHI, KERALA, INDIA

DATA STRUCTURES

LABORATORY RECORD

Name : MUKESH KUMAR


Register No. : 38222048
Semester & Course : I, Masters in Computer Application
Year : 2022

Certified that this is a bonafide record of work done by Mr. Mukesh Kumar in
the Data Structures Laboratory of the Department of Computer Applications,
Cochin University of Science and Technology.

Faculty in Charge Head of the Department


2
CONTENT

Sr. Topics Pg.


No. No.

1. Write a C program to evaluate the arithmetic expression ((a -b / c * d + 5


e)* (f +g)) and display its solution.

2. Create a C Program to read 3 integer values, find the largest among them 5-6

3. Develop a C program to check if the number is Prime or not. 6-7

4. Develop a program to check whether the given number is armstrong or 7-8


not.

5. Write a c program to read a string and count the number of vowels, 8-10
consonants and spaces in it.

6. Using structure, write a program to read and print data of n employees 10-11
(Name, EmployeeId and Salary)

7. Write a C program to create a fibonacci series using recursive function. 12

8. Find the factorial of a given Natural Number n using 12-14


i) a non recursive function
ii) a recursive function

9. Do the following using pointers 14-15


i) add two numbers
ii) swap two numbers using user defined function

10. Construct binary search trees to perform insertion, deletion, search. 15-20

11. Apply Queue and stack in Breadth First Search and Depth First Search 20-25
respectively

12. Write a program to create a binary search tree and find the number of 25-30
leaf nodes

13. Create a binary search tree with the following operations: 30-35
i)Insert a new node
ii)Inorder traversal
iii)Preorder traversal
iv)Postorder traversal

3
v) Delete a node.

14. Design, develop, and execute a program in C to create a max heap and 35-39
perform the following operations
i)Insertion
ii)Deletion
iii)Print Largest Value

15. Write a program to implement Depth First Search (DFS) graph traversal 39-43
methods.

16. Write a program to implement Breadth First Search (BFS) graph 43-47
traversal methods

17. Create a text file containing the name, height, weight of the students in a 47-53
class. Perform Quick sort and Merge sort on this data and store the
resultant data in two separate files. Also write the time taken by the two
sorting methods into the respective files. Sony Mathew 5.5 60 Arun
Sajeev 5.7 58 Rajesh Kumar 6.1 70

18. Write a program to sort a set of numbers using Heap sort and find a 53-57
particular number from the sorted set using Binary Search.

19. Implement a Hash table using Chaining method. Let the size of hash 57-61
table be 10 so that the index varies from 0 to 9.

20. Implement a Hash table that uses Linear Probing for collision resolution 61-66

4
1. Write a C program to evaluate the arithmetic expression ((a -b / c * d + e) * (f +g))
and display its solution.

Objective: To familiarize the basic data types and arithmetic operations in C


Algorithm:
1. Declare variables a, b, c, d, e, f, g and result.
2. Read variables a, b, c, d, e, f, g.
3. If c == 0 : print(“Zero Division Error”) and go to step 6..
4. Else evaluate the expression and store it in result.
5. Print the result.
6. Exit.
Source Code :

#include <stdio.h>
int main(){
int a, b, c, d, e, f, g, result;
printf("Enter variable to evaluate((a-b/c*d+e)*(f +g))\n");
printf("Enter a, b, c, d, e, f, g : ");
scanf("%d %d %d %d %d %d %d", &a, &b, &c, &d, &e, &f, &g);
if(c == 0)
printf("Zero Division Error !\n");
else{
result = (a - ((b / c) * d) + e) * (f + g);
printf("(a -b / c * d + e) * (f +g) = %d\n", result);
}
return 0;
}

Output :
Enter variable to evaluate((a -b / c * d + e) * (f +g))
Enter a, b, c, d, e, f, g : 10 10 5 2 4 5 6
(a -b / c * d + e) * (f +g) = 110

2. Create a C Program to read 3 integer values, find the largest among them.

Objective: To familiarize use of conditional operators in C.


Algorithm:
1. Declare variables a, b, c as int.
2. Check if a>b and a>c : if True print(“a” is largest).

5
3. Otherwise check if b>a and b>c : if True print(“b” is largest).
4. Otherwise check if c>a and c>b : if True print(“c” is largest).
5. Exit
Source Code :
#include <stdio.h>
int main(){
int a, b, c, max;
printf("Enter num1, num2, num3 to find largest among them :
");
scanf("%d %d %d", &a, &b, &c);
if(a>b && a>c)
printf("'a' = %d is the largest no.\n", a);
else if(b>a && b>c)
printf("'b' = %d is the largest no.\n", b);
else if(c>a && c>b)
printf("'c' = %d is the largest no.\n", c);
return 0;
}
Output :
Enter num1, num2, num3 to find largest among them : 10 20 15
'b' = 20 is the largest no.

3. Develop a C program to check if the number is prime or not.

Objective: To familiarize the iterative structures in C.


Algorithm:
1. Declare variables ‘num’, ‘i’ and ‘isPrime’ as integer.
2. Check num <= 0, if True print(“Negative and Zero not allowed”)
3. Otherwise check num == 1, if True print(“1 is a Unique Number”)
4. Otherwise, assign isPrime = 1.
5. Assign i = 2.
6. Repeat steps 7 to 9 till i < n otherwise go to step no. 10
7. Check n%i == 0 :
If True : print(“Not a prime Number”)
Assign isPrime = 0 and go to step no. 10.
8. Increment i by 1.
9. Go to step 6
10. Check isPrime == 1 : if True print(“A prime No.”)
11. Stop.
Source Code :
#include <stdio.h>

6
#define True 1
#define False 0
int main(){
int num, i, isPrime;
printf("Enter a natural no. to check if it is prime : ");
scanf("%d", &num);
if(num<=0)
printf("Negative and zero not allowed!\n");
else if(num == 1)
printf("1 is Unique number");
else{
isPrime = True;
for(i = 2; i<num; i++){
if(num%i == 0){
isPrime = False;
break;}
}
if(isPrime)
printf("%d is a prime no.\n", num);
else
printf("%d is not a prime no.\n", num);
}
return 0;
}
Output :
Enter a natural no. to check if it is prime : 17
17 is a prime no.

4. Develop a program to check whether the given number is Armstrong or not.

Objective: To familiarize the looping statements in C.


Algorithm:
1. Declare variables ‘num’, ‘numCopy’, ‘cntDigits’, ‘rem’, ‘sum’, ‘i’.
2. Read ‘num’.
3. Assign numCopy = num.
4. Assign cntDigits = 0;
5. Repeat steps 6 to 7 until numCopy > 0.
6. Increment cntDigits by 1.
7. numCopy = numCopy/10.
8. Assign sum = 0 and numCopy = num.
9. Repeat steps 10 to 12 until numCopy > 0.
10. rem = numCopy%10.
11. sum = sum + power(rem, cntDigits)

7
12. numCopy = numCopy/10.
13. Check numCopy == num
If true : print(“An armstrong number”)
14. Otherwise print(“Not an Armstrong number”)
15. Exit
*power(base, exp)
1. Declare variable ‘i’ and ‘result’ as int.
2. Assign ‘result’ = 1 and ‘i’ = 1.
3. Repeat Steps 4 to 5 until i <= exp
4. result = result * base
5. Increment i by 1.
6. Return result.
Source Code :
#include <stdio.h>
int power(int base, int exp);
int main(){
int num, numCopy, cntDigits, rem, sum, i;
printf("Enter a no. to check if it is Armstrong : ");
scanf("%d", &num);
numCopy = num;
for(cntDigits = 0; numCopy > 0; numCopy /= 10, cntDigits++);
for(sum = 0, numCopy = num; numCopy; numCopy/=10){
rem = numCopy%10; sum += power(rem, cntDigits);}
if(sum == num)
printf("%d is an Armstrong Number\n", num);
else
printf("%d is not an Armstrong Number\n", num);
return 0;
}
int power(int base, int exp){
int res;
for(res = 1; exp; res = res*base, exp--);
return res;}
Output :
Enter a no. to check if it is Armstrong : 153
153 is an Armstrong Number

5. Write a c program to read a string and count the number of vowels, consonants
and spaces in it.

Objective: To familiarize string manipulation in C.


Algorithm:

8
1. Declare an array of characters ‘str[100]’.
2. Declare variables ‘i’, ‘cntVowels’, ‘cntSpaces’ and ‘cntCons’ as int.
3. Read ‘str’.
4. Assign cntVowels = cntSpaces = cntCons = 0.
5. Assign i = 0;
6. Repeat steps 7 to 11 until str[i] is not the last character of the string.
7. Check str[i] is a character or a space
If true then proceed
Otherwise go to step no. 11.
8. Check str[i] to be a vowel if true increment cntVowels by 1.
9. Otherwise check str[i] to be a space, if true increment cntSpaces by 1.
10. Otherwise increment cntCons by 1.
11. Increment i by 1.
12. Print the count of vowels, consonants and spaces.
Source Code :
#include <stdio.h>
int main(){
char str[100];
int i, cntVowels, cntSpaces, cntCons;
printf("Enter a string to count vowels, consonants and
spaces : ");
scanf("%[^\n]s", str);
cntVowels = cntSpaces = cntCons = 0;
for(i = 0; str[i] != '\0'; i++)
{
if((str[i] >= 65 && str[i] <= 90) || (str[i] >= 97 &&
str[i] <= 122) || str[i] == ' ')
{
switch(str[i]){
case 'a' : case 'e' : case 'i' : case 'o' : case
'u' : case 'A' : case 'E' : case 'I' : case 'O' : case 'U' :
cntVowels++;break;
case ' ' : cntSpaces++;break;
default : cntCons++;
}}
}
printf("No. of vowels : %d\n", cntVowels);
printf("No. of consonants : %d\n", cntCons);
printf("No. of spaces : %d\n", cntSpaces);
return 0;
}
Output :

9
Enter a string to count vowels, consonants and spaces : The
quick brown fox jumped over the lazy dog.
No. of vowels : 12
No. of consonants : 24
No. of spaces : 8

6. Using structure, write a program to read and print data of n employees (Name,
EmployeeId and Salary)

Objective: To familiarize use of structures in C.


Algorithm:
1. Declare a structure ‘Employee’ with field members.
a. emp_name as character array.
b. emp_Id as character array.
c. emp_salary as double.
2. Declare ‘emp’ a pointer to the struct Employee.
3. Declare ‘n’ and ‘i’ as int.
4. Read ‘n’.
5. Allocate memory equivalent to store ‘n’ records and assign to emp.
6. Assign i = 0.
7. Repeat Steps 8 to 9 until i < n
8. Read emp[i] all the field members.
9. Increment i.
10. Display all the records.
Source Code :
#include <stdio.h>
#include <stdlib.h>
struct Employee{
char emp_name[20]; char emp_Id[5]; double emp_salary;
};
int main(){
struct Employee *emp;
int n, i;
printf("Enter no. of Employees : ");
scanf("%d", &n);
emp = (struct Employee *) calloc(n, sizeof(struct
Employee));
for(i = 0; i<n; i++){
printf("\n___Fill in Employee %d details___\n", i+1);
printf("Employee Name : ");
scanf(" %[^\n]s", (emp+i)->emp_name);

10
printf("Employee Id : ");
scanf("%s", (emp+i)->emp_Id);
printf("Employee Salary : ");
scanf("%lf", &((emp+i)->emp_salary));
}
for(i = 0; i<n; i++){
printf("\n---Employee %d Details---\n", i+1);
printf("NAME : %s\n", (emp+i)->emp_name);
printf("ID : %s\n", (emp+i)->emp_Id);
printf("SALARY : %lf\n", (emp+i)->emp_salary);
}
free(emp);
return 0;
}
Output :
Enter no. of Employees : 3 ---Employee 1 Details---
NAME : Rama
___Fill in Employee 1 ID : e001
details___ SALARY : 10000.000000
Employee Name : Rama
Employee Id : e001 ---Employee 2 Details---
Employee Salary : 10000.00 NAME : Krishna
ID : e002
___Fill in Employee 2 SALARY : 20000.200000
details___
Employee Name : Krishna ---Employee 3 Details---
Employee Id : e002 NAME : Hari
Employee Salary : 20000.20 ID : e003
SALARY : 12000.200000
___Fill in Employee 3
details___
Employee Name : Hari
Employee Id : e003
Employee Salary : 12000.20

7. Write a C program to create a Fibonacci series using recursive function.

Objective: To familiarize use of recursion in C.


Algorithm:
1. Declare n, firstTerm, secondTerm, currTerm as int.
2. Read n.

11
3. Assign firstTerm = 0, secondTerm = 1 and currentTerm = 1.
4. Call genFibSeries(firstTerm, secondTerm, currentTerm, n).
genFibSeries(first, second, current, n)
1. Check current <= n
If true : print(first)
Increment current by 1
Class genFibSeries(second, first+second, current, n)
2. Otherwise return.
Source Code :
#include <stdio.h>
void genFibSeries(int firstTerm, int SecondTem, int currTerm,
int nTerms);
int main(){
int n, firstTerm, secondTerm, currTerm;
printf("Enter no. of terms to generate Fibonacci Series :
");
scanf("%d", &n);
firstTerm = 0; secondTerm = 1; currTerm = 1;
genFibSeries(firstTerm, secondTerm, currTerm, n);
return 0;
}
void genFibSeries(int first, int second, int currTerm, int
nTerms){
if(currTerm <= nTerms){
printf("%d\t", first);
genFibSeries(second, first+second, currTerm+1, nTerms);
}}
Output :
Enter no. of terms to generate Fibonacci Series : 10
0 1 1 2 3 5 8 13
21 34

8. Find the factorial of a given Natural Number using


i) A non-recursive function
ii) A recursive function

Objective: To understand the difference between recursive and non-recursive functions


in C.
Algorithm:

1. Declare num.

12
2. Read num.
3. Call factorial()
4. Call recFactorial()
5. Exit
factorial(num)
1. Declare i, fact.
2. Assign fact = 1 and i = 1.
3. Repeat steps 4 to 5 until i<=num
4. Fact = fact * i
5. Increment i by 1
6. Print fact.
recFactorial(num)
1. Check num <= 1 if true return 1
2. Otherwise return(num * recFactorial(num-1))
Source Code :
#include <stdio.h>
int factorial(int);
int recFactorial(int);
int main(){
int num;
printf("Enter non-negative integer to find factorial : ");
scanf("%d", &num);
if(num < 0)
printf("Factorial doesn't exists!\n");
else{
printf("Factorial Value\n");
printf("From Non-Recursive function : %d\n",
factorial(num));
printf("From Recursive function : %d\n",
recFactorial(num));
}
return 0;
}
int factorial(int num){
int fact=1;
for(; num>1; fact *= num, num--);
return fact;
}
int recFactorial(int num){
return(num > 1 ? num * recFactorial(num-1) : 1);
}

Output :

13
Enter non-negative integer to find factorial : 5
Factorial Value
From Non-Recursive function : 120
From Recursive function : 120

9. Do the following using pointers


i) Add two numbers
ii) Swap two numbers using user defined function

Objective: To understand the use of pointers in C.


Algorithm:
1. Declare variables num1 and num2 as int.
2. Read num1 and num2.
3. Call add(&num1, &num2).
4. Print value of num1 and num2 befoe
5. Call swap(&num1, &num2).
6. Print value of num1 and num2 after swapping.
7. STOP.
add(*num1, *num2)
1. Return *num1 + *num2.
swap(*num1, *num2)
1. Declare temp as int.
2. Assign temp = *num1.
3. *num1 = *num2
4. *num2 = temp.
Source Code :
#include <stdio.h>
int add(int *num1, int *num2);
void swap(int *num1, int *num2);
int main(){
int num1, num2;
printf("Enter numbers for swapping and adding\n");
printf("Enter num1 : ");
scanf("%d", &num1);
printf("Enter num2 : ");
scanf("%d", &num2);
printf("Addition result : %d\n", add(&num1, &num2));
printf("Before Swapping\n");
printf("num1 = %d, num2 = %d\n", num1, num2);
swap(&num1, &num2);
printf("After Swapping\n");

14
printf("num1 = %d, num2 = %d\n", num1, num2);
return 0;
}
int add(int *num1, int *num2){
return *num1 + *num2;
}
void swap(int *num1, int *num2){
int temp;
temp = *num1; *num1 = *num2; *num2 = temp;
}
Output :
Enter numbers for swapping and adding
Enter num1 : 20
Enter num2 : 40
Addition result : 60
Before Swapping
num1 = 20, num2 = 40
After Swapping
num1 = 40, num2 = 20

10. Construct binary search trees to perform insertion, deletion, and search.

Objective: To understand the construction and use of Binary Search Trees.


Algorithm:
1. Declare ‘struct NODE’ with fields:
I. struct NODE pointer left, right.
II. integer ‘data’
2. Declare a struct NODE pointer ‘root’, integer ‘ch’ and ‘data’.
3. Assign root = NULL in the beginning.
4. Repeat steps 5 to 6 infinitely till user exits:
5. Read ‘ch’.
6. Check ch:
I . if ch == 1 :
Read ‘data’. Call insert()
II. if ch == 2 :
Read ‘data’. Call delete()
III. if ch == 3 :
Read ‘data’. Call search()
IV. if ch == 4 :
call inorder()

15
V. Exit. Go to last step.
7. Exit
Insert(node, data)
1. If node == NULL : return a newnode with data as ‘data’
2. Otherwise if data < root->data : call insert(node->left, data).
3. Otherwise if data > root->data : call insert(node->right, data).
4. Exit
Delete(root, data)
1. If root === NULL : return ‘data not found’.
2. Otherwise if data < root->data : call delete(node->left, data)
3. Otherwise if data > root->data : call delete(node->right, data)
4. Otherwise if :
a.if root->left = NULL. struct NODE *temp = root->right. free(root). Return temp
b.if root->right = NULL. struct NODE *temp = root->left. free(root). Return temp
c.else temp = inorderSuccessor of root. Exchange the values of root and temp.
Delete inorder successor
Return root.
5. Exit
Search(root, data)
1. Repeat steps 2 to till root != NULL.
2. If data < root->data : root = root->left
3. Otherwise data > root->data : root->right
4. Otherwise print(“data found”)
5. Exit
Source Code :
#include <stdio.h>
#include <stdlib.h>
struct NODE{
struct NODE *left, *right;
int data;
};
struct NODE * insertNode(struct NODE *, int);
struct NODE * createNode(int);
int searchNode(struct NODE *, int);
void inorder(struct NODE *);
struct NODE * deleteNode(struct NODE *, int);
struct NODE * inorderSuccesor(struct NODE *);
int main(){
struct NODE *root;
int ch, data;

16
root = NULL;
while(1){
printf("\n1. Insert\n2. Delete\n3. Search\n4.
Display(Inorder Traversal)\n5. Exit");
printf("\nC H O O S E : ");
scanf("%d", &ch);
switch(ch){
case 1 :
printf("Enter the value to insert : ");
scanf("%d", &data);
root = insertNode(root, data);
printf("%d inserted...\n", data);
break;
case 2 :
if(root == NULL)
printf("Empty BST...\n");
else{
printf("Enter the data to delete : ");
scanf("%d", &data);
root = deleteNode(root, data);
}
break;
case 3 :
if(root == NULL)
printf("Empty BST...\n");
else{
printf("Enter the element to search : ");
scanf("%d", &data);
if(searchNode(root, data))
printf("%d found...\n", data);
else
printf("%d not found...\n", data);
}
break;
case 4 :
if(root == NULL)
printf("Empty BST...\n");
else{
printf("Inorder Traversal : ");
inorder(root);
printf("\n");
}
break;
case 5 : exit(0);
default : printf("\n! INVALID CHOICE !\n");
}}
return 0;

17
}
struct NODE * insertNode(struct NODE *root, int data){
if(root == NULL)
return(createNode(data));
if(data == root->data)
printf("Duplicate(%d) not allowed...\n", data);
if(data < root->data)
root->left = insertNode(root->left, data);
else if(data > root->data)
root->right = insertNode(root->right, data);
return root;
}
int searchNode(struct NODE *root, int data){
while(root != NULL){
if(data < root->data)
root = root->left;
else if(data > root->data)
root = root->right;
else
return 1;
}
return 0;
}
void inorder(struct NODE *root){
if(root != NULL) {
inorder(root->left);
printf("%d\t", root->data);
inorder(root->right);
}
}
struct NODE *createNode(int data){
struct NODE *newNode;
newNode = (struct NODE *) malloc(sizeof(struct NODE));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
struct NODE * inorderSuccessor(struct NODE * root){
if(root->left == NULL)
return root;
return (inorderSuccessor(root->left));
}
struct NODE * deleteNode(struct NODE *root, int data){
struct NODE *temp;
if(root == NULL)
printf("%d not found...\n", data);
else if(data < root->data)

18
root->left = deleteNode(root->left, data);
else if(data > root->data)
root->right = deleteNode(root->right, data);
else{
if(root->left == NULL){
temp = root->right;
free(root);
return temp;
}
else if(root->right == NULL){
temp = root->left;
free(root);
return temp;
}
else{
temp = inorderSuccessor(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
printf("%d deleted...\n", data);
}
return root;
}
Output :

1. Insert 1. Insert
2. Delete 2. Delete
3. Search 3. Search
4. Display(Inorder Traversal) 4. Display(Inorder Traversal)
5. Exit 5. Exit
C H O O S E : 1 C H O O S E : 4
Enter the value to insert : 50 Inorder Traversal : 5 25
50 inserted... 50 75 80

1. Insert 1. Insert
2. Delete 2. Delete
3. Search 3. Search
4. Display(Inorder Traversal) 4. Display(Inorder Traversal)
5. Exit 5. Exit
C H O O S E : 1 C H O O S E : 3
Enter the value to insert : 25 Enter the element to search :
25 inserted... 25
25 found...

19
1. Insert
2. Delete 1. Insert
3. Search 2. Delete
4. Display(Inorder Traversal) 3. Search
5. Exit 4. Display(Inorder Traversal)
C H O O S E : 1 5. Exit
Enter the value to insert : 75 C H O O S E : 2
75 inserted... Enter the data to delete : 25

1. Insert 1. Insert
2. Delete 2. Delete
3. Search 3. Search
4. Display(Inorder Traversal) 4. Display(Inorder Traversal)
5. Exit 5. Exit
C H O O S E : 1 C H O O S E : 4
Enter the value to insert : 5 Inorder Traversal : 5 50
5 inserted... 75 80

1. Insert 1. Insert
2. Delete 2. Delete
3. Search 3. Search
4. Display(Inorder Traversal) 4. Display(Inorder Traversal)
5. Exit 5. Exit
C H O O S E : 1 C H O O S E : 5
Enter the value to insert : 80
80 inserted...

11. Apply Queue and stack in Breadth First Search and Depth First Search
respectively

Objective: To understand the concepts of Queue, Stack, Breadth First Search and Depth
First Search
Algorithm:
1. Declare a struct NODE with fields data as integer, next as struct node *.
2. Create a stack, queue and a visited array.
3. Get the graph.
4. Apply bfs(). Apply dfs()
5. Exit.

20
dfs(graph, vertex v) :
1. If the vertex v is not visited print ‘v’.
2. Repeat steps 3 to 4 until all the adjacent vertex are not visited.
3. Explore the adjacent vertices to ‘v’.
4. If adjacent vertex is not visited : push ‘v’ in the stack.Call dfs(graph, adjacent
vertex)
5. If stack is not empty : dfs(pop the stack)
6. Exit
bfs(graph, vertex v) :
1. If the vertex v is not visited print ‘v’.
2. Repeat the steps 3 to 4 until all the adjacent vertices are not visited.
3. Explore the adjacent vertices to ‘v’.
4. If adjacent vertex is not visited : push ‘adjacent vertex’ to queue.
5. If queue is not empty apply bfs(dequeue())
6. Exit
Source Code :
#include <stdio.h>
#include <stdlib.h>
struct NODE{
int data;
struct NODE *next; };
struct NODE *top;
struct NODE *front, *rear;
void displayAdjMat(int **graph);
void dfs(int **graph, int);
void bfs(int **graph, int);
int n, *visited;
int main(){
int i, **graph, edge, vertex;
char ch;
printf("Enter no. of vertices : ");
scanf("%d", &n);
visited = (int *) calloc(n, sizeof(int));
graph = (int **) calloc(n, sizeof(int *));
for(i = 0; i<n; i++)
*(graph + i) = (int *) calloc(n, sizeof(int));
for(vertex = 0; vertex<n; vertex++){
printf("\nLink Vertex %d(y/n) : ", vertex);
scanf(" %c", &ch);
while((ch == 'y') || (ch == 'Y')){
do{
printf("Vertex no.(0 - %d) : ", n-1);
scanf("%d", &edge);

21
}while((edge<0) || (edge>=n));
graph[vertex][edge] = 1;
printf("Link More(y/n) : ");
scanf(" %c", &ch);
}
}
displayAdjMat(graph);
do{
for(i = 0; i<n; i++)
visited[i] = 0;
printf("Choose starting vertex for DFS : ");
scanf("%d", &vertex);
dfs(graph, vertex);
for(i = 0; i<n; i++)
visited[i] = 0;
printf("Choose starting vertex for BFS : ");
scanf("%d", &vertex);
bfs(graph, vertex);
printf("Traverse again(y/n) : ");
scanf(" %c", &ch);
} while (ch == 'y' || ch == 'Y');
return 0;
}
void displayAdjMat(int **graph){
int i, j;
printf("\n...Adjacency Matrix...\n");
for(i = 0; i<n; i++)
printf("\t%d", i);
printf("\n");
for(i = 0; i<n; i++){
printf("%d\t", i);
for(j = 0; j<n; j++)
printf("%d\t", graph[i][j]);
printf("\n");
}
}
void push(int data){
struct NODE * temp;
temp = (struct NODE *) malloc(sizeof(struct NODE));
temp->data = data;
temp->next = top;
top = temp;
}
int pop(){
struct NODE *temp;
int data;
if(top == NULL)

22
return -1;
data = top->data;
top = top->next;
return data;
}
void enqueue(int data){
struct NODE *temp;
temp = (struct NODE *) malloc(sizeof(struct NODE));
temp->data = data;
temp->next = NULL;
if(front == NULL)
front = rear = temp;
else{
rear->next = temp;
rear = temp;
}
}
int dequeue(){
int data;
if(front == NULL)
return -1;
data = front->data;
if(front == rear)
front = rear = NULL;
else
front = front->next;
return data;
}
void dfs(int **graph, int v){
int i, data;
if(visited[v] == 0){
printf("%d\t", v);
visited[v] = 1;
}
for(i = 0; i<n; i++){
if(graph[v][i] == 1 && visited[i] == 0){
visited[i] = 1;
printf("%d\t", i);
push(v);
dfs(graph, i);
}
}
data = pop();
if(data != -1)
dfs(graph, data);
}
void bfs(int **graph, int v){

23
int i, data;
if(visited[v] == 0){
visited[v] = 1;
printf("%d\t", v);
enqueue(v);
}
for(i = 0; i<n; i++){
if(graph[v][i] == 1 && visited[i] == 0) {
visited[i] = 1;
printf("%d\t", i);
enqueue(i);
}
}
data = dequeue();
if(data != -1)
bfs(graph, data);
}
Output :
Enter no. of vertices : 4

Link Vertex 0(y/n) : y


Vertex no.(0 - 3) : 3
Link More(y/n) : n

Link Vertex 1(y/n) : y


Vertex no.(0 - 3) : 3
Link More(y/n) : n

Link Vertex 2(y/n) : y


Vertex no.(0 - 3) : 3
Link More(y/n) : n

Link Vertex 3(y/n) : y


Vertex no.(0 - 3) : 0
Link More(y/n) : y
Vertex no.(0 - 3) : 1
Link More(y/n) : y
Vertex no.(0 - 3) : 2
Link More(y/n) : n

...Adjacency Matrix...
0 1 2 3
0 0 0 0 1

24
1 0 0 0 1
2 0 0 0 1
3 1 1 1 0
Choose starting vertex for DFS : 3
3 0 1 2
Choose starting vertex for BFS : 1
1 3 0 2
Traverse again(y/n) : n

12. Write a program to create a binary search tree and find the number of leaf
nodes

Objective: To understand the construction and use of binary search trees.


Algorithm:
1. Declare ‘struct NODE’ with fields:
I. struct NODE pointer left, right.
II. integer ‘data’
2. Declare a struct NODE pointer ‘root’, integer ‘ch’ and ‘data’.
3. Assign root = NULL in the beginning.
4. Repeat steps 5 to 6 infinitely till user exits:
5. Read ‘ch’.
6. Check ch:
I . if ch == 1 :
Read ‘data’. Call insert()
II. if ch == 2 :
Read ‘data’. Call delete()
III. if ch == 3 :
Read ‘data’. Call search()
IV. if ch == 4 :
call inorder()
V. Exit. Go to last step.
7. Exit
Insert(node, data)
1. If node == NULL : return a newnode with data as ‘data’
2. Otherwise if data < root->data : call insert(node->left, data).
3. Otherwise if data > root->data : call insert(node->right, data).
4. Exit
Delete(root, data)

25
1.
If root === NULL : return ‘data not found’.
2.
Otherwise if data < root->data : call delete(node->left, data)
3.
Otherwise if data > root->data : call delete(node->right, data)
4.
Otherwise if :
a.if root->left = NULL. struct NODE *temp = root->right. free(root). Return temp
b.if root->right = NULL. struct NODE *temp = root->left. free(root). Return temp
c.else temp = inorderSuccessor of root. Exchange the values of root and temp.
Delete inorder successor
Return root.
5. Exit
countLeafNode(root)
1. If root != NULL then proceed otherwise return
2. Call countLeafNode(root->left)
3. If root is a leaf node: Increment a counter
4. Call countLeafNode(root->right)
5. Return counter
Source Code :
#include <stdio.h>
#include <stdlib.h>
struct NODE{
struct NODE *left,*right;
int data;};
struct NODE * create(int);
struct NODE * insert(struct NODE *, int);
struct NODE * delete(struct NODE *, int);
struct NODE * inorderSuccessor(struct NODE *);
int search(struct NODE *, int);
int cntLeaf(struct NODE *);
void inorder(struct NODE *);
int cnt = 0;

int main()
{
struct NODE *root;
int ch, data;
root = NULL;
while(1){
printf("\n1. Insert\n2. Deletion\n3. Search\n4.
Display(Inorder Traversal)\n5. Count Leaf\n6. Exit\nC H O O S E
: ");
scanf("%d", &ch);
switch(ch){
case 1 :

26
printf("Enter data : ");
scanf("%d", &data);
root = insert(root, data);
printf("%d insertd...\n", data);
Break;
case 2 :
if(root == NULL)
printf("Empty BST...\n");
else{
printf("Enter data : ");
scanf("%d", &data);
root = delete(root, data);
}
break;
case 3 :
if(root == NULL)
printf("Empty BST...\n");
else{
printf("Enter the data to search : ");
scanf("%d", &data);
if(search(root, data))
printf("%d found...\n", data);
else
printf("%d not found...\n", data);
}
break;
case 4 :
printf("\nDisplay : ");
inorder(root);
break;
case 5 :
printf("No. of leaf node : %d\n",
cntLeaf(root));
case 6 : exit(0);
default : printf("\n! INVALID CHOICE !\n");
}
}
return 0;
}
struct NODE * create(int data){
struct NODE *newNode;
newNode = (struct NODE *) malloc(sizeof(struct NODE));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
struct NODE * insert(struct NODE *root, int data){

27
if(root == NULL)
return(create(data));
if(data < root->data)
root->left = insert(root->left, data);
else if(data > root->data)
root->right = insert(root->right, data);
return root;
}
void inorder(struct NODE *root){
if(root != NULL){
inorder(root->left);
printf("%d\t", root->data);
inorder(root->right);
}
}
struct NODE * delete(struct NODE *root, int data){
struct NODE *temp;
if(root == NULL)
printf("%d not found...\n", data);
else if(data == root->data){
if(root->left == NULL){
temp = root->right;
free(root);
return(temp);
}
else if(root->right == NULL){
temp = root->left;
free(root); return temp;
}
temp = inorderSuccessor(root->right);
root->data = temp->data;
root->right = delete(root->right, temp->data);
}
else if(data > root->data)
root->right = delete(root->right, data);
else
root->left = delete(root->left, data);
return root;
}
struct NODE * inorderSuccessor(struct NODE *root){
if(root->left == NULL)
return(root);
return(inorderSuccessor(root->left));
}
int cntLeaf(struct NODE *root){
if(root != NULL){
cntLeaf(root->left);

28
if(root->left == NULL && root->right == NULL)
cnt++;
cntLeaf(root->right);
}
return cnt;
}
int search(struct NODE * root, int data){
while(root != NULL){
if(data < root->data)
root = root->left;
else if(data > root->data)
root = root->right;
else
return 1;
}
return 0;
}
Output :

1. Insert
2. Deletion 1. Insert
3. Search 2. Deletion
4. Display(Inorder Traversal) 3. Search
5. Count Leaf 4. Display(Inorder Traversal)
6. Exit 5. Count Leaf
C H O O S E : 1 6. Exit
Enter data : 50 C H O O S E : 1
50 insertd... Enter data : 60
60 insertd...
1. Insert
2. Deletion 1. Insert
3. Search 2. Deletion
4. Display(Inorder Traversal) 3. Search
5. Count Leaf 4. Display(Inorder Traversal)
6. Exit 5. Count Leaf
C H O O S E : 1 6. Exit
Enter data : 20 C H O O S E : 1
20 insertd... Enter data : 70
70 insertd...
1. Insert
2. Deletion 1. Insert
3. Search 2. Deletion

29
4. Display(Inorder Traversal) 3. Search
5. Count Leaf 4. Display(Inorder Traversal)
6. Exit 5. Count Leaf
C H O O S E : 1 6. Exit
Enter data : 30 C H O O S E : 5
30 inserted... No. of leaf node : 2

13. Create a binary search tree with the following operations:


i)Insert a new node ii)Inorder traversal iii)Preorder traversal
iv)Postorder traversal v) Delete a node.

Objective: To understand the concepts of Queue, Stack, Breadth First Search and Depth
First Search .
Algorithm:
1. Declare ‘struct NODE’ with fields:
I. struct NODE pointer left, right.
II. integer ‘data’
2. Declare a struct NODE pointer ‘root’, integer ‘ch’ and ‘data’.
3. Assign root = NULL in the beginning.
4. Repeat steps 5 to 6 infinitely till user exits:
5. Read ‘ch’.
6. Check ch:
I . if ch == 1 :
Read ‘data’. Call insert()
II. if ch == 2 :
Read ‘data’. Call delete()
III. if ch == 3 :
Read ‘data’. Call search()
IV. if ch == 4 :
call inorder()
V. Exit. Go to last step.
7. Exit
Insert(node, data)
1. If node == NULL : return a newnode with data as ‘data’
2. Otherwise if data < root->data : call insert(node->left, data).
3. Otherwise if data > root->data : call insert(node->right, data).
4. Exit

30
Delete(root, data)
1. If root === NULL : return ‘data not found’.
2. Otherwise if data < root->data : call delete(node->left, data)
3. Otherwise if data > root->data : call delete(node->right, data)
4. Otherwise if :
a.if root->left = NULL. struct NODE *temp = root->right. free(root). Return temp
b.if root->right = NULL. struct NODE *temp = root->left. free(root). Return temp
c.else temp = inorderSuccessor of root. Exchange the values of root and temp.
Delete inorder successor
Return root.
5. Exit
Preorder(root)
1. If root != NULL then proceed otherwise return
2. Print root -> data.
3. Call preorder(root->left)
4. Call preorder(root->right)
5. Return.
Inorder(root)
1. If root != NULL then proceed otherwise return
2. Call inorder(root->left)
3. Print root->data.
4. Call inorder(root->right)
5. Return.
Postorder(root)
1. If root != NULL then proceed otherwise return
2. Call postorder(root->left)
3. Call postorder(root->right)
4. Print root->data
5. Return.
Source Code :
#include <stdio.h>
#include <stdlib.h>
struct NODE
{
struct NODE *left, *right;;
int data; };
struct NODE * insert(struct NODE *root, int);
struct NODE * delete(struct NODE *root, int);
struct NODE * inorderSuccessor(struct NODE *root);

31
void preorder(struct NODE *);
void inorder(struct NODE *);
void postorder(struct NODE *);
struct NODE * createNode(int);
int main(){
struct NODE *root;
int ch, data;
root = NULL;
while(1){
printf("\n1. Insert\n2. Delete\n3. Display\n4. Exit\nC H
O O S E : ");
scanf("%d", &ch);
switch(ch) {
case 1 :
printf("Enter data to insert : ");
scanf("%d", &data);
root = insert(root, data);
break;
case 2 :
if(root == NULL)
printf("Empty BST...\n");
else{
printf("Enter data to delete : ");
scanf("%d", &data);
root = delete(root, data);
}break;
case 3 :
if(root == NULL)
printf("Empty BST...\n");
else{
printf("\nPreorder : ");
preorder(root);
printf("\nInorder : ");
inorder(root);
printf("\nPostorder : ");
postorder(root);
}
break;
case 4 : exit(0);
default : printf("! INVALID CHOICE !\n");
}
}return 0;
}
struct NODE * insert(struct NODE *root, int data){
if(root == NULL)
return(createNode(data));
if(data == root->data)

32
printf("Duplicate %d not allowed\n", data);
else if(data < root->data)
root->left = insert(root->left, data);
else
root->right = insert(root->right, data);
return root;
}

struct NODE * createNode(int data){


struct NODE *newNode;
newNode = (struct NODE *) malloc(sizeof(struct NODE));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
struct NODE * delete(struct NODE *root, int data){
struct NODE *temp;
if(data < root->data)
root->left = delete(root->left, data);
else if(data > root->data)
root->right = delete(root->right, data);
else{
if(data == root->data){
if(root->left == NULL){
temp = root->right;
free(root);
return temp;
}
else if(root->right == NULL){
temp = root->left;
free(root);
return temp;
}
else{
temp = inorderSuccessor(root->right);
root->data = temp->data;
root->right = delete(root->right, data);
}}
}
return root;
}
struct NODE *inorderSuccessor(struct NODE *root){
if(root->left == NULL)
return root;
return (inorderSuccessor(root->left));
}
void preorder(struct NODE *root){

33
if(root != NULL){
printf("%d\t", root->data);
preorder(root->left);
preorder(root->right);
}
}
void inorder(struct NODE *root){
if(root != NULL){
inorder(root->left);
printf("%d\t", root->data);
inorder(root->right);
}
}
void postorder(struct NODE *root){
if(root != NULL)
{
postorder(root->left);
postorder(root->right);
printf("%d\t", root->data);
}
}
Output :

1. Insert
2. Delete 3. Display
3. Display 4. Exit
4. Exit C H O O S E : 3
C H O O S E : 1
Enter data to insert : 50 Preorder : 50 20 40
70 90
1. Insert Inorder : 20 40 50
2. Delete 70 90
3. Display Postorder : 40 20 90
4. Exit 70 50
C H O O S E : 1 1. Insert
Enter data to insert : 20 2. Delete
3. Display
1. Insert 4. Exit
2. Delete C H O O S E : 2
3. Display Enter data to delete : 50
4. Exit
C H O O S E : 1 1. Insert
Enter data to insert : 70 2. Delete

34
3. Display
1. Insert 4. Exit
2. Delete C H O O S E : 3
3. Display
4. Exit Preorder : 70 20 40
C H O O S E : 1 90
Enter data to insert : 40 Inorder : 20 40 70
1. Insert 90
2. Delete Postorder : 40 20 90
3. Display 70
4. Exit 1. Insert
C H O O S E : 1 2. Delete
Enter data to insert : 90 3. Display
4. Exit
1. Insert C H O O S E : 4
2. Delete

14. Design, develop, and execute a program in C to create a max heap and perform
the following operations :
i)Insertion ii)Deletion iii)Print Largest Value

Objective: To understand and develop max heap using heap.


Algorithm:
1. Declare ‘heap’ as an array of integers.
2. Repeat steps 3 to till user exits
3. Read ch.
4. If ch == 1: call insert() to construct the heap
5. Otherwise if ch == 2 : insert a new element to the heap.
6. Otherwise if ch == 3 : call displayHeap()
7. Otherwise if ch == 4 : call deleteHeap()
8. Otherwise if ch == 5 : exit the program
9. Exit
insert()
1. Read all the elements in an array.
2. Assign i = sizeof(heap)/2
3. Repeat steps 4 to 5 till i>0
4. Apply heapify(i)

35
5. Decrement i
6. Exit
delete()
1. If size of array = 0 print “Heap empty” and go to the last step
2. Otherwise Replace the root element with the last leaf node and delete the last
index.
3. Apply heapify(1) on the first index
heapify()
1. Check if the root node is greater than the left and right child.
2. If not, exchange with the child, and apply heapify() on the position where you
exchanged from.
Source Code :
#include <stdio.h>
#include <stdlib.h>
int t_size = 1, u_size = 0;
void displayHeap(int *);
int * insert(int *, int);
void heapify(int *, int);
int main(){
int *heap, data, i, ch, rootIndex, childIndex, temp;
char c;
while(1){
printf("\n1. Create Heap\n2. Insert\n3. Display\n4.
Delete\n5. Print Largest Value\n6. Exit\nC H O O S E : ");
scanf(" %d", &ch);
switch(ch){
case 1 :
do{
printf("Enter data : ");
scanf("%d", &data);
heap = insert(heap, data);

printf("Insert more(y/n) : ");


scanf(" %c", &c);
} while (c == 'y' || c == 'Y');
for(i = u_size/2; i>0; i--)
heapify(heap, i);
break;
case 2 :
t_size++; u_size++;
if(u_size == 1)
heap = (int *) calloc(t_size, sizeof(int));
else

36
heap = (int *) realloc(heap, t_size *
sizeof(int));
printf("Enter data to insert : ");
scanf("%d", &data);
heap[u_size] = data;
childIndex = u_size;
rootIndex = u_size/2;
while(heap[childIndex] > heap[rootIndex] &&
rootIndex > 0){
temp = heap[childIndex];
heap[childIndex] = heap[rootIndex];
heap[rootIndex] = temp;
childIndex /= 2;
rootIndex /= 2;
}
break;
case 3 :
displayHeap(heap);
break;
case 4 :
if(u_size == 0)
printf("Heap empty...\n");
else{
data = heap[1];
heap[1] = heap[u_size];
t_size--; u_size--;
heap = (int *) realloc(heap, t_size *
sizeof(int));
if(heap != NULL)
heapify(heap, 1);
printf("%d deleted...\n", data);
}
break;
case 5 :
if(u_size == 0)
printf("Heap Empty...\n");
else{printf("Largest value : %d\n", heap[1]);}
break;
case 6 : exit(0);
default : printf("! INVALID CHOICE !\n");
} }
return 0;
}
void displayHeap(int *heap){
int i;
printf("INDEX : ");
for(i = 0; i<t_size; i++)

37
printf("%d\t", i);
printf("\nVALUE : ");
for(i = 0; i<t_size; i++)
printf("%d\t", heap[i]);
printf("\n");
}
int * insert(int *heap, int data){
u_size++; t_size++;
if(u_size == 1)
heap = (int *) calloc(t_size, sizeof(int));
else
heap = (int *) realloc(heap, t_size * sizeof(int));
*(heap + u_size) = data;
return heap;
}
void heapify(int *heap, int index){
int lchild, rchild, largestIndex, temp;
lchild = 2*index; rchild = 2*index + 1;
largestIndex = index;
if(lchild <= u_size && heap[lchild] > heap[index])
largestIndex = lchild;
if(rchild <= u_size && heap[rchild] > heap[largestIndex])
largestIndex = rchild;
if(largestIndex != index){
temp = heap[index];
heap[index] = heap[largestIndex];
heap[largestIndex] = temp;
heapify(heap, largestIndex);
}
}
Output :

1. Create Heap 1. Create Heap


2. Insert 2. Insert
3. Display 3. Display
4. Delete 4. Delete
5. Print Largest Value 5. Print Largest Value
6. Exit 6. Exit
C H O O S E : 1 C H O O S E : 3
Enter data : 50 INDEX : 0 1 2
Insert more(y/n) : y 3 4 5 6
Enter data : 30 VALUE : 0 100 90
Insert more(y/n) : y 70 30 50 20
Enter data : 20

38
Insert more(y/n) : y 1. Create Heap
Enter data : 100 2. Insert
Insert more(y/n) : y 3. Display
Enter data : 90 4. Delete
Insert more(y/n) : n 5. Print Largest Value
6. Exit
1. Create Heap C H O O S E : 4
2. Insert 100 deleted...
3. Display
4. Delete 1. Create Heap
5. Print Largest Value 2. Insert
6. Exit 3. Display
C H O O S E : 3 4. Delete
INDEX : 0 1 2 5. Print Largest Value
3 4 5 6. Exit
VALUE : 0 100 90 C H O O S E : 5
20 30 50 Largest value : 90

1. Create Heap 1. Create Heap


2. Insert 2. Insert
3. Display 3. Display
4. Delete 4. Delete
5. Print Largest Value 5. Print Largest Value
6. Exit 6. Exit
C H O O S E : 2 C H O O S E : 6
Enter data to insert : 70

15. Write a program to implement Depth First Search (DFS) graph traversal
methods.

Objective: To understand DFS traversal.


Algorithm:
1. Declare a struct NODE with fields data as integer, next as struct node *.
2. Create a stack and a visited array.
3. Get the graph.
4. Apply dfs()
5. Exit.
dfs(graph, vertex v)

39
1. If the vertex v is not visited print ‘v’.
2. Repeat steps 3 to 4 until all the adjacent vertex are not visited.
3. Explore the adjacent vertices to ‘v’.
4. If adjacent vertex is not visited : push ‘v’ in the stack.Call dfs(graph, adjacent
vertex)
5. If stack is not empty : dfs(pop the stack)
6. Exit

Source Code :
#include <stdio.h>
#include <stdlib.h>
struct NODE{
int data;
struct NODE *next; };
struct NODE *top = NULL;
int *visited;
void push(int);
int pop();
struct NODE * createNode(int);
int searchNode(struct NODE *, int);
void dispAdjList(struct NODE **, int);
void dfs(struct NODE **, int);
int main(){
struct NODE **adjList, *curr;
int n, i, vertex, found;
char ch;
printf("Enter no. of vertices : ");
scanf("%d", &n);
visited = (int *) calloc(n, sizeof(int));
adjList = (struct NODE **) calloc(n, sizeof(struct NODE *));
for(i = 0; i<n; i++)
adjList[i] = NULL;
for(i = 0; i<n; i++){
printf("\nLink node %d (y/n) : ", i);
scanf(" %c", &ch);
while(ch == 'y' || ch == 'Y'){
do{
printf("Node no.(0-%d) : ", n-1);
scanf("%d", &vertex);
} while (vertex < 0 || vertex >= n);
if(adjList[i] == NULL)
adjList[i] = createNode(vertex);
else{
found = searchNode(adjList[i], vertex);
if(!found){

40
curr = adjList[i];
while(curr->next != NULL)
curr = curr->next;
curr->next = createNode(vertex);
}
else
printf("Already linked...\n");
}
printf("Link More(y/n) : ");
scanf(" %c", &ch);
}}
printf("\nDisplaying adjList\n");
dispAdjList(adjList, n);
do{
for(i = 0; i<n; i++)
visited[i] = 0;
printf("Choose starting vertex for DFS : ");
scanf("%d", &vertex);
dfs(adjList, vertex);
printf("\nTraverse it again(y/n) : ");
scanf(" %c", &ch);
} while (ch == 'y' || ch == 'Y');
return 0;
}
struct NODE * createNode(int data){
struct NODE *newNode;
newNode = (struct NODE *) malloc(sizeof(struct NODE));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void dispAdjList(struct NODE **adjList, int n){
int i;
struct NODE *curr;
for(i = 0; i<n; i++){
printf("%d : ", i);
curr = adjList[i];
while(curr != NULL){
printf("%d => ", curr->data);
curr = curr->next;
} printf(" N");
printf("\n");
}
}
int searchNode(struct NODE * node, int data){
if(node == NULL)
return 0;

41
else{
while(node != NULL){
if(node->data == data)
return 1;
node = node->next;
}
return 0;
}
}
void push(int n){
struct NODE * temp;
temp = createNode(n);
temp->next = top;
top = temp;
}
int pop(){
int data = -1;
if(top != NULL){
data = top->data;
top = top->next;
}
return data;
}
void dfs(struct NODE **adjList, int v){
struct NODE *vertex;
int n;
if(visited[v] == 0){
printf("%d => ", v);
visited[v] = 1;
}
vertex = adjList[v];
while(vertex != NULL){
n = vertex->data;
if(visited[n] == 0){
push(v);
dfs(adjList, n);
}
vertex = vertex->next;
}
v = pop();
if(v != -1)
dfs(adjList, v);
}
Output :
Enter no. of vertices : 4

Link node 0 (y/n) : y

42
Node no.(0-3) : 3
Link More(y/n) : n

Link node 1 (y/n) : y


Node no.(0-3) : 3
Link More(y/n) : n

Link node 2 (y/n) : y


Node no.(0-3) : 3
Link More(y/n) : n

Link node 3 (y/n) : y


Node no.(0-3) : 0
Link More(y/n) : y
Node no.(0-3) : 1
Link More(y/n) : y
Node no.(0-3) : 2
Link More(y/n) : n

Displaying adjList
0 : 3 => N
1 : 3 => N
2 : 3 => N
3 : 0 => 1 => 2 => N
Choose starting vertex for DFS : 3
3 => 0 => 1 => 2 =>
Traverse it again(y/n) : n

16. Write a program to implement Depth First Search (BFS) graph traversal
methods.

Objective: To understand BFS traversal.


Algorithm:
1. Declare a struct NODE with fields data as integer, next as struct node *.
2. Create a stack and a visited array.
3. Get the graph.
4. Apply bfs()
5. Exit.
bfs(graph, vertex v)
1. If the vertex v is not visited print ‘v’.

43
2. Repeat the steps 3 to 4 until all the adjacent vertices are not visited.
3. Explore the adjacent vertices to ‘v’.
4. If adjacent vertex is not visited : push ‘adjacent vertex’ to queue.
5. If queue is not empty apply bfs(dequeue())
6. Exit
Source Code :
#include <stdio.h>
#include <stdlib.h>
struct NODE{
int data;
struct NODE *next;
};
struct NODE *front = NULL, *rear = NULL;
int n, *visited;
void enqueue(int);
int dequeue();
struct NODE * createNode(int);
int searchNode(struct NODE *, int);
void insertNode(struct NODE *, int);
void bfs(struct NODE **, int);
int main(){
struct NODE **adjList, *curr;
int i, vertex, v;
char ch;
printf("Enter no. of vertices : ");
scanf("%d", &n);
adjList = (struct NODE **) calloc(n, sizeof(struct NODE *));
for(i = 0; i<n; i++)
adjList[i] = NULL;
visited = (int *) calloc(n, sizeof(int));
for(vertex = 0; vertex < n; vertex++){
printf("Want to link %d (y/n) : ", vertex);
scanf(" %c", &ch);
while(ch == 'y' || ch == 'Y'){
do{ printf("Link with(0 - %d) : ", n-1);
scanf("%d", &v);
} while (v < 0 || v >= n);
if(adjList[vertex] == NULL)
adjList[vertex] = createNode(v);
else{
if(searchNode(adjList[vertex], v) == -1)
insertNode(adjList[vertex], v);
else
printf("Duplicate(%d) not allowed...\n", v);
}
printf("Link More(y/n) : ");

44
scanf(" %c", &ch);
}
}
for(i = 0; i<n; i++){
printf("%d : ", i);
curr = adjList[i];
while(curr != NULL){
printf("%d -> ", curr->data);
curr = curr->next;
}
printf("N\n");
}
do{
for(i = 0; i<n; i++)
visited[i] = 0;
printf("Enter a vertex to start BFS : ");
scanf("%d", &v);
bfs(adjList, v);
printf("N");
printf("\nPerform BFS again(y/n) : ");
scanf(" %c", &ch);
} while (ch == 'y' || ch == 'Y');
return 0;
}
void enqueue(int data){
struct NODE * newNode;
newNode = createNode(data);
if(front == NULL)
front = rear = newNode;
else{
rear->next = newNode;
rear = newNode;
}
}
int dequeue(){
int data;
if(front == NULL)
return -1;
data = front->data;
if(front == rear)
front = rear = NULL;
else
front = front->next;
return data;
}
struct NODE * createNode(int data){
struct NODE * temp;

45
temp = (struct NODE *) malloc(sizeof(struct NODE));
temp->data = data;
temp->next = NULL;
return temp;
}
int searchNode(struct NODE * node, int data){
while(node != NULL){
if(node->data == data)
return 1;
node = node->next;
}
return -1;
}
void insertNode(struct NODE * node, int data){
while(node->next != NULL)
node = node->next;
node->next = createNode(data);
}
void bfs(struct NODE **adjList, int v){
struct NODE *curr;
if(visited[v] == 0){
visited[v] = 1;
printf("%d -> ", v);
}
curr = adjList[v];
while(curr != NULL){
if(visited[curr->data] == 0){
printf("%d -> ", curr->data);
visited[curr->data] = 1;
enqueue(curr->data);
}
curr = curr->next;
}
v = dequeue();
if(v != -1)
bfs(adjList, v);
}
Output :
Enter no. of vertices : 4
Want to link 0 (y/n) : y
Link with(0 - 3) : 3
Link More(y/n) : n
Want to link 1 (y/n) : y
Link with(0 - 3) : 3
Link More(y/n) : n
Want to link 2 (y/n) : y

46
Link with(0 - 3) : 3
Link More(y/n) : n
Want to link 3 (y/n) : y
Link with(0 - 3) : 0
Link More(y/n) : y
Link with(0 - 3) : 1
Link More(y/n) : y
Link with(0 - 3) : 2
Link More(y/n) : n
0 : 3 -> N
1 : 3 -> N
2 : 3 -> N
3 : 0 -> 1 -> 2 -> N
Enter a vertex to start BFS : 0
0 -> 3 -> 1 -> 2 -> N
Perform BFS again(y/n) : n

17. Create a text file containing the name, height, weight of the students in a class.
Perform Quick sort and Merge sort on this data and store the resultant data in two
separate files. Also write the time taken by the two sorting methods into the
respective files.
Sony Mathew 5.5 60 Arun Sajeev 5.7 58 Rajesh Kumar 6.1 70

Objective:
To understand data files and file handling in C. Helps to understand sorting in
files.

Algorithm:
1. Files :
2. Open file1.txt and file2.txt with “a+”(append and read) option, so that the
previous content of the file is not deleted. If files don’t exist, they will be
created.
3. Explicitly write a newline (“\n”) to the destination file to enhance readability.
4. Write content from source file to destination file.
5. Display the contents in file2.txt to console (stdout).
Quick sort :
1. Pick an element, called a pivot, from the array.
2. Partition the array into two halves, the left side of the array containing
3. Elements less than the pivot element, and the right side of the array containing

47
elements greater than the pivot element.
4. Recursively sort the left side of the array and the right side of the array.
5. Return the array.
Merge sort :
1: Start
2: Declare an array and left, right, mid variable
3: Perform merge function.
mergesort(array,left,right)
mergesort (array, left, right)
if left > right
return
else
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
4: Stop
Source Code :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int partition(int, int);
void quickSort(int, int);
struct stud{
char name[20];
float hgt, wgt;
}s[10];

struct Name{
char st_name[10];
}
name[10], copy[10];
void quickSort(int low, int high){
int pIndex;
if (low<high){
pIndex = partition(low, high);
quickSort(low, pIndex-1);
quickSort(pIndex+1, high);
}

48
}
int partition(int low, int high){
char pivot[10], temp[10];
int i, j;
strcpy(pivot, name[low].st_name);
i = low; j = high;
while(i<j){
while(strcmp(name[i].st_name, pivot) == 0 ||
strcmp(name[i].st_name, pivot) == -1)
i++;
while(strcmp(name[j].st_name, pivot) == 1)
j--;
if(i<j){
strcpy(temp, name[i].st_name);
strcpy(name[i].st_name, name[j].st_name);
strcpy(name[j].st_name, temp);
}
}
strcpy(temp, name[j].st_name);
strcpy(name[j].st_name, name[low].st_name);
strcpy(name[low].st_name, temp);
return j;
}
void merge(int l, int m, int r){
int i, j, k;
int n1 = m - l + 1, n2 = r - m;
struct Name L[10], R[10];
for (i = 0; i < n1; i++)
strcpy(L[i].st_name,name[l + i].st_name);
for (j = 0; j < n2; j++)
strcpy(R[j].st_name, name[m + 1 + j].st_name);
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2) {
if (strcmp(L[i].st_name,R[j].st_name) == -1) {
strcpy(name[k].st_name, L[i].st_name);
i++;
}
else {
strcpy(name[k].st_name, R[j].st_name);

49
j++;
}
k++;
}
while (i < n1) {
strcpy(name[k].st_name, L[i].st_name);
i++;
k++;
}
while (j < n2) {
strcpy(name[k].st_name, R[j].st_name);
j++;
k++;
}
}
void mergeSort(int l, int r){
int m;
if (l < r) {
m = l + (r - l) / 2;
mergeSort(l, m); mergeSort(m + 1, r); merge(l, m, r);
}
}

int main(){
FILE *fp;
int i,n, k;
char c, str[100];
fp = fopen("student.txt", "w");
printf("Enter record of student:\n\n");
printf("Enter no. of entries : ");
scanf("%d", &n);
for(i = 0; i<n; i++){
printf("\nEnter name of %d th student: ",i+1);
scanf(" %s", s[i].name);
fprintf(fp, "%s ",s[i].name);
}
fprintf(fp, "\n");
for(i = 0; i<n; i++){
printf("\nEnter height of %d th student: ",i+1);
scanf(" %f", &s[i].hgt);
fprintf(fp, "%f ",s[i].hgt);

50
}
fprintf(fp, "\n");
for(i = 0; i<n; i++){
printf("\nEnter weight of %d th student: ",i+1);
scanf(" %f", &s[i].wgt);
fprintf(fp, "%f ",s[i].wgt);
}
printf("\nRecord stored in file...\n");
fclose(fp);

// ======Performing Quick sort on student.txt======

fp = fopen("student.txt", "r");
i = 0; k = 0;
while((c = getc(fp)) != '\n'){
if (c == ' '){
str[i] = '\0';
strcpy(name[k].st_name, str);
i = 0;
k++;
}
else{
str[i] = c; i++;
}
}
fclose(fp);
fp = fopen("student.txt", "r");
while((c = getc(fp)) != EOF)
printf("%c", c);
fclose(fp);
quickSort(0, n-1);
printf("\n");
for(i = 0; i<n; i++)
printf("%s\t", name[i].st_name);
fp = fopen("quickSortFile.txt", "w");
for(i = 0; i<n; i++)
fprintf(fp, "%s\t", name[i].st_name);
fclose(fp);
printf("\n…Quicksort writing is done\n");

// ======Performing Merge sort on student.txt======

51
fp = fopen("student.txt", "r");
i = 0;
k = 0;
while((c = getc(fp)) != '\n'){
if (c == ' '){
str[i] = '\0';
strcpy(name[k].st_name, str);
i = 0;
k++;
}
else{
str[i] = c;
i++;
}
}
fclose(fp);
mergeSort(0,n- 1);
printf("\n");
for(i = 0; i<n; i++)
printf("%s\t", name[i].st_name);
fp = fopen("mergedSortFile.txt", "w");
for(i = 0; i<n; i++)
fprintf(fp, "%s\t", name[i].st_name);
fclose(fp);
printf("\n…Mergesort writing is done\n");
return 0;
}
Output :
Enter record of student:
Enter no. of entries : 3
Enter name of 1 th student: mohan
Enter name of 2 th student: radhika
Enter name of 3 th student: keshava
Enter height of 1 th student: 151.23
Enter height of 2 th student: 155
Enter height of 3 th student: 160.15
Enter weight of 1 th student: 50
Enter weight of 2 th student: 45
Enter weight of 3 th student: 55

52
Record stored in file...
mohan radhika keshava
151.229996 155.000000 160.149994
50.000000 45.000000 55.000000
keshava mohan radhika …Quicksort writing is done
keshava mohan radhika …Mergesort writing is done

18. Write a program to sort a set of numbers using Heap sort and find a particular
number from the sorted set using Binary Search.

Objective: To understand Heapsort and Binary Search


Algorithm:
1. Declare ‘heap’ as an array of integers.
2. Repeat steps 3 to till user exits
3. Read ch.
4. If ch == 1: call insert() to construct the heap
5. Otherwise if ch == 2 : call displayHeap().
6. Otherwise if ch == 3 : call heapSort().
7. Otherwise if ch == 4 : binarySearch()
8. Otherwise if ch == 5 : exit the program
9. Exit
Insert(data)
1. Read all the elements in an array.
2. Assign i = sizeof(heap)/2
3. Repeat steps 4 to 5 till i>0
4. Apply heapify(i)
5. Decrement i
6. Exit
Delete(data)
1. If size of array = 0 print “Heap empty” and go to the last step
2. Otherwise Replace the root element with the last leaf node and delete the last
index.
3. Apply heapify(1) on the first index
Heapify(index)

53
1. Check if the root node is greater than the left and right child.
2. If not, exchange with the child, and apply heapify() on the position where you
exchanged from.
HeapSort()
1. Declare an array ‘sortedArray’.
2. Continuously apply delete() on the heap and store the deleted element in the
‘sortedArray’, till the heap becomes empty.
BinarySearch(data, low, high)
1. Repeat steps 2 to 5 till low<=high
2. Assign mid = (low+high) /2
3. If data < arr[mid] : low = mid+1
4. Otherwise if data > arr[mid] : high = mid-1
5. Otherwise print ‘data found at the respective position’ and return
6. Print ‘data not found’
7. Exit
Source Code :
#include <stdio.h>
#include <stdlib.h>
int t_size = 1, u_size = 0;
int array_size;
void displayHeap(int *);
int * insert(int *, int);
void heapify(int *, int);
void binarySearch(int *, int);
int main(){
int *heap, *sortedArray, i, ch, rootIndex, childIndex, temp,
data;
char c;
while(1){
printf("\n1. Create Heap\n2. Display\n3. Heap Sort\n4.
Binary Search\n5. Exit\nC H O O S E : ");
scanf(" %d", &ch);
switch(ch){
case 1 :
do{
printf("Enter data : ");
scanf("%d", &data);
heap = insert(heap, data);

printf("Insert more(y/n) : ");


scanf(" %c", &c);
} while (c == 'y' || c == 'Y');
for(i = u_size/2; i>0; i--)

54
heapify(heap, i);
break;
case 2 :
displayHeap(heap);
break;
case 3 :
if(u_size == 0)
printf("Heap empty...\n");
else{
sortedArray = (int *) calloc(u_size,
sizeof(int));
array_size = u_size;
for(i = 0; i<array_size; i++){
sortedArray[i] = heap[1];
heap[1] = heap[u_size];
t_size--; u_size--;
heap = (int *) realloc(heap, t_size *
sizeof(int));
if(heap != NULL)
heapify(heap, 1);
}
}
printf("\nSorted Array : ");
for(i = 0; i<array_size; i++)
printf("%d\t", sortedArray[i]);
break;
case 4 :
if(heap == NULL)
printf("Empty Heap...\n");
else{
do{
printf("Size of the array : %d\n",
array_size);
printf("Enter the data to search : ");
scanf("%d", &data);
binarySearch(sortedArray, data);
printf("Want to search again(y/n) : ");
scanf(" %c", &ch);
} while (ch == 'y' || ch == 'Y');
}
case 5 : exit(0);
default : printf("! INVALID CHOICE !\n"); }
}
return 0;
}
void displayHeap(int *heap){
int i;

55
printf("INDEX : ");
for(i = 0; i<t_size; i++)
printf("%d\t", i);
printf("\nVALUE : ");
for(i = 0; i<t_size; i++)
printf("%d\t", heap[i]);
printf("\n");
}
int * insert(int *heap, int data){
u_size++; t_size++;
if(u_size == 1)
heap = (int *) calloc(t_size, sizeof(int));
else
heap = (int *) realloc(heap, t_size * sizeof(int));
*(heap + u_size) = data;
return heap;
}
void heapify(int *heap, int index){
int lchild, rchild, largestIndex, temp;
lchild = 2*index; rchild = 2*index + 1;
largestIndex = index;
if(lchild <= u_size && heap[lchild] > heap[index])
largestIndex = lchild;
if(rchild <= u_size && heap[rchild] > heap[largestIndex])
largestIndex = rchild;
if(largestIndex != index){
temp = heap[index];
heap[index] = heap[largestIndex];
heap[largestIndex] = temp;
heapify(heap, largestIndex); }

}
void binarySearch(int *arr, int elem){
int low, high, mid;
low = 0; high = array_size-1;
while(low <= high){
mid = (low+high)/2;
if(elem < arr[mid])
low = mid+1;
else if(elem > arr[mid])
high = mid - 1;
else{
printf("Element %d found at position %d.\n", elem,
mid+1);
break;
}}
if(low > high)

56
printf("Element %d not found...\n", elem);
}
Output :

1. Create Heap
2. Display 1. Create Heap
3. Heap Sort 2. Display
4. Binary Search 3. Heap Sort
5. Exit 4. Binary Search
C H O O S E : 1 5. Exit
Enter data : 50 C H O O S E : 3
Insert more(y/n) : y
Enter data : 20 Sorted Array : 200 100
Insert more(y/n) : y 90 50 20
Enter data : 100 1. Create Heap
Insert more(y/n) : y 2. Display
Enter data : 90 3. Heap Sort
Insert more(y/n) : y 4. Binary Search
Enter data : 200 5. Exit
Insert more(y/n) : n C H O O S E : 4
Size of the array : 5
1. Create Heap Enter the data to search : 90
2. Display Element 90 found at position 3.
3. Heap Sort Want to search again(y/n) : n
4. Binary Search
5. Exit
C H O O S E : 2
INDEX : 0 1 2
3 4 5
VALUE : 0 200 90
100 50 20

19. Implement a Hash table using Chaining method. Let the size of hash table be 10
so that the index varies from 0 to 9.

Objective: To understand Hash tables using chaining method

Algorithm:

57
1.
Declare a structure NODE with fields int ‘data’, struct NODE * left, *right.
2.
Declare ‘hashTable’ as an array of pointers to struct NODE.
3.
Read the elements.
4.
Hash the element to the respective position in the hashtable using function hash(x)
= x%10.
5. Read the ‘elem’ to be searched. Generate the key and search the element in the
hashtable.
6. Read the ‘elem’ to be dropped. Generate the key and delete the element in the
hashtable.
Source Code :
#include <stdio.h>
#include <stdlib.h>
#define HASH(x) x%n
struct NODE {
int data;
struct NODE *next;
};
int main(){
struct NODE **hashTable, *temp, *curr, *prev;
int ch, n, i, num, key, elemCnt;
printf("Size of the HashTable : ");
scanf("%d", &n);
hashTable = (struct NODE **) calloc(n, sizeof(struct NODE
*));
for(i = 0; i<n; i++)
*(hashTable + i) = NULL;
elemCnt = 0;
while(1)
{
printf("\nHASH TABLE MENU \n");
printf("1. Insert\n2. Remove\n3. Display\n4.
DisplaySize\n5. Exit\nC H O O S E : ");
scanf("%d", &ch);
switch(ch){
case 1 :
printf("Enter data : ");
scanf("%d", &num);
temp = (struct NODE *) calloc(1, sizeof(struct
NODE));
temp->data = num;
temp->next = NULL;
key = HASH(num);
if(*(hashTable + key) == NULL)
*(hashTable + key) = temp;

58
else{
curr = *(hashTable + key);
while(curr->next != NULL)
curr = curr->next;

curr->next = temp;
}
printf("%d successfully hashed...\n", num);
elemCnt++;
break;
case 2 :
printf("Element to remove : ");
scanf("%d", &num);
key = HASH(num);
curr = *(hashTable + key);
while(curr != NULL){
if(curr->data == num){
temp = curr;
if(curr == *(hashTable + key))
*(hashTable + key) = curr->next;
else
prev->next = curr->next;
free(curr);
printf("%d removed ...\n", num);
break;
}
prev = curr;
curr = curr->next;
}
if(curr == NULL)
printf("! Value not found !\n");
break;
case 3 :
for(i = 0; i<n; i++){
printf("%d : ", i);
curr = *(hashTable + i);
while(curr != NULL){
printf("%d -> ", curr->data);
curr = curr->next;
}
printf("N\n");
}
break;
case 4 : printf("Element Count : %d\n", elemCnt);
break;
case 5 : exit(0);
default : printf("\n! INVALID CHOICE !");

59
} }
return 0;
}
Output :

Size of the HashTable : 10


HASH TABLE MENU
HASH TABLE MENU 1. Insert
1. Insert 2. Remove
2. Remove 3. Display
3. Display 4. DisplaySize
4. DisplaySize 5. Exit
5. Exit C H O O S E : 3
C H O O S E : 1 0 : 20 -> 30 -> N
Enter data : 20 1 : N
20 successfully hashed... 2 : N
3 : N
HASH TABLE MENU 4 : N
1. Insert 5 : 5 -> 45 -> N
2. Remove 6 : N
3. Display 7 : N
4. DisplaySize 8 : 8 -> N
5. Exit 9 : N
C H O O S E : 1
Enter data : 30 HASH TABLE MENU
30 successfully hashed... 1. Insert
2. Remove
HASH TABLE MENU 3. Display
1. Insert 4. DisplaySize
2. Remove 5. Exit
3. Display C H O O S E : 2
4. DisplaySize Element to remove : 30
5. Exit 30 removed ...
C H O O S E : 1
Enter data : 5 HASH TABLE MENU
5 successfully hashed... 1. Insert
2. Remove
HASH TABLE MENU 3. Display
1. Insert 4. DisplaySize
2. Remove 5. Exit

60
3. Display C H O O S E : 3
4. DisplaySize 0 : 20 -> N
5. Exit 1 : N
C H O O S E : 1 2 : N
Enter data : 45 3 : N
45 successfully hashed... 4 : N
5 : 5 -> 45 -> N
HASH TABLE MENU 6 : N
1. Insert 7 : N
2. Remove 8 : 8 -> N
3. Display 9 : N
4. DisplaySize
5. Exit HASH TABLE MENU
C H O O S E : 1 1. Insert
Enter data : 8 2. Remove
8 successfully hashed... 3. Display
4. DisplaySize
5. Exit
C H O O S E : 5

20. Implement a Hash table that uses Linear Probing for collision resolution.

Objective: To implement Hash table using linear probing.


Algorithm:
1. Create an array of structure (i.e a hash table).
2. Take a key and a value to be stored in hash table as input.
3. Corresponding to the key, an index will be generated i.e every key is stored in a
particular array index.
4. Using the generated index, access the data located in that array index.
5. In case of absence of data, create one and insert the data item (key and value) into
it and increment the size of hash table.
6. In case the data exists, probe through the subsequent elements (looping back if
necessary) for free space to insert new data item. Note: This probing will continue
until we reach the same element again (from where we began probing)
7. To display all the elements of hash table, element at each index is accessed (via for
loop).
8. To remove a key from hash table, we will first calculate its index and delete it if
key matches, else probe through elements until we find key or an empty space

61
where not a single data has been entered (means data does not exist in the hash
table).
9. Exit
Source Code :
#include <stdio.h>
#include <stdlib.h>
struct item{
int key;
int value;
};
struct hashtable_item{
int flag;
struct item *data;
};
struct hashtable_item *array;
int size = 0;
int max = 10;
void init_array(){
int i;
for (i = 0; i < max; i++){
array[i].flag = 0;
array[i].data = NULL;
}
}
int hashcode(int key){
return (key % max);
}
void insert(int key, int value){
int index = hashcode(key);
int i = index;
struct item *new_item = (struct item *)malloc(sizeof(struct
item));
new_item->key = key;
new_item->value = value;
while (array[i].flag == 1){
if (array[i].data->key == key){
printf("\n Key already exists, hence updating its
value \n");
array[i].data->value = value;
return;
}

62
i = (i + 1) % max;
if (i == index){
printf("\n Hash table is full, cannot insert any
more item \n");
return;
}
}
array[i].flag = 1;
array[i].data = new_item;
size++;
printf("\n Key (%d) has been inserted \n", key);
}
void remove_element(int key){
int index = hashcode(key);
int i = index;
while (array[i].flag != 0){
if (array[i].flag == 1 && array[i].data->key == key){
array[i].flag = 2;
array[i].data = NULL;
size--;
printf("\n Key (%d) has been removed \n", key);
return;
}
i = (i + 1) % max;
if (i == index)
{
break;
}
}
printf("\n This key does not exist \n");
}
void display(){
int i;
for (i = 0; i < max; i++){
struct item *current = (struct item *)array[i].data;
if (current == NULL){
printf("\n Array[%d] has no elements \n", i);
}
else{
printf("\n Array[%d] has elements -: \n %d (key) and
%d(value) ", i, current->key, current->value);

63
}
}
}
int size_of_hashtable(){return size;}
int main(){
int choice, key, value, n, c;
array = (struct hashtable_item *)malloc(max * sizeof(struct
hashtable_item));
init_array();
do{
printf("Implementation of Hash Table in C with Linear
Probing \n\n");
printf("MENU-: \n1.Inserting item in the Hashtable"
"\n2.Removing item from the Hashtable"
"\n3.Check the size of Hashtable"
"\n4.Display Hashtable"
"\n\n Please enter your choice-:");
scanf("%d", &choice);
switch (choice){
case 1:
printf("Inserting element in Hashtable\n");
printf("Enter key and value-:\t");
scanf("%d %d", &key, &value);
insert(key, value);
break;
case 2:
printf("Deleting in Hashtable \n Enter the key to
delete-:");
scanf("%d", &key);
remove_element(key);
break;
case 3:
n = size_of_hashtable();
printf("Size of Hashtable is-:%d\n", n);
break;
case 4:
display();
break;
default:
printf("Wrong Input\n");
}

64
printf("\n Do you want to continue-:(press 1 for
yes)\t");
scanf("%d", &c);
} while (c == 1);

return 0;
}
Output :

Implementation of Hash Table in MENU-:


C with Linear Probing 1.Inserting item in the
Hashtable
MENU-: 2.Removing item from the
1.Inserting item in the Hashtable
Hashtable 3.Check the size of Hashtable
2.Removing item from the 4.Display Hashtable
Hashtable
3.Check the size of Hashtable Please enter your choice-:4
4.Display Hashtable
Array[0] has elements -:
Please enter your choice-:1 10 (key) and 20(value)
Inserting element in Hashtable Array[1] has no elements
Enter key and value-: 15 25
Array[2] has no elements
Key (15) has been inserted
Array[3] has no elements
Do you want to continue-
:(press 1 for yes) 1 Array[4] has no elements
Implementation of Hash Table in
C with Linear Probing Array[5] has elements -:
15 (key) and 25(value)
MENU-: Array[6] has no elements
1.Inserting item in the
Hashtable Array[7] has no elements
2.Removing item from the
Hashtable Array[8] has no elements
3.Check the size of Hashtable
4.Display Hashtable Array[9] has elements -:
29 (key) and 39(value)
Please enter your choice-:1 Do you want to continue-
Inserting element in Hashtable :(press 1 for yes) 1
Enter key and value-: 10 20 Implementation of Hash Table in
C with Linear Probing
Key (10) has been inserted
MENU-:

65
Do you want to continue- 1.Inserting item in the
:(press 1 for yes) 1 Hashtable
Implementation of Hash Table in 2.Removing item from the
C with Linear Probing Hashtable
3.Check the size of Hashtable
MENU-: 4.Display Hashtable
1.Inserting item in the
Hashtable Please enter your choice-:2
2.Removing item from the Deleting in Hashtable
Hashtable Enter the key to delete-:29
3.Check the size of Hashtable
4.Display Hashtable Key (29) has been removed

Please enter your choice-:1 Do you want to continue-


Inserting element in Hashtable :(press 1 for yes) 0
Enter key and value-: 29 39

Key (29) has been inserted

Do you want to continue-


:(press 1 for yes) 1
Implementation of Hash Table in
C with Linear Probing

66

You might also like