0% found this document useful (0 votes)
39 views62 pages

Ds Lab Manual

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

Ds Lab Manual

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

I MCA.

I SEM Regulation: R24

Laboratory Manual

For the course of

DATA STRUCTURES USING C


Branch: MASTER OF COMPUTER
APPLICATIONS

DEPARTMENT OF MASTER OF
COMPUTER APPLICATIONS
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY KAKINADA
(Established by Govt. of A.P., ACT No.30 of 2008)
KAKINADA – 533 003 (A.P) INDIA
MCA COURSE STRUCTURE & SYLLABUS
(Applicable for batches admitted from 2024
2024-25)
MCA I Semester L T P C
0 0 4 2
DATA STRUCTURES USING C LAB

Course Objectives:
This Course will enable students to
• Design and implement various data structures.
• Implement operations like searching, insertion, and deletion, traversing
mechanism
• Develop applications using data structure algorithms.

Experiment 1:
a) Write a program in C to display the n terms of even natural numbers and
their sum.
b) Write a program in C to display the n terms of harmonic series and their
sum. 1 + 1/2 + 1/3 + 1/4 + 1/5 ... 1/n terms.
c) Write a C program to check whether a given number is an Armstrong
number or not
d) Write a C program to calculate the factorial of a given number.

Experiment 2:
a) Write a program in C for multiplication of two square Matrices.
b) Write a program in C to find the transpose of a given matrix.

Experiment 3:
a) Write a program in C to check whether a number is a prime number or not
using the function.
b) Write a recursive program which computes the nth Fibonacci number, for
appropriate values of n.
c) Write a program in C to add numbers using call by reference.

Experiment 4:
a) Write a program in C to append multiple lines at the end of a text file.
b) Write a program in C to copy a file in another name

Experiment 5:
Write recursive program for the following
a) Write recursive and non recursive C program for calculation of Factorial of an
integer.
b) Write recursive and non recursive C program for calculation of GCD (n, m)
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY KAKINADA
(Established by Govt. of A.P., ACT No.30 of 2008)
KAKINADA – 533 003 (A.P) INDIA
MCA COURSE STRUCTURE & SYLLABUS
(Applicable for batches admitted from 2024
2024-25)
c) Write recursive and non recursive C program for Towers of Hanoi: N disks
are to be transferred from peg S to peg D with Peg I as the intermediate
peg.

Experiment 6:
a) Write a C program that uses both recursive and non recursive functions to
perform Linear search for a Key value in a given list.
b) Write a C program that uses both recursive and non recursive functions to
perform Binary search for a Key value in a given list.

Experiment 7:
a) Write a C program that implements stack (its operations) using
using arrays.
b) Write a C program that implements stack (its operations) using Linked list.

Experiment 8:
a) Write a C program that uses Stack operations to convert infix expressions into
postfix expressions.
a) Write a C program that implements Queue (its operations) using arrays.
b) Write a C program that implements Queue (its operations) using linked lists.

Experiment 9:
Write a C program that uses functions to create a singly linked list and perform
various operations on it.

Experiment 10:
Write a C program to store a polynomial expression in memory using a linked list and
perform polynomial addition.

Experiment 11:
a) Write a recursive C program for traversing a binary tree in preorder, in order and
post order.
b) Write a non recursive C program for traversing a binary tree in preorder, in order
and post order.

Experiment 12:
Implementation of Hash table using double hashing as collision resolution function.

Experiment 13:
Implementation of Binary Search trees-
trees Insertion and deletion..
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY KAKINADA
(Established by Govt. of A.P., ACT No.30 of 2008)
KAKINADA – 533 003 (A.P) INDIA
MCA COURSE STRUCTURE & SYLLABUS
(Applicable for batches admitted from 2024
2024-25)
Experiment 14:
Implementation of AVL Tree – Insertion and Deletion
Experiment 15:
a) Write a C program that implements Bubble sort, to sort a given list of integers in
ascending order.
b) Write a C program that implements Quick sort, to sort a given list of integers in
ascending order.
c) Write C program that implement Merge sort, to sort a given list of integers in
ascending order

Web resources:
1. https://ds1-iiith.vlabs.ac.in/
iiith.vlabs.ac.in/
2. https://profile.iiita.ac.in/bibhas.ghoshal/teaching_ds_lab.html
3. https://moodle.sit.ac.in/blog/data
https://moodle.sit.ac.in/blog/data-structures-laboratory/
4. https://dsalab.netlify.app/
5. https://www.vtuloop.com/data
https://www.vtuloop.com/data-structure-lab-programs-all/
DATA STRUCTURES USING C LAB

Experiment 1
a) Write a program in C to display the n terms of even natural numbers and their
sum.
Program:
#include <stdio.h>
int main() {
int n, sum = 0,even_num=0;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("The even natural numbers are: ");
for(int i = 0; i <n; i++) {
even_num+= 2;
printf("%d ", even_num);
sum += even_num;
}
printf("\nThe sum of the even natural numbers is: %d", sum);
return 0;
}
Output:
Enter the number of terms: 12
The even natural numbers are: 2 4 6 8 10 12 14 16 18 20 22 24
The sum of the even natural numbers is: 156

b) Write a program in C to display the n terms of harmonic series and their sum. 1 +
1/2 + 1/3 + 1/4 + 1/5 ... 1/n terms.
Program:
#include <stdio.h>
int main() {
int n;
float sum = 0.0;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("The harmonic series is: ");
for(int i = 1; i <= n; i++) {
float term = (float)1 / i;
printf("%f ", term);
sum += term;
}
printf("\nThe sum of the harmonic series is: %f\n", sum);
return 0;
}
Output:
Enter the number of terms: 10
The harmonic series is: 1.000000 0.500000 0.333333 0.250000 0.200000 0.166667
0.142857 0.125000 0.111111 0.100000
The sum of the harmonic series is: 2.928968

c) Write a C program to check whether a given number is an Armstrong number or


not.
Program:
#include <stdio.h>
int main() {
int num, original_num, sum = 0;
printf("Enter a number: ");
scanf("%d", &num);
original_num = num;
while(num != 0) {
int digit = num % 10;
sum += digit * digit * digit;
num /= 10;
}
if(sum == original_num) {
printf("%d is an Armstrong number.", original_num);
} else {
printf("%d is not an Armstrong number.", original_num);
}
return 0;
}
Output:
Enter a number: 407
407 is an Armstrong number.

d) Write a C program to calculate the factorial of a given number.


Program:
#include <stdio.h>
int main() {
int num, factorial = 1;
printf("Enter a number: ");
scanf("%d", &num);
for(int i = 1; i <= num; i++) {
factorial *= i;
}
printf("The factorial of %d is: %d", num, factorial);
return 0;
}
Output:
Enter a number: 5
The factorial of 5 is: 120

Experiment 2
a) Write a program in C for multiplication of two square Matrices.
Program:
#include <stdio.h>
#define SIZE 3 // size of the square matrix
void multiply_matrices(int matrix1[SIZE][SIZE], int matrix2[SIZE][SIZE], int
result[SIZE][SIZE]) {
for(int i = 0; i < SIZE; i++) {
for(int j = 0; j < SIZE; j++) {
result[i][j] = 0;
for(int k = 0; k < SIZE; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
}
void print_matrix(int matrix[SIZE][SIZE]) {
for(int i = 0; i < SIZE; i++) {
for(int j = 0; j < SIZE; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int matrix1[SIZE][SIZE], matrix2[SIZE][SIZE], result[SIZE][SIZE];
printf("Enter elements of matrix 1:\n");
for(int i = 0; i < SIZE; i++) {
for(int j = 0; j < SIZE; j++) {
scanf("%d", &matrix1[i][j]);
}
}
printf("Enter elements of matrix 2:\n");
for(int i = 0; i < SIZE; i++) {
for(int j = 0; j < SIZE; j++) {
scanf("%d", &matrix2[i][j]);
}
}
multiply_matrices(matrix1, matrix2, result);
printf("Matrix 1:\n");
print_matrix(matrix1);
printf("Matrix 2:\n");
print_matrix(matrix2);
printf("Resultant Matrix:\n");
print_matrix(result);
return 0;
}
Output:
Enter elements of matrix 1:
234456789
Enter elements of matrix 2:
234456789
Matrix 1:
234
456
789
Matrix 2:
234
456
789
Resultant Matrix:
44 53 62
70 85 100
109 133 157

b) Write a program in C to find the transpose of a given matrix.


Program:
#include <stdio.h>
#define ROWS 3
#define COLS 3
void print_matrix(int matrix[ROWS][COLS]) {
for(int i = 0; i < ROWS; i++) {
for(int j = 0; j < COLS; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
void find_transpose(int matrix[ROWS][COLS], int transpose[COLS][ROWS]) {
for(int i = 0; i < ROWS; i++) {
for(int j = 0; j < COLS; j++) {
transpose[j][i] = matrix[i][j];
}
}
}
int main() {
int matrix[ROWS][COLS], transpose[COLS][ROWS];

printf("Enter elements of matrix:\n");


for(int i = 0; i < ROWS; i++) {
for(int j = 0; j < COLS; j++) {
scanf("%d", &matrix[i][j]);
}
}
find_transpose(matrix, transpose);
printf("Original Matrix:\n");
print_matrix(matrix);
printf("Transpose Matrix:\n");
print_matrix(transpose);
return 0;
}
Output:
Enter elements of matrix:
123456789
Original Matrix:
123
456
789
Transpose Matrix:
147
258
369

Experiment 3
a) Write a program in C to check whether a number is a prime number or not using
the function.
Program:
#include <stdio.h>
int is_prime(int num) {
if(num <= 1) {
return 0;
}
for(int i = 2; i<= num/2; i++) {
if(num % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(is_prime(num)) {
printf("%d is a prime number.", num);
} else {
printf("%d is not a prime number.", num);
}
return 0;
}
Output:
Enter a number: 23
23 is a prime number.

b) Write a recursive program which computes the nth Fibonacci number, for
appropriate values of n.
Program:
#include <stdio.h>
int fibonacci(int n) {
if(n == 0 || n == 1) {
return n;
}
return fibonacci(n-1) + fibonacci(n-2);
}
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("The %dth Fibonacci number is: %d\n", n, fibonacci(n));
return 0;
}
Output:
Enter a positive integer: 10
The 10th Fibonacci number is: 55

c) Write a program in C to add numbers using call by reference.


Program:
#include <stdio.h>
void add_numbers(int *a, int *b, int *result) {
*result = *a + *b;
}
int main() {
int a, b, result;
printf("Enter the first number: ");
scanf("%d", &a);
printf("Enter the second number: ");
scanf("%d", &b);
add_numbers(&a, &b, &result);
printf("The sum of the two numbers is: %d\n", result);
return 0;
}
Output:
Enter the first number: 10
Enter the second number: 20
The sum of the two numbers is: 30

Experiment 4
a) Write a program in C to append multiple lines at the end of a text file.
Program:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file;
char line[256];
char filename[100];
int i, numLines;
printf("Enter the filename to append to: ");
scanf("%s", filename);
file = fopen(filename, "a");
if (file == NULL) {
perror("Error opening file");
return EXIT_FAILURE;
}
printf("How many lines do you want to append? ");
scanf("%d", &numLines);
getchar(); // To consume the newline character left by scanf
for (i = 0; i < numLines; i++) {
printf("Enter line %d: ", i + 1);
fgets(line, sizeof(line), stdin);
fprintf(file, "%s", line);
}
fclose(file);
printf("Lines appended successfully.");
return EXIT_SUCCESS;
}
Output:
Enter the filename to append to: test.txt
How many lines do you want to append? 4
Enter line 1: hello
Enter line 2: hai
Enter line 3: this is
Enter line 4: test code
Lines appended successfully.
b) Write a program in C to copy a file in another name
Program:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *sourceFile, *destFile;
char sourceFilename[100], destFilename[100];
char ch;
printf("Enter the source filename: ");
scanf("%s", sourceFilename);
printf("Enter the destination filename: ");
scanf("%s", destFilename);
sourceFile = fopen(sourceFilename, "r");
if (sourceFile == NULL) {
perror("Error opening source file");
return EXIT_FAILURE;
}
destFile = fopen(destFilename, "w");
if (destFile == NULL) {
perror("Error opening destination file");
fclose(sourceFile);
return EXIT_FAILURE;
}
while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, destFile);
}
fclose(sourceFile);
fclose(destFile);
printf("File copied successfully.\n");
return EXIT_SUCCESS;
}

Output:
Enter the source filename: ochote.txt
Enter the destination filename: Test.txt
File copied successfully.

Experiment 5
Write recursive program for the following
a) Write recursive and non recursive C program for calculation of Factorial of an
integer.
Recursive Progaram:
#include <stdio.h>
unsigned long long factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
printf("Factorial of %d = %llu\n", num, factorial(num));
}
return 0;
}
Output:
Enter a positive integer: 5
Factorial of 5 = 120

Non Recursive Program:


#include <stdio.h>
unsigned long long factorial(int n) {
unsigned long long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
int main() {
int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
printf("Factorial of %d = %llu\n", num, factorial(num));
}
return 0;
}
Output:
Enter a positive integer: 5
Factorial of 5 = 120

b) Write recursive and non recursive C program for calculation of GCD (n, m).
Recursive Program:
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
int main() {
int num1, num2;
printf("Enter two positive integers: ");
scanf("%d %d", &num1, &num2);
printf("GCD of %d and %d = %d", num1, num2, gcd(num1, num2));
return 0;
}
Output:
Enter two positive integers: 55 65
GCD of 55 and 65 = 5

Non Recursive Program:


#include <stdio.h>
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
int num1, num2;
printf("Enter two positive integers: ");
scanf("%d %d", &num1, &num2);
printf("GCD of %d and %d = %d\n", num1, num2, gcd(num1, num2));
return 0;
}
Output:
Enter two positive integers: 66 69
GCD of 66 and 69 = 3

c) Write recursive and non recursive C program for Towers of Hanoi: N disks are to
be transferred from peg S to peg D with Peg I as the intermediate peg.
Recursive Program:
#include <stdio.h>
void towersOfHanoi(int n, char source, char destination, char auxiliary) {
if (n == 1) {
printf("Move disk 1 from peg %c to peg %c\n", source, destination);
return;
}
towersOfHanoi(n - 1, source, auxiliary, destination);
printf("Move disk %d from peg %c to peg %c\n", n, source, destination);
towersOfHanoi(n - 1, auxiliary, destination, source);
}
int main() {
int num;
printf("Enter the number of disks: ");
scanf("%d", &num);
towersOfHanoi(num, 'A', 'C', 'B'); // A, B and C are names of rods
return 0;
}
Output:
Enter the number of disks: 3
Move disk 1 from peg A to peg C
Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C

Non Recursive Program:


#include <stdio.h>
#include <math.h>
void moveDisk(char from_rod, char to_rod) {
printf("Move disk from peg %c to peg %c\n", from_rod, to_rod);
}
void towersOfHanoiIterative(int num) {
int totalMoves = pow(2, num) - 1;
char source = 'A', destination = 'C', auxiliary = 'B';
for (int i = 1; i <= totalMoves; i++) {
char from_rod = (i % 3 == 1) ? source : (i % 3 == 2) ? auxiliary : destination;
char to_rod = (i % 3 == 1) ? destination : (i % 3 == 2) ? source : auxiliary;
moveDisk(from_rod, to_rod);
}
}
int main() {
int num;
printf("Enter the number of disks: ");
scanf("%d", &num);
towersOfHanoiIterative(num);
return 0;
}
Output:
Enter the number of disks: 4
Move disk from peg A to peg C
Move disk from peg B to peg A
Move disk from peg C to peg B
Move disk from peg A to peg C
Move disk from peg B to peg A
Move disk from peg C to peg B
Move disk from peg A to peg C
Move disk from peg B to peg A
Move disk from peg C to peg B
Move disk from peg A to peg C
Move disk from peg B to peg A
Move disk from peg C to peg B
Move disk from peg A to peg C
Move disk from peg B to peg A
Move disk from peg C to peg B

Experiment 6
a) Write a C program that uses both recursive and non recursive functions to perform
Linear search for a Key value in a given list.
Recursive Program:
#include <stdio.h>
int linearSearchRecursive(int arr[], int n, int key, int index) {
if (index >= n) {
return -1;
}
if (arr[index] == key) {
return index;
}
return linearSearchRecursive(arr, n, key, index + 1);
}
int main() {
int arr[100], n, key, pos, i;
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the elements of the array: ");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the key to search: ");
scanf("%d", &key);
pos = linearSearchRecursive(arr, n, key, 0);
if (pos >= 0) {
printf("Element found at position %d\n", pos + 1);
} else {
printf("Element not found in the array\n");
}
return 0;
}
Output:
Enter the size of the array: 5
Enter the elements of the array: 1 2 3 4 5
Enter the key to search: 5
Element found at position 5

Non Recursive Program:


#include <stdio.h>
int linearSearch(int arr[], int n, int key) {
int i;
for (i = 0; i < n; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
int main() {
int arr[100], n, key, pos, i;
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the elements of the array: ");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the key to search: ");
scanf("%d", &key);
pos = linearSearch(arr, n, key);
if (pos >= 0) {
printf("Element found at position %d\n", pos + 1);
} else {
printf("Element not found in the array\n");
}
return 0;
}
Output:
Enter the size of the array: 4
Enter the elements of the array: 4 5 7 8
Enter the key to search: 5
Element found at position 2

b) Write a C program that uses both recursive and non recursive functions to perform
Binary search for a Key value in a given list.
Recursive Program:
#include<stdio.h>
int binarySearchRecursive(int arr[], int left, int right, int key) {
if (right >= left) {
int mid = left + (right - left) / 2;
if (arr[mid] == key) {
return mid; // Key found
}
if (arr[mid] > key) {
return binarySearchRecursive(arr, left, mid - 1, key);
}
return binarySearchRecursive(arr, mid + 1, right, key);
}
return -1; // Key not found
}
int main() {
int arr[100], n, key, pos, i;
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the elements of the array: ");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the key to search: ");
scanf("%d", &key);
pos = binarySearchRecursive(arr,0,n,key);
if (pos >= 0) {
printf("Element found at position %d\n", pos + 1);
} else {
printf("Element not found in the array\n");
}
return 0;
}
Output:
Enter the size of the array: 5
Enter the elements of the array: 2 3 4 5 6
Enter the key to search: 3
Element found at position 2

Non Recursive:
#include<stdio.h>
int binarySearchIterative(int arr[], int size, int key) {
int left = 0;
int right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == key) {
return mid;
}
if (arr[mid] > key) {
right = mid - 1;
}

else {
left = mid + 1;
}
}
return -1;
}
int main() {
int arr[100], n, key, pos, i;
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the elements of the array: ");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the key to search: ");
scanf("%d", &key);
pos = binarySearchIterative(arr,n,key);
if (pos >= 0) {
printf("Element found at position %d\n", pos + 1);
} else {
printf("Element not found in the array\n");
}
return 0;
}
Output:
Enter the size of the array: 6
Enter the elements of the array: 3 4 5 6 7 8
Enter the key to search: 6
Element found at position 4

Experiment 7
a) Write a C program that implements stack (its operations) using arrays.
Program:
#include <stdio.h>
#define MAX_SIZE 100
int top = -1;
int stack[MAX_SIZE];
void push(int element) {
if (top == MAX_SIZE - 1) {
printf("Stack Overflow\n");
return;
}
stack[++top] = element;
}
int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack[top--];
}
int peek() {
if (top == -1) {
printf("Stack is empty\n");
return -1;
}
return stack[top];
}
void display() {
int i;
if (top == -1) {
printf("Stack is empty\n");
return;
}
printf("Stack elements: ");
for (i = 0; i <= top; i++) {
printf("%d ", stack[i]);
}
printf("\n");
}
int main() {
int choice, element;
while (1) {
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Display\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the element to push: ");
scanf("%d", &element);
push(element);
break;
case 2:
element = pop();
if (element != -1) {
printf("Popped element: %d\n", element);
}
break;
case 3:
element = peek();
if (element != -1) {
printf("Top element: %d\n", element);
}
break;
case 4:
display();
break;
case 5:
return 0;
default:
printf("Invalid choice\n");
}
}
return 0;
}
Output:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter the element to push: 100
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter the element to push: 200
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter the element to push: 300
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 3
Top element: 300
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 2
Popped element: 300
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 3
Top element: 200
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 4
Stack elements: 100 200
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter the element to push: 500
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 4
Stack elements: 100 200 500
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 5

b) Write a C program that implements stack (its operations) using Linked list.
Program:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* top = NULL;
void push(int element) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = element;
newNode->next = top;
top = newNode;
}
int pop() {
if (top == NULL) {
printf("Stack Underflow\n");
return -1;
}
int element = top->data;
Node* temp = top;
top = top->next;
free(temp);
return element;
}
int peek() {
if (top == NULL) {
printf("Stack is empty\n");
return -1;
}
return top->data;
}
void display() {
Node* temp = top;
if (temp == NULL) {
printf("Stack is empty\n");
return;
}
printf("Stack elements: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
int choice, element;
while (1) {
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Display\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the element to push: ");
scanf("%d", &element);
push(element);
break;
case 2:
element = pop();
if (element != -1) {
printf("Popped element: %d\n", element);
}
break;
case 3:
element = peek();
if (element != -1) {
printf("Top element: %d\n", element);
}
break;
case 4:
display();
break;
case 5:
return 0;
default:
printf("Invalid choice\n");
}
}
return 0;
}
Output:
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter the element to push: 100
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 1
Enter the element to push: 200
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 4
Stack elements: 100 200
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 3
Top element: 200
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 2
Popped element: 200
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 4
Stack elements: 100
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter your choice: 5

Experiment 8
a) Write a C program that uses Stack operations to convert infix expressions into
postfix expressions.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct Stack {
char data[MAX_SIZE];
int top;
} Stack;
void initStack(Stack* stack) {
stack->top = -1;
}
int isEmpty(Stack* stack) {
return stack->top == -1;
}
int isFull(Stack* stack) {
return stack->top == MAX_SIZE - 1;
}
void push(Stack* stack, char element) {
if (isFull(stack)) {
printf("Stack Overflow\n");
return;
}
stack->data[++stack->top] = element;
}
char pop(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack Underflow\n");
return -1;
}
return stack->data[stack->top--];
}
char peek(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return -1;
}
return stack->data[stack->top];
}
int precedence(char operator) {
if (operator == '+' || operator == '-') {
return 1;
} else if (operator == '*' || operator == '/') {
return 2;
} else {
return 0;
}
}
void infixToPostfix(char infix[], char postfix[]) {
Stack stack;
initStack(&stack);
int i, j = 0;
for (i = 0; i < strlen(infix); i++) {
if (infix[i] == ' ') {
continue;
} else if (infix[i] == '(') {
push(&stack, infix[i]);
} else if (infix[i] == ')') {
while (!isEmpty(&stack) && peek(&stack) != '(') {
postfix[j++] = pop(&stack);
}
if (isEmpty(&stack)) {
printf("Invalid infix expression\n");
return;
}
pop(&stack);
} else if (infix[i] == '+' || infix[i] == '-' || infix[i] == '*' || infix[i] == '/') {
while (!isEmpty(&stack) && peek(&stack) != '(' && precedence(infix[i]) <=
precedence(peek(&stack))) {
postfix[j++] = pop(&stack);
}
push(&stack, infix[i]);
} else {
postfix[j++] = infix[i];
}
}
while (!isEmpty(&stack)) {
postfix[j++] = pop(&stack);
}
postfix[j] = '\0';
}
int main() {
char infix[100], postfix[100];
printf("Enter the infix expression: ");
scanf("%s", infix);
infixToPostfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
return 0;
}
Output:
Enter the infix expression: A+B*C+D
Postfix expression: ABC*+D+

b) Write a C program that implements Queue (its operations) using arrays.


Program:
#include <stdio.h>
#define MAX_SIZE 100
typedef struct Queue {
int data[MAX_SIZE];
int front;
int rear;
} Queue;
void initQueue(Queue* queue) {
queue->front = queue->rear = -1;
}
int isEmpty(Queue* queue) {
return queue->front == -1;
}
int isFull(Queue* queue) {
return queue->rear == MAX_SIZE - 1;
}
void enqueue(Queue* queue, int element) {
if (isFull(queue)) {
printf("Queue is full\n");
return;
}
if (isEmpty(queue)) {
queue->front = queue->rear = 0;
} else {
queue->rear++;
}
queue->data[queue->rear] = element;
}
int dequeue(Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty\n");
return -1;
}
int element = queue->data[queue->front];
if (queue->front == queue->rear) {
queue->front = queue->rear = -1;
} else {
queue->front++;
}
return element;
}
int front(Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty\n");
return -1;
}
return queue->data[queue->front];
}
void display(Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty\n");
return;
}
printf("Queue elements: ");
for (int i = queue->front; i <= queue->rear; i++) {
printf("%d ", queue->data[i]);
}
printf("\n");
}
int main() {
Queue queue;
initQueue(&queue);
int choice, element;
while (1) {
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Front\n");
printf("4. Display\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the element to enqueue: ");
scanf("%d", &element);
enqueue(&queue, element);
break;
case 2:
element = dequeue(&queue);
if (element != -1) {
printf("Dequeued element: %d\n", element);
}
break;
case 3:
element = front(&queue);
if (element != -1) {
printf("Front element: %d\n", element);
}
break;
case 4:
display(&queue);
break;
case 5:
return 0;
default:
printf("Invalid choice\n");
}
}
return 0;
}
Output:
1. Enqueue
2. Dequeue
3. Front
4. Display
5. Exit
Enter your choice: 1
Enter the element to enqueue: 100
1. Enqueue
2. Dequeue
3. Front
4. Display
5. Exit
Enter your choice: 1
Enter the element to enqueue: 200
1. Enqueue
2. Dequeue
3. Front
4. Display
5. Exit
Enter your choice: 2
Dequeued element: 100
1. Enqueue
2. Dequeue
3. Front
4. Display
5. Exit
Enter your choice: 3
Front element: 200
1. Enqueue
2. Dequeue
3. Front
4. Display
5. Exit
Enter your choice: 4
Queue elements: 200
1. Enqueue
2. Dequeue
3. Front
4. Display
5. Exit
Enter your choice: 5

c)Write a C program that implements Queue (its operations) using linked lists.
Program:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct Queue {
Node* front;
Node* rear;
} Queue;
void initQueue(Queue* queue) {
queue->front = queue->rear = NULL;
}
int isEmpty(Queue* queue) {
return queue->front == NULL;
}
void enqueue(Queue* queue, int element) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = element;
newNode->next = NULL;
if (isEmpty(queue)) {
queue->front = queue->rear = newNode;
} else {
queue->rear->next = newNode;
queue->rear = newNode;
}
}
int dequeue(Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty\n");
return -1;
}
int element = queue->front->data;
Node* temp = queue->front;
queue->front = queue->front->next;
if (queue->front == NULL) {
queue->rear = NULL;
}
free(temp);
return element;
}
int front(Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty\n");
return -1;
}
return queue->front->data;
}
void display(Queue* queue) {
Node* temp = queue->front;
if (isEmpty(queue)) {
printf("Queue is empty\n");
return;
}
printf("Queue elements: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
Queue queue;
initQueue(&queue);
int choice, element;
while (1) {
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Front\n");
printf("4. Display\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the element to enqueue: ");
scanf("%d", &element);
enqueue(&queue, element);
break;
case 2:
element = dequeue(&queue);
if (element != -1) {
printf("Dequeued element: %d\n", element);
}
break;
case 3:
element = front(&queue);
if (element != -1) {
printf("Front element: %d\n", element);
}
break;
case 4:
display(&queue);
break;
case 5:
exit(0);
default:
printf("Invalid choice\n");
}
}
return 0;
}
Output:
1. Enqueue
2. Dequeue
3. Front
4. Display
5. Exit
Enter your choice: 1
Enter the element to enqueue: 100
1. Enqueue
2. Dequeue
3. Front
4. Display
5. Exit
Enter your choice: 1
Enter the element to enqueue: 300
1. Enqueue
2. Dequeue
3. Front
4. Display
5. Exit
Enter your choice: 3
Front element: 100
1. Enqueue
2. Dequeue
3. Front
4. Display
5. Exit
Enter your choice: 4
Queue elements: 100 300
1. Enqueue
2. Dequeue
3. Front
4. Display
5. Exit
Enter your choice: 2
Dequeued element: 100
1. Enqueue
2. Dequeue
3. Front
4. Display
5. Exit
Enter your choice: 4
Queue elements: 300
1. Enqueue
2. Dequeue
3. Front
4. Display
5. Exit
Enter your choice: 5

Experiment 9
Write a C program that uses functions to create a singly linked list and perform various
operations on it.
Program:
#include <stdio.h>
#include <stdlib.h>
// Define the structure for a linked list node
typedef struct Node {
int data;
struct Node* next;
} Node;
// Function to create a new node
Node* createNode(int data) {
Node* newNode = (Node*) malloc(sizeof(Node));
if (!newNode) {
printf("Memory error\n");
return NULL;
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to insert a node at the beginning of the list
void insertAtBeginning(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
newNode->next = *head;
*head = newNode;
}
}
// Function to insert a node at the end of the list
void insertAtEnd(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// Function to delete a node from the list
void deleteNode(Node** head, int data) {
if (*head == NULL) return;

if ((*head)->data == data) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* temp = *head;
while (temp->next != NULL) {
if (temp->next->data == data) {
Node* nodeToDelete = temp->next;
temp->next = temp->next->next;
free(nodeToDelete);
return;
}
temp = temp->next;
}
}
// Function to print the linked list
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
// Function to free the linked list
void freeList(Node* head) {
Node* temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
}
int main() {
Node* head = NULL;
// Insert nodes at the beginning and end of the list
insertAtBeginning(&head, 10);
insertAtEnd(&head, 20);
insertAtBeginning(&head, 5);
insertAtEnd(&head, 30);
// Print the linked list
printf("Linked List: ");
printList(head);
// Delete a node from the list
deleteNode(&head, 20);
// Print the linked list after deletion
printf("Linked List after deletion: ");
printList(head);
// Free the linked list
freeList(head);
return 0;
}
Output:
Linked List: 5 -> 10 -> 20 -> 30 -> NULL
Linked List after deletion: 5 -> 10 -> 30 -> NULL

Experiment 10
Write a C program to store a polynomial expression in memory using a linked list and
perform polynomial addition.
Program:
#include <stdio.h>
#include <stdlib.h>

// Define the structure for a polynomial term


typedef struct Term {
int coefficient;
int exponent;
struct Term* next;
} Term;

// Function to create a new term


Term* createTerm(int coefficient, int exponent) {
Term* newTerm = (Term*) malloc(sizeof(Term));
if (!newTerm) {
printf("Memory error\n");
return NULL;
}
newTerm->coefficient = coefficient;
newTerm->exponent = exponent;
newTerm->next = NULL;
return newTerm;
}

// Function to insert a term at the end of the polynomial


void insertTerm(Term** head, int coefficient, int exponent) {
Term* newTerm = createTerm(coefficient, exponent);
if (*head == NULL) {
*head = newTerm;
} else {
Term* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newTerm;
}
}

// Function to print the polynomial


void printPolynomial(Term* head) {
Term* temp = head;
while (temp != NULL) {
printf("%dx^%d + ", temp->coefficient, temp->exponent);
temp = temp->next;
}
printf("0\n");
}

// Function to add two polynomials


Term* addPolynomials(Term* poly1, Term* poly2) {
Term* result = NULL;
Term* temp1 = poly1;
Term* temp2 = poly2;

while (temp1 != NULL && temp2 != NULL) {


if (temp1->exponent > temp2->exponent) {
insertTerm(&result, temp1->coefficient, temp1->exponent);
temp1 = temp1->next;
} else if (temp1->exponent < temp2->exponent) {
insertTerm(&result, temp2->coefficient, temp2->exponent);
temp2 = temp2->next;
} else {
int coefficient = temp1->coefficient + temp2->coefficient;
if (coefficient != 0) {
insertTerm(&result, coefficient, temp1->exponent);
}
temp1 = temp1->next;
temp2 = temp2->next;
}
}

while (temp1 != NULL) {


insertTerm(&result, temp1->coefficient, temp1->exponent);
temp1 = temp1->next;
}

while (temp2 != NULL) {


insertTerm(&result, temp2->coefficient, temp2->exponent);
temp2 = temp2->next;
}

return result;
}

// Function to free the polynomial


void freePolynomial(Term* head) {
Term* temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
}

int main() {
Term* poly1 = NULL;
Term* poly2 = NULL;
Term* result = NULL;

// Create polynomial 1: 2x^2 + 3x + 1


insertTerm(&poly1, 2, 2);
insertTerm(&poly1, 3, 1);
insertTerm(&poly1, 1, 0);

// Create polynomial 2: x^2 + 2x + 1


insertTerm(&poly2, 1, 2);
insertTerm(&poly2, 2, 1);
insertTerm(&poly2, 1, 0);

// Print the polynomials


printf("Polynomial 1: ");
printPolynomial(poly1);
printf("Polynomial 2: ");
printPolynomial(poly2);

// Add the polynomials


result = addPolynomials(poly1, poly2);

// Print the result


printf("Result: ");
printPolynomial(result);

// Free the polynomials


freePolynomial(poly1);
freePolynomial(poly2);
freePolynomial(result);

return 0;
}
Output:
Polynomial 1: 2x^2 + 3x^1 + 1x^0 + 0
Polynomial 2: 1x^2 + 2x^1 + 1x^0 + 0
Result: 3x^2 + 5x^1 + 2x^0 + 0

Experiment 11
a) Write a recursive C program for traversing a binary tree in preorder, in order and
post order.
Program:
#include <stdio.h>
#include <stdlib.h>

// Define the structure for a binary tree node


typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;

// Function to create a new node


Node* createNode(int data) {
Node* newNode = (Node*) malloc(sizeof(Node));
if (!newNode) {
printf("Memory error\n");
return NULL;
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

// Recursive function to traverse the binary tree in preorder


void preorderRecursive(Node* root) {
if (root == NULL) return;
printf("%d ", root->data);
preorderRecursive(root->left);
preorderRecursive(root->right);
}

// Recursive function to traverse the binary tree in inorder


void inorderRecursive(Node* root) {
if (root == NULL) return;
inorderRecursive(root->left);
printf("%d ", root->data);
inorderRecursive(root->right);
}

// Recursive function to traverse the binary tree in postorder


void postorderRecursive(Node* root) {
if (root == NULL) return;
postorderRecursive(root->left);
postorderRecursive(root->right);
printf("%d ", root->data);
}

int main() {
Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);

printf("Preorder Recursive: ");


preorderRecursive(root);
printf("\n");

printf("Inorder Recursive: ");


inorderRecursive(root);
printf("\n");

printf("Postorder Recursive: ");


postorderRecursive(root);
printf("\n");

return 0;
}
Output:
Preorder Recursive: 1 2 4 5 3
Inorder Recursive: 4 2 5 1 3
Postorder Recursive: 4 5 2 3 1

b) Write a non recursive C program for traversing a binary tree in preorder, in order
and post order.
Program:
#include <stdio.h>
#include <stdlib.h>

// Define the structure for a binary tree node


typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;

// Function to create a new node


Node* createNode(int data) {
Node* newNode = (Node*) malloc(sizeof(Node));
if (!newNode) {
printf("Memory error\n");
return NULL;
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

// Non-recursive function to traverse the binary tree in preorder


void preorderNonRecursive(Node* root) {
if (root == NULL) return;
Node* stack[100];
int top = -1;
Node* temp = root;

while (temp != NULL || top != -1) {


while (temp != NULL) {
printf("%d ", temp->data);
stack[++top] = temp;
temp = temp->left;
}
temp = stack[top--];
temp = temp->right;
}
printf("\n");
}

// Non-recursive function to traverse the binary tree in inorder


void inorderNonRecursive(Node* root) {
if (root == NULL) return;
Node* stack[100];
int top = -1;
Node* temp = root;

while (temp != NULL || top != -1) {


while (temp != NULL) {
stack[++top] = temp;
temp = temp->left;
}
temp = stack[top--];
printf("%d ", temp->data);
temp = temp->right;
}
printf("\n");
}

// Non-recursive function to traverse the binary tree in postorder


void postorderNonRecursive(Node* root) {
if (root == NULL) return;
Node* stack1[100];
Node* stack2[100];
int top1 = -1;
int top2 = -1;
Node* temp = root;

while (temp != NULL || top1 != -1) {


while (temp != NULL) {
stack1[++top1] = temp;
temp = temp->left;
}
temp = stack1[top1--];
stack2[++top2] = temp;
temp = temp->right;
}

while (top2 != -1) {


printf("%d ", stack2[top2--]->data);
}
printf("\n");
}

int main() {
Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);

printf("Preorder Non-Recursive: ");


preorderNonRecursive(root);

printf("Inorder Non-Recursive: ");


inorderNonRecursive(root);

printf("Postorder Non-Recursive: ");


postorderNonRecursive(root);

return 0;
}
Output:
Preorder Non-Recursive: 1 2 4 5 3
Inorder Non-Recursive: 4 2 5 1 3
Postorder Non-Recursive: 3 1 5 2 4

Experiment 12
Implementation of Hash table using double hashing as collision resolution function.
Program:
#include <stdio.h>
#include <stdlib.h>
#define TABLE_SIZE 10

typedef struct HashTable {


int *table;
int size;
int count;
} HashTable;

// Primary hash function


int hash1(int key, int size) {
return key % size;
}

// Secondary hash function (should be non-zero)


int hash2(int key, int size) {
return 1 + (key % (size - 1));
}

// Create a hash table


HashTable* createHashTable(int size) {
HashTable *ht = malloc(sizeof(HashTable));
ht->size = size;
ht->count = 0;
ht->table = malloc(size * sizeof(int));

for (int i = 0; i < size; i++) {


ht->table[i] = -1; // Use -1 to indicate empty slots
}

return ht;
}

// Insert a key into the hash table


void insert(HashTable *ht, int key) {
if (ht->count >= ht->size * 0.7) { // Load factor threshold
// Resize logic can be implemented here
printf("Resize operation not implemented.\n");
return;
}

int index = hash1(key, ht->size);


int step = hash2(key, ht->size);
while (ht->table[index] != -1) {
if (ht->table[index] == key) {
return; // Key already exists
}
index = (index + step) % ht->size;
}

ht->table[index] = key;
ht->count++;
}

// Search for a key in the hash table


int search(HashTable *ht, int key) {
int index = hash1(key, ht->size);
int step = hash2(key, ht->size);

while (ht->table[index] != -1) {


if (ht->table[index] == key) {
return 1; // Key found
}
index = (index + step) % ht->size;
}

return 0; // Key not found


}

// Delete a key from the hash table


void delete(HashTable *ht, int key) {
int index = hash1(key, ht->size);
int step = hash2(key, ht->size);

while (ht->table[index] != -1) {


if (ht->table[index] == key) {
ht->table[index] = -2; // Mark as deleted
ht->count--;
return;
}
index = (index + step) % ht->size;
}
}

// Print the hash table


void printHashTable(HashTable *ht) {
for (int i = 0; i < ht->size; i++) {
if (ht->table[i] >= 0) {
printf("Index %d: %d\n", i, ht->table[i]);
} else if (ht->table[i] == -2) {
printf("Index %d: [deleted]\n", i);
} else {
printf("Index %d: [empty]\n", i);
}
}
}

// Free the hash table


void freeHashTable(HashTable *ht) {
free(ht->table);
free(ht);
}

// Example usage
int main() {
HashTable *ht = createHashTable(TABLE_SIZE);

insert(ht, 10);
insert(ht, 20);
insert(ht, 30);
insert(ht, 40);

printHashTable(ht);

printf("Search for 20: %d\n", search(ht, 20));


printf("Search for 50: %d\n", search(ht, 50));

delete(ht, 20);
printf("After deleting 20:\n");
printHashTable(ht);

insert(ht, 50);
printf("After inserting 50:\n");
printHashTable(ht);

freeHashTable(ht);
return 0;
}

Output:
Index 0: 10
Index 1: [empty]
Index 2: [empty]
Index 3: 20
Index 4: 30
Index 5: 40
Index 6: [empty]
Index 7: [empty]
Index 8: [empty]
Index 9: [empty]
Search for 20: 1
Search for 50: 0
After deleting 20:
Index 0: 10
Index 1: [empty]
Index 2: [empty]
Index 3: [deleted]
Index 4: 30
Index 5: 40
Index 6: [empty]
Index 7: [empty]
Index 8: [empty]
Index 9: [empty]
After inserting 50:
Index 0: 10
Index 1: [empty]
Index 2: [empty]
Index 3: [deleted]
Index 4: 30
Index 5: 40
Index 6: 50
Index 7: [empty]
Index 8: [empty]
Index 9: [empty]

Experiment 13
Implementation of Binary Search trees insertion and deletion
Program:
#include <stdio.h>
#include <stdlib.h>

// Define the structure for a tree node


typedef struct Node {
int data;
struct Node *left;
struct Node *right;
} Node;

// Function to create a new node


Node* createNode(int data) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

// Function to insert a new node into the BST


Node* insert(Node* root, int data) {
if (root == NULL) {
return createNode(data);
}

if (data < root->data) {


root->left = insert(root->left, data);
} else if (data > root->data) {
root->right = insert(root->right, data);
}

return root; // Return the unchanged root pointer


}

// Function to find the minimum value node in the BST


Node* findMin(Node* root) {
while (root->left != NULL) {
root = root->left;
}
return root;
}

// Function to delete a node from the BST


Node* delete(Node* root, int data) {
if (root == NULL) {
return root; // Key not found
}

// Traverse the tree


if (data < root->data) {
root->left = delete(root->left, data);
} else if (data > root->data) {
root->right = delete(root->right, data);
} else {
// Node with only one child or no child
if (root->left == NULL) {
Node *temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
Node *temp = root->left;
free(root);
return temp;
}

// Node with two children: Get the inorder successor (smallest in the right
subtree)
Node *temp = findMin(root->right);

// Copy the inorder successor's content to this node


root->data = temp->data;

// Delete the inorder successor


root->right = delete(root->right, temp->data);
}
return root;
}

// Function to perform in-order traversal of the BST


void inOrder(Node* root) {
if (root != NULL) {
inOrder(root->left);
printf("%d ", root->data);
inOrder(root->right);
}
}

// Main function to demonstrate the BST operations


int main() {
Node *root = NULL;

// Insert nodes
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);

// Print in-order traversal of the BST


printf("In-order traversal: ");
inOrder(root);
printf("\n");

// Delete a node
printf("Deleting 20...\n");
root = delete(root, 20);
printf("In-order traversal after deleting 20: ");
inOrder(root);
printf("\n");

return 0;
}
Output:
In-order traversal: 20 30 40 50 60 70 80
Deleting 20...
In-order traversal after deleting 20: 30 40 50 60 70 80

Experiment 14
Implementation of AVL Tree insertion and deletion
Program:
#include <stdio.h>
#include <stdlib.h>

// Define the structure for a tree node


typedef struct Node {
int data;
struct Node *left;
struct Node *right;
int height; // Height of the node
} Node;

// Function to create a new node


Node* createNode(int data) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
newNode->height = 1; // New node is initially added at leaf
return newNode;
}

// Function to get the height of the node


int getHeight(Node *node) {
return (node == NULL) ? 0 : node->height;
}

// Function to get the balance factor of the node


int getBalance(Node *node) {
return (node == NULL) ? 0 : getHeight(node->left) - getHeight(node->right);
}

// Right rotation
Node* rightRotate(Node *y) {
Node *x = y->left;
Node *T2 = x->right;

// Perform rotation
x->right = y;
y->left = T2;

// Update heights
y->height = 1 + (getHeight(y->left) > getHeight(y->right) ? getHeight(y->left) :
getHeight(y->right));
x->height = 1 + (getHeight(x->left) > getHeight(x->right) ? getHeight(x->left) :
getHeight(x->right));

// Return new root


return x;
}

// Left rotation
Node* leftRotate(Node *x) {
Node *y = x->right;
Node *T2 = y->left;

// Perform rotation
y->left = x;
x->right = T2;

// Update heights
x->height = 1 + (getHeight(x->left) > getHeight(x->right) ? getHeight(x->left) :
getHeight(x->right));
y->height = 1 + (getHeight(y->left) > getHeight(y->right) ? getHeight(y->left) :
getHeight(y->right));

// Return new root


return y;
}

// Insert a node into the AVL tree


Node* insert(Node* node, int data) {
if (node == NULL) {
return createNode(data);
}

if (data < node->data) {


node->left = insert(node->left, data);
} else if (data > node->data) {
node->right = insert(node->right, data);
} else {
return node; // Duplicate keys are not allowed
}

// Update the height of this ancestor node


node->height = 1 + (getHeight(node->left) > getHeight(node->right) ?
getHeight(node->left) : getHeight(node->right));

// Check balance and perform rotations if necessary


int balance = getBalance(node);

// Left Left Case


if (balance > 1 && data < node->left->data) {
return rightRotate(node);
}

// Right Right Case


if (balance < -1 && data > node->right->data) {
return leftRotate(node);
}

// Left Right Case


if (balance > 1 && data > node->left->data) {
node->left = leftRotate(node->left);
return rightRotate(node);
}

// Right Left Case


if (balance < -1 && data < node->right->data) {
node->right = rightRotate(node->right);
return leftRotate(node);
}

return node; // Return the unchanged node pointer


}

// Get the node with the minimum value


Node* minValueNode(Node* node) {
Node* current = node;
while (current->left != NULL) {
current = current->left;
}
return current;
}

// Delete a node from the AVL tree


Node* deleteNode(Node* root, int data) {
if (root == NULL) {
return root; // Key not found
}

// Perform standard BST delete


if (data < root->data) {
root->left = deleteNode(root->left, data);
} else if (data > root->data) {
root->right = deleteNode(root->right, data);
} else {
// Node with one child or no child
if ((root->left == NULL) || (root->right == NULL)) {
Node *temp = root->left ? root->left : root->right;

// No child case
if (temp == NULL) {
temp = root;
root = NULL;
} else {
*root = *temp; // Copy the contents of the non-empty child
}
free(temp);
} else {
// Node with two children: Get the inorder successor (smallest in the right
subtree)
Node* temp = minValueNode(root->right);
root->data = temp->data; // Copy the inorder successor's data
root->right = deleteNode(root->right, temp->data); // Delete the inorder
successor
}
}

if (root == NULL) {
return root; // Tree had only one node, it is now empty
}

// Update the height of the current node


root->height = 1 + (getHeight(root->left) > getHeight(root->right) ?
getHeight(root->left) : getHeight(root->right));

// Check balance and perform rotations if necessary


int balance = getBalance(root);

// Left Left Case


if (balance > 1 && getBalance(root->left) >= 0) {
return rightRotate(root);
}

// Left Right Case


if (balance > 1 && getBalance(root->left) < 0) {
root->left = leftRotate(root->left);
return rightRotate(root);
}

// Right Right Case


if (balance < -1 && getBalance(root->right) <= 0) {
return leftRotate(root);
}

// Right Left Case


if (balance < -1 && getBalance(root->right) > 0) {
root->right = rightRotate(root->right);
return leftRotate(root);
}

return root; // Return the unchanged node pointer


}

// Function to perform in-order traversal of the AVL tree


void inOrder(Node *root) {
if (root != NULL) {
inOrder(root->left);
printf("%d ", root->data);
inOrder(root->right);
}
}

// Main function to demonstrate AVL tree operations


int main() {
Node *root = NULL;

// Insert nodes
root = insert(root, 10);
root = insert(root, 20);
root = insert(root, 30);
root = insert(root, 40);
root = insert(root, 50);
root = insert(root, 25);

// Print in-order traversal of the AVL tree


printf("In-order traversal: ");
inOrder(root);
printf("\n");

// Delete nodes
printf("Deleting 20...\n");
root = deleteNode(root, 20);
printf("In-order traversal after deleting 20: ");
inOrder(root);
printf("\n");

printf("Deleting 30...\n");
root = deleteNode(root, 30);
printf("In-order traversal after deleting 30: ");
inOrder(root);
printf("\n");

return 0;
}
Output:
In-order traversal: 10 20 25 30 40 50
Deleting 20...
In-order traversal after deleting 20: 10 25 30 40 50
Deleting 30...
In-order traversal after deleting 30: 10 25 40 50

Experiment 15
a) Write a C program that implements Bubble sort, to sort a given list of integers in
ascending order.
Program:
#include <stdio.h>

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

void printArray(int arr[], int n) {


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);

bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);

return 0;
}
Output:
Sorted array:
11 12 22 25 34 64 90
b) Write a C program that implements Quick sort, to sort a given list of integers
ascending order.
Program:
#include <stdio.h>

int partition(int arr[], int low, int high) {


int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element

for (int j = low; j < high; j++) {


// If current element is smaller than or equal to pivot
if (arr[j] <= pivot) {
i++; // increment index of smaller element
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Swap pivot
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;

return (i + 1);
}

void quickSort(int arr[], int low, int high) {


if (low < high) {
int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1); // Before pi


quickSort(arr, pi + 1, high); // After pi
}
}

void printArray(int arr[], int n) {


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);

quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);

return 0;
}
Output:
Sorted array:
11 12 22 25 34 64 90
c) Write C program that implement Merge sort, to sort a given list of integers in
ascending order.
Program:
#include <stdio.h>

void merge(int arr[], int l, int m, int r) {


int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

// Create temporary arrays


int L[n1], R[n2];

// Copy data to temp arrays L[] and R[]


for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

// Merge the temp arrays back into arr[l..r]


i = 0; // Initial index of first sub-array
j = 0; // Initial index of second sub-array
k = l; // Initial index of merged sub-array
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
// Copy the remaining elements of L[], if there are any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

// Copy the remaining elements of R[], if there are any


while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

void mergeSort(int arr[], int l, int r) {


if (l < r) {
int m = l + (r - l) / 2;

mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}

void printArray(int arr[], int n) {


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);

mergeSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);

return 0;
}
Output:
Sorted array:
11 12 22 25 34 64 90

You might also like