Data Structures Lab ALL EXPERIMENTS FILE

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 84

Data Structures Lab

FILE OF COMBINED EXPERIMENTS

Name: DHRUV SHARMA

Batch: 34

Sap Id: 500095950

Roll.no: - R2142211010
Experiment 1
Program 1: Find sum of arrays using recursion.

Code:

#include <iostream>

using namespace std;

int sum(int a[], int n)

if (n <= 0)

return 0;

return (sum(a, n - 1) + a[n - 1]);

int main()

int a[] = {0, 2, 3, 4, 5 };

int n = sizeof(a) / sizeof(a[0]);

printf("%d \n", sum(a, n));

return 0;

}
Program 2: Create an array ‘a1’ with ‘n’ elements. Insert an element in ith position of ‘a1’
and also delete an element from jth position of ‘a1’

#include<iostream>

using namespace std;

void display(int a[] , int n){

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

cout<<a[i]<<"\t"; }}

int main(){

int n , a1[100] , i , j;

cout<<"Enter number of elements : ";

cin>>n;

cout<<"Enter elements in array : "<<endl;

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

cin>>a1[i]; }

cout<<"Array : ";

display(a1 , n);

cout<<"\n\nEnter position (form 1 to "<<n<<") at which you want to insert the element : ";

cin>>i;

if(i > n) {

cout<<"Invalid position";}

else {

for(int x = n-1 ; x >= i-1 ; x--) {

a1[x+1] = a1[x]; }
cout<<"Enter the element to be inserted : ";

cin>>a1[i-1];

cout<<"Array after inserting the element : ";

n = n+1;

display(a1 , n); }

cout<<"\n\nEnter position (form 1 to "<<n<<") from where you want to delete the
element : ";

cin>>j;

if(i > n){

cout<<"Invalid position";}

else{

for(int x = j-1 ; x < n-1 ; x++) {

a1[x] = a1[x+1]; }

cout<<"Array after deleting the element : ";

n = n-1;

display(a1 , n); }

return 0;

Program 3: Program to convert upper string to lower string


#include <iostream>

#include <cstring>

using namespace std;

int main()

{ char s[20];

int i;

cout<<"Enter the String in uppercase: ";

cin>>s;

for(i=0;i<=strlen(s);i++) {

if(s[i]>=65 && s[i]<=92)

{ s[i]=s[i]+32; } }

cout<<"The entered string in lowercase: "<<s;

return 0;

Program 4: Find the sum of rows and columns of matrix of given order

#include <iostream>

using namespace std;

int main()

{ int size1;

size1 = 3;
int Arr[size1][size1];

int a, b, c;

cout<<"Enter elements in matrix of size "<<size1<<" x "<<size1<<"\n";

for(a=0; a<size1; a++) {

for(b=0; b<size1; b++) {

cin>>Arr[a][b]; } }

for(a=0; a<size1; a++) {

c = 0;

for(b=0; b<size1; b++) {

c += Arr[a][b]; }

cout<<"sum of elements of row "<<a+1<<" = "<<c<<"\n";

for(a=0; a<size1; a++) {

c = 0;

for(b=0; b<size1; b++) {

c += Arr[b][a]; }

cout<<"sum of elements of col "<<a+1<<" = "<<c<<"\n"; }

return 0;

}
Program 5: Find the product of matrix using pointers

#include <stdio.h>

#define ROW 3

#define COL 3

void matrixInput(int mat[][COL]);

void matrixPrint(int mat[][COL]);

void matrixMultiply(int mat1[][COL], int mat2[][COL], int res[][COL]);

int main()

{ int mat1[ROW][COL];

int mat2[ROW][COL];

int product[ROW][COL];

printf("Enter elements in first matrix of size %dx%d\n", ROW, COL);

matrixInput(mat1);

printf("Enter elements in second matrix of size %dx%d\n", ROW, COL);

matrixInput(mat2);
matrixMultiply(mat1, mat2, product);

printf("Product of both matrices is : \n");

matrixPrint(product);

return 0; }

void matrixInput(int mat[][COL])

{ int row, col;

for (row = 0; row < ROW; row++) {

for (col = 0; col < COL; col++)

{ scanf("%d", (*(mat + row) + col)); } } }

void matrixPrint(int mat[][COL])

{ int row, col;

for (row = 0; row < ROW; row++)

{ for (col = 0; col < COL; col++)

{ printf("%d ", *(*(mat + row) + col));}

printf("\n"); }}

void matrixMultiply(int mat1[][COL], int mat2[][COL], int res[][COL])

{ int row, col, i;

int sum;

for (row = 0; row < ROW; row++)

{ for (col = 0; col < COL; col++)

{ sum = 0;

for (i = 0; i < COL; i++)

{sum += (*(*(mat1 + row) + i)) * (*(*(mat2 + i) + col));}

*(*(res + row) + col) = sum; } } }


Program 6: Store ‘n’ numbers in an array. Conduct linear search for a given number and
report success or failure in the form of a suitable message

#include <stdio.h>

int search(int arr[], int n, int x)

int i;

for (i = 0; i < n; i++)

if (arr[i] == x)
return i;

return -1;

int main()

int arr[] = { 2, 3, 4, 10, 40 };

int x;

printf("enter the element to search");

scanf("%d",&x);

int n = sizeof(arr) / sizeof(arr[0]);

int result = search(arr, n, x);

(result == -1);

printf("Element is not present in array");

printf("Element is present at index %d", result);

return 0;

Program 7: Conduct binary search for a given number

#include <stdio.h>
int Search(int arr[], int l, int r, int a)

if (r >= l) {

int mid = l + (r - l) / 2;

if (arr[mid] == a)

return mid;

if (arr[mid] > a)

return Search(arr, l, mid - 1, a);

return Search(arr, mid + 1, r, a);

return -1;

int main(void)

int arr[] = { 2, 3, 4, 10, 40 };

int n = sizeof(arr) / sizeof(arr[0]);

int a ;

printf("enter the element to search");

scanf("%d", &a);

int res = Search(arr, 0, n - 1, a);

if (res == -1)

printf("Element is not present in array");

else printf("Element is present at index %d", res);

return 0;
}

Program 8: Structure to store 10 student information

#include<stdio.h>

#include <string.h>

struct student{

int rollno;

char name[10];

char course[10]

};

int main(){

int i;

struct student st[10];

printf("Enter Records of 10 students");

for(i=0;i<10;i++){

printf("\nEnter Rollno:");

scanf("%d",&st[i].rollno);

printf("\nEnter Name:");

scanf("%s",&st[i].name);

printf("\nEnter Course:");

scanf("%s",&st[i].course);

}
printf("\nStudent Information List:");

for(i=0;i<10;i++){

printf("\nRollno:%d, Name:%s, Course:%s",st[i].rollno,st[i].name,st[i].course);

return 0;

}
Program 9: Merging of Two Arrays

#include<iostream>

using namespace std;

void mergeArrays(int arr1[], int arr2[], int n1,int n2, int arr3[])

{ int i = 0, j = 0, k = 0;

while (i<n1 && j <n2)

{ if(arr1[i] < arr2[j])

arr3[k++] = arr1[i++];

else

arr3[k++] = arr2[j++];

while (i < n1)

arr3[k++] = arr1[i++];

while (j < n2)

arr3[k++] = arr2[j++]; }

int main(){

int arr1[] = {1, 3, 5, 7};

int n1 = sizeof(arr1) / sizeof(arr1[0]);

int arr2[] = {2, 4, 6, 8};

int n2 = sizeof(arr2) / sizeof(arr2[0]);

int arr3[n1+n2];

mergeArrays(arr1, arr2, n1, n2, arr3);

cout << "Array after merging" <<endl;


for (int i=0; i < n1+n2; i++)

cout << arr3[i] << " ";

return 0;

Experiment 2

Write C program, compile, execute and test the code using Linux C compiler with suitable
test cases.

1. Design a union ‘product’ to store the details of the product purchased like product
name, price per unit, number of quantities purchased, and amount spent. Get the
name, price per unit, and number of quantities of the product purchased. Calculate
the amount spent on the product and then display all the details of the procured
product.

#include <stdio.h>

#include <string.h>

union product

int qnt;

char n[10];

float price;
};

int main()

union product t;

int i, n, q;

float m, p;

char a[20];

printf("Number of products you buy: ");

scanf("%d", &n);

for(i=0; i<n; i++)

printf("Name of product: ");

scanf("%s", t.n);

strcpy(a, t.n);

printf("Price of the product: ");

scanf("%f", &t.price);

p=t.price;

printf("Enter quantity bought: ");

scanf("%d", &t.qnt);

q=t.qnt;

printf("You purchased: \n");

printf("Name: %s, Quantity: %d, Price: %f\n", a, q, p);

m=m+p*q;

};
printf("Your total amount is %f",m);

Experiment 3
List of Lab Activities:

Write algorithm and C program, compile, execute and test the code using Linux C

compiler with suitable test cases.

i) Implement single Linked List data structure and its operations like insert and delete in

the beginning/end and nth position of the list, and display the items stored in the linked

list.

#include <stdio.h>

#include <stdlib.h>

struct Node {

int data;

struct Node* next;

};

void insertAtBeginning(struct Node** head_ref, int new_data) {

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

new_node->data = new_data;
new_node->next = (*head_ref);

(*head_ref) = new_node;

void insertAfter(struct Node* prev_node, int new_data) {

if (prev_node == NULL) {

printf("the given previous node cannot be NULL");

return;

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

new_node->data = new_data;

new_node->next = prev_node->next;

prev_node->next = new_node;

void insertAtEnd(struct Node** head_ref, int new_data) {

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

struct Node* last = *head_ref; /* used in step 5*/

new_node->data = new_data;

new_node->next = NULL;

if (*head_ref == NULL) {

*head_ref = new_node;

return;

while (last->next != NULL) last = last->next;

last->next = new_node;
return;

void deleteNode(struct Node** head_ref, int key) {

struct Node *temp = *head_ref, *prev;

if (temp != NULL && temp->data == key) {

*head_ref = temp->next;

free(temp);

return;

while (temp != NULL && temp->data != key) {

prev = temp;

temp = temp->next;

if (temp == NULL) return;

prev->next = temp->next;

free(temp);

void printList(struct Node* node) {

while (node != NULL) {

printf(" %d ", node->data);

node = node->next;

int main() {
struct Node* head = NULL;

insertAtEnd(&head, 1);

printf("Linked list: ");

printList(head);

printf("\n");

insertAtBeginning(&head, 2);

printf("Linked list: ");

printList(head);

printf("\n");

insertAtBeginning(&head, 3);

insertAtEnd(&head, 4);

printf("Linked list: ");

printList(head);

printf("\n");

insertAfter(head->next, 5);

printf("Linked list: ");

printList(head);

printf("\n");

deleteNode(&head, 3);

printf("Linked list: ");

printList(head);

printf("\n");

}
ii)Using single linked list and functions implement Stack and its operations like insert,

delete, and display

#include <iostream>

using namespace std;

struct Node

int data;

Node* link;

};

Node* top;

void push(int data)

Node* temp = new Node();

if (!temp)

cout << "\nStack Overflow";

exit(1);

temp->data = data;
temp->link = top;

top = temp;

int isEmpty()

return top == NULL;

int peek(){

if (!isEmpty())

return top->data;

else

exit(1);

void pop()

Node* temp;

if (top == NULL)

cout << "\nStack Underflow" << endl;

exit(1);

else

temp = top;
top = top->link;

free(temp);

void display()

Node* temp;

if (top == NULL)

cout << "\nStack Underflow";

exit(1);

else

temp = top;

while (temp != NULL)

cout << temp->data << " ";

temp = temp->link;

int main()

{
push(11);

display();

printf("\n");

push(22);

display();

printf("\n");

push(33);

push(44);

display();

cout << "\nTop element is "<< peek() << endl;

pop();

pop();

display();

cout << "\nTop element is " << peek() << endl;

return 0;

}
Experiment 4
1) Write C program, compile, execute and test the code using Linux

C compiler with suitable test cases.

• Using array and functions implement Stack and its operations like insert,

delete, and display.

#include <stdio.h>

#include <stdlib.h>

#define MAX 10

int STACK[MAX],TOP;

void push(int stack[],int item)

if(TOP==MAX-1)

printf("\nFull stack\n");

return;

TOP++;

stack[TOP]=item;

void display(int stack[])

int i=0;

if(TOP==-1)
{

printf(" Empty Stack .\n");

return;

else{

printf("%d <-- TOP ",stack[TOP]);

for(i=TOP-1;i >=0;i--)

printf("\n%d",stack[i]);

printf("\n");

void pop(int stack[])

int deletedItem;

if(TOP==-1)

printf(" EMPTY STACK\n");

return;

else{

deletedItem=stack[TOP];

TOP--;
printf("%d successfully deleted \n",deletedItem);

return;

void main()

int ITEM=0;

int choice=0;

TOP=-1;

while(1)

printf("\n Menu ");

printf("\n 1: display");

printf("\n 2: insert");

printf("\n 3: remove");

printf("\n 4: Exit");

printf("\n Enter Choice");

scanf("%d",&choice);

switch(choice)

{ case 1:

display(STACK);

break;

case 2:

printf("Enter Item :");


scanf("%d",&ITEM);

push(STACK,ITEM);

break;

case 3:

pop(STACK);

break;

case 4:

exit(0);

default:

printf("\n Wrong choice.");

break;

}}}
2) Reverse a String using stack

#include <stdio.h>

#include <string.h>

#define MAX 100

int top=-1;

int item;

char stack_string[MAX];

void pushChar(char item);

char popChar(void);

char fitem;

int isEmpty(void);

int isFull(void);
int main()

char str[MAX];

int i;

printf("Input a string: ");

scanf("%[^\n]s",str);

fitem=str[0];

for(i=0;i<strlen(str);i++)

if(top==MAX-1){

printf("\nFull Stack \n");

else

top=top+1;

stack_string[top]=str[i];

printf("Reversed String is: ");

top=top+1;

for(i=strlen(str);i>=0;i--)

if(top==-1)

printf("\nEmpty Stack \n");


else{

stack_string[top];

top=top-1;

printf("%c",stack_string[i]);

return 0;

Experiment 5

Write C program, compile, execute and test the code using Linux

C compiler with suitable test cases.

1) Using array and functions implement Queue data structure and its operations

like insert, delete, and display.

#include <stdio.h>

#define MAX 50

void insert();

void delete();
void display();

int queue_array[MAX];

int rear = - 1;

int front = - 1;

main()

int choice;

while (1)

printf("1.Insert element to queue \n");

printf("2.Delete element from queue \n");

printf("3.Display all elements of queue \n");

printf("4.Quit \n");

printf("Enter your choice : ");

scanf("%d", &choice);

switch (choice)

case 1:

insert();

break;

case 2:

delete();

break;

case 3:
display();

break;

case 4:

exit(1);

default:

printf("Wrong choice \n");

void insert()

int add_item;

if (rear == MAX - 1)

printf("Queue Overflow \n");

else

if (front == - 1)

front = 0;

printf("Inset the element in queue : ");

scanf("%d", &add_item);

rear = rear + 1;

queue_array[rear] = add_item;

}
void delete()

if (front == - 1 || front > rear)

printf("Queue Underflow \n");

return ;

else

printf("Element deleted from queue is : %d\n", queue_array[front]);

front = front + 1;

void display()

int i;

if (front == - 1)

printf("Queue is empty \n");

else

printf("Queue is : \n");

for (i = front; i <= rear; i++)

printf("%d ", queue_array[i]);

printf("\n");
}

2) Check whether the string is palindrome or not using array and Queue.

#include<iostream>

using namespace std;

class node{

public:

char v;

node *next;

node *prev;

};
class queue{

node *front,*rear;

int size;

public:

queue()

front=new node();

rear=NULL;

size=0;

void enqueue(char a)

node *newnode=new node();

newnode->v=a;

if(rear!=NULL)

rear->next=newnode;

newnode->prev=rear;

newnode->next=NULL;

rear=newnode;

else

front->next=newnode;
front->prev=NULL;

newnode->next=NULL;

newnode->prev=front;

rear=newnode;

size++;

int si()

return size;

int check()

int count;

node *p=new node();

p=front->next;

while(p!=NULL && rear!=NULL)

if(p->v==rear->v)

count++;

p=p->next;

rear=rear->prev;
}

return count;

};

int main()

queue q1;

int s,num;

cout<<"Enter size of string :";

cin>>s;

char a[s],n;

cout<<"Enter string :";

cin>>a;

for(int i=0;i<s;i++)

n=a[i];

q1.enqueue(n);

num=q1.check();

int ns=s%2;

if(ns==1)

if(num==(s-1))
{

cout<<"Palindrome"<<endl;

else

cout<<"not a Palindrome";

else

if(num==s)

cout<<"Palindrome"<<endl;

else

cout<<"not a Palindrome";

return 0;

}
Experiment 6
Write C program, compile, execute and test the code using Linux

C compiler with suitable test cases.

1) Merge the contents of two lists to another.

#include <stdio.h>

#include<stdlib.h>

#include <assert.h>

struct Node

int data;

struct Node* next;

};

void MoveNode(struct Node** destRef, struct Node** sourceRef);

struct Node* SortedMerge(struct Node* a, struct Node* b)

struct Node dummy;

struct Node* tail = &dummy;

dummy.next = NULL;

while (1)

if (a == NULL)

tail->next = b;
break;

else if (b == NULL)

tail->next = a;

break;

if (a->data <= b->data)

MoveNode(&(tail->next), &a);

else

MoveNode(&(tail->next), &b);

tail = tail->next;

return(dummy.next);

void MoveNode(struct Node** destRef, struct Node** sourceRef)

struct Node* newNode = *sourceRef;

assert(newNode != NULL);

*sourceRef = newNode->next;

newNode->next = *destRef;

*destRef = newNode;

}
void push(struct Node** head_ref, int new_data){

struct Node* new_node =

(struct Node*) malloc(sizeof(struct Node));

new_node->data = new_data;

new_node->next = (*head_ref);

(*head_ref) = new_node;

void printList(struct Node *node)

while (node!=NULL)

printf("%d ", node->data);

node = node->next;

int main()

struct Node* res = NULL;

struct Node* a = NULL;

struct Node* b = NULL;

push(&a, 10);

push(&a, 5);

push(&b, 20);
push(&b, 3);

push(&b, 2);

res = SortedMerge(a, b);

printf("Merged Linked List is: \n");

printList(res);

return 0;

2) Read the numbers from the user into an array and sort them using the insertion Sort
algorithm

#include <math.h>

#include <stdio.h>

void insertionSort(int arr[], int n)

int i, key, j;

for (i = 1; i < n; i++) {

key = arr[i];

j = i - 1;

while (j >= 0 && arr[j] > key) {

arr[j + 1] = arr[j];
j = j - 1;

arr[j + 1] = key;

void printArray(int arr[], int n)

int i;

for (i = 0; i < n; i++)

printf("%d ", arr[i]);

printf("\n");

int main()

{ int q;

printf("enter the number of element");

int arr[q];

scanf("%d",&q);

for(int w = 0;w<q;w++){

scanf("%d",&arr[w]);

};

int n = sizeof(arr) / sizeof(arr[0]);

insertionSort(arr, q);

printArray(arr, q);

return 0;
}

Experiment 7

Write algorithm and C program, compile, execute and test the code using Linux

C compiler with suitable test cases.

WAP to implement linear and binary search algorithms

#include <stdio.h>

#include <stdlib.h>

int main()

int array[100],search_key,i,j,n,low,high,location,choice;

void linear_search(int search_key,int array[100],int n);

void binary_search(int search_key,int array[100],int n);

printf("ENTER THE SIZE OF THE ARRAY:");

scanf("%d",&n);

printf("ENTER THE ELEMENTS OF THE ARRAY:\n");

for(i=1;i<=n;i++)
{

scanf("%d",&array[i]);

printf("ENTER THE SEARCH KEY:");

scanf("%d",&search_key);

printf("___________________\n");

printf("1.LINEAR SEARCH\n");

printf("2.BINARY SEARCH\n");

printf("___________________\n");

printf("ENTER YOUR CHOICE:");

scanf("%d",&choice);

switch(choice)

case 1:

linear_search(search_key,array,n);

break;

case 2:

binary_search(search_key,array,n);

break;

default:

exit(0);

return 0;

}
void linear_search(int search_key,int array[100],int n)

int i,location;

for(i=1;i<=n;i++)

if(search_key == array[i])

location = i;

printf("______________________________________\n");

printf("The location of Search Key = %d is %d\n",search_key,location);

printf("______________________________________\n");

void binary_search(int search_key,int array[100],int n)

int mid,i,low,high;

low = 1;

high = n;

mid = (low + high)/2;

i=1;

while(search_key != array[mid])

if(search_key <= array[mid])


{

low = 1;

high = mid+1;

mid = (low+high)/2;

else

low = mid+1;

high = n;

mid = (low+high)/2;

printf("__________________________________\n");

printf("location=%d\t",mid);

printf("Search_Key=%d Found!\n",search_key);

printf("__________________________________\n");

}
Experiment 8
Write C program, compile, execute and test the code using Linux

C compiler with suitable test cases.


1. Implement a hash function on student SAP-ID and categorize them in to their

10 families based on the last three digits. Example: Student with SAP-ID

5000423 belongs to family 9 and student with SAP-ID 5000425 belongs to

family 2 based on last three digits.

#include <stdio.h>

#include <stdlib.h>

struct set

int SAPID;

int MARKS;

};

struct set *array;

int capacity = 10;

int size = 0;

int hashFunction(int SAPID)

int n,sum=0,m;

n = SAPID;

while(n>0)

m=n%10;

sum=sum+m;

n=n/10;

}
sum = sum-5;

return 0;

};

int checkPrime(int n)

int i;

if (n == 1 || n == 0)

return 0;

for (i = 2; i < n / 2; i++)

if (n % i == 0)

return 0;

return 1;

int getPrime(int n)

if (n % 2 == 0)

n++;
}

while (!checkPrime(n))

n += 2;

return n;

void init_array()

capacity = getPrime(capacity);

array = (struct set *)malloc(capacity * sizeof(struct set));

for (int i = 0; i < capacity; i++)

array[i].SAPID = 0;

array[i].MARKS = 0;

void insert(int SAPID, int MARKS)

int index = hashFunction(SAPID);

if (array[index].MARKS == 0)

array[index].SAPID = SAPID;

array[index].MARKS = MARKS;
size++;

printf("\n Key (%d) has been inserted \n", SAPID);

else if (array[index].SAPID == SAPID)

array[index].MARKS = MARKS;

else

printf("\n Collision occured \n");

void remove_element(int SAPID)

int index = hashFunction(SAPID);

if (array[index].MARKS == 0)

printf("\n This SAPID does not exist \n");

else

array[index].SAPID = 0;

array[index].MARKS = 0;

size--;
printf("\n Key (%d) has been removed \n", SAPID);

void display()

int i;

for (i = 0; i < capacity; i++)

if (array[i].MARKS == 0)

printf("\n array[%d]: / ", i);

else

printf("\n SAPID: %d array[%d]: %d \t", array[i].SAPID, i, array[i].MARKS);

int size_of_hashtable()

return size;

int main()

{
int choice, SAPID, MARKS, n;

int c = 0;

init_array();

do

printf("1.Insert item in the Hash Table"

"\n2.Remove item from the Hash Table"

"\n3.Check the size of Hash Table"

"\n4.Display a Hash Table"

"\n\n Please enter your choice: ");

scanf("%d", &choice);

switch (choice)

case 1:

printf("Enter SAPID -:\t");

scanf("%d", &SAPID);

printf("Enter MARKS -:\t");

scanf("%d", &MARKS);

insert(SAPID, MARKS);

break;

case 2:

printf("Enter the SAPID to delete-:");

scanf("%d", &SAPID);

remove_element(SAPID);
break;

case 3:

n = size_of_hashtable();

printf("Size of Hash Table is-:%d\n", n);

break;

case 4:

display();

break;

default:

printf("Invalid Input\n");

printf("\nDo you want to continue (press 1 for yes): ");

scanf("%d", &c);

} while (c == 1);

}
2. Implement a Hash table using arrays. Perform Insert, Delete and Search

operations on the hash table using the above Hash function (S.No.1). Adopt a

suitable user-defined exception handling strategy if collision occurs while

inserting data.

#include<stdio.h>

#define size 7

int arr[size];

void init()

int i;

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

arr[i] = -1;

void insert(int value)

int key = value % size;

if(arr[key] == -1)

arr[key] = value;

printf("%d inserted at arr[%d]\n", value,key);

else

printf("Collision : arr[%d] has element %d already!\n",key,arr[key]);


printf("Unable to insert %d\n",value);

void del(int value)

int key = value % size;

if(arr[key] == value)

arr[key] = -1;

else

printf("%d not present in the hash table\n",value);

void search(int value)

int key = value % size;

if(arr[key] == value)

printf("Search Found\n");

else

printf("Search Not Found\n");

void print()

int i;

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

printf("arr[%d] = %d\n",i,arr[i]);
}

int main()

init();

insert(10);

insert(4);

insert(2);

insert(3);

printf("Hash table\n");

print();

printf("\n");

printf("Deleting value 10..\n");

del(10);

printf("After the deletion hash table\n");

print();

printf("\n");

printf("Deleting value 5..\n");

del(5);

printf("After the deletion hash table\n");

print();

printf("\n");

printf("Searching value 4..\n");

search(4);

printf("Searching value 10..\n");


search(10);

return 0;

}
3. Implement a Hash table using arrays. Perform Insert, Delete and Search

operations on the hash table using the above Hash function (S.No.1) and with

Linear probing as Collision avoidance strategy.

#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;

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);

int size_of_hashtable()

return size;

void main()

int choice, key, value, n, c;

clrscr();

array = (struct hashtable_item*) malloc(max * sizeof(struct hashtable_item*));

init_array();
do {

printf("Implementation of Hash Table in C with 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");

printf("\n Do you want to continue-:(press 1 for yes)\t");

scanf("%d", &c);

}while(c == 1);

}
Experiment 9

Write C program, compile, execute and test the code using Linux

C compiler with suitable test cases.

1. Create a binary tree using an array/linked List.

#include <iostream>

#include <string>

#include <queue>

using namespace std;

struct ListNode

int data;

ListNode* next;

};

struct BinaryTreeNode

int data;

BinaryTreeNode *left, *right;

};

void push(struct ListNode** head_ref, int new_data)

struct ListNode* new_node = new ListNode;

new_node->data = new_data;
new_node->next = (*head_ref);

(*head_ref) = new_node;

BinaryTreeNode* newBinaryTreeNode(int data)

BinaryTreeNode *temp = new BinaryTreeNode;

temp->data = data;

temp->left = temp->right = NULL;

return temp;

void convertList2Binary(ListNode *head, BinaryTreeNode* &root)

queue<BinaryTreeNode *> q;

if (head == NULL)

root = NULL;

return;

root = newBinaryTreeNode(head->data);

q.push(root);

head = head->next;

while (head)

BinaryTreeNode* parent = q.front();


q.pop();

BinaryTreeNode *leftChild = NULL, *rightChild = NULL;

leftChild = newBinaryTreeNode(head->data);

q.push(leftChild);

head = head->next;

if (head)

rightChild = newBinaryTreeNode(head->data);

q.push(rightChild);

head = head->next;

parent->left = leftChild;

parent->right = rightChild;

void inorderTraversal(BinaryTreeNode* root)

if (root)

inorderTraversal( root->left );

cout << root->data << " ";

inorderTraversal( root->right );

}
int main()

struct ListNode* head = NULL;

push(&head, 36);

push(&head, 30);

push(&head, 25);

push(&head, 15);

push(&head, 12);

push(&head, 10);

BinaryTreeNode *root;

convertList2Binary(head, root);

cout << "Inorder Traversal of the constructed Binary Tree is: \n";

inorderTraversal(root);

return 0;

2. Construct a Binary Tree and perform Inorder, Preorder and Postorder Traversal.

#include <stdio.h>

#include <stdlib.h>

struct node {

int data;
struct node* left;

struct node* right;

};

struct node* newNode(int data)

struct node* node

= (struct node*)malloc(sizeof(struct node));

node->data = data;

node->left = NULL;

node->right = NULL;

return (node);

void printPostorder(struct node* node)

if (node == NULL)

return;

printPostorder(node->left);

printPostorder(node->right);

printf("%d ", node->data);

void printInorder(struct node* node)

if (node == NULL)

return;
printInorder(node->left);

printf("%d ", node->data);

printInorder(node->right);

void printPreorder(struct node* node)

if (node == NULL)

return;

printf("%d ", node->data);

printPreorder(node->left);

printPreorder(node->right);

int main()

struct node* root = newNode(1);

root->left = newNode(2);

root->right = newNode(3);

root->left->left = newNode(4);

root->left->right = newNode(5);

printf("\nPreorder traversal of binary tree is \n");

printPreorder(root);

printf("\nInorder traversal of binary tree is \n");

printInorder(root);

printf("\nPostorder traversal of binary tree is \n");


printPostorder(root);

getchar();

return 0;

3) Implement Heap Sort

#include <iostream>

using namespace std;

void heapify(int arr[], int n, int i)

int largest = i;

int l = 2 * i + 1;

int r = 2 * i + 2;

if (l < n && arr[l] > arr[largest])

largest = l;

if (r < n && arr[r] > arr[largest])

largest = r;

if (largest != i) {

swap(arr[i], arr[largest]);

heapify(arr, n, largest);

}
}

void heapSort(int arr[], int n)

for (int i = n / 2 - 1; i >= 0; i--)

heapify(arr, n, i);

for (int i = n - 1; i > 0; i--) {

swap(arr[0], arr[i]);

heapify(arr, i, 0);

void printArray(int arr[], int n)

for (int i = 0; i < n; ++i)

cout << arr[i] << " ";

cout << "\n";

int main()

int arr[] = { 12, 11, 13, 5, 6, 7 };

int n = sizeof(arr) / sizeof(arr[0]);

heapSort(arr, n);

cout << "Sorted array is \n";

printArray(arr, n);

}
Experiment 10

Write C program, compile, execute and test the code using Linux

C compiler with suitable test cases.

1. Accept the vertices and edges for a graph and stores it as an adjacency matrix.

Implement functions to print in-degree and out-degree of any vertex 'i'. Also

display the adjacency matrix.

#include <stdio.h>

int N, M;

void createAdjMatrix(int Adj[][N + 1],

int arr[][2])

for (int i = 0; i < N + 1; i++) {

for (int j = 0; j < N + 1; j++) {

Adj[i][j] = 0;

}
}

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

int x = arr[i][0];

int y = arr[i][1];

Adj[x][y] = 1;

Adj[y][x] = 1;

void printAdjMatrix(int Adj[][N + 1])

for (int i = 1; i < N + 1; i++) {

for (int j = 1; j < N + 1; j++) {

printf("%d ", Adj[i][j]);

printf("\n");

int main()

N = 5;

int arr[][2]

= { { 1, 2 }, { 2, 3 },

{ 4, 5 }, { 1, 5 } };

M = sizeof(arr) / sizeof(arr[0]);
int Adj[N + 1][N + 1];

createAdjMatrix(Adj, arr);

printAdjMatrix(Adj);

return 0;

2.Accept the graph as an adjacency matrix and check if the graph is undirected

#include <stdio.h>

#include <stdlib.h>

struct AdjListNode {

int dest;

struct AdjListNode* next;

};

struct AdjList {

struct AdjListNode* head;

};

struct Graph {

int V;

struct AdjList* array;

};
struct AdjListNode* newAdjListNode(int dest)

struct AdjListNode* newNode

= (struct AdjListNode*)malloc(

sizeof(struct AdjListNode));

newNode->dest = dest;

newNode->next = NULL;

return newNode;

struct Graph* createGraph(int V)

struct Graph* graph

= (struct Graph*)malloc(sizeof(struct Graph));

graph->V = V;

graph->array = (struct AdjList*)malloc(

V * sizeof(struct AdjList));

int i;

for (i = 0; i < V; ++i)

graph->array[i].head = NULL;

return graph;}

void addEdge(struct Graph* graph, int src, int dest)

struct AdjListNode* check = NULL;

struct AdjListNode* newNode = newAdjListNode(dest);


if (graph->array[src].head == NULL) {

newNode->next = graph->array[src].head;

graph->array[src].head = newNode;

else {

check = graph->array[src].head;

while (check->next != NULL) {

check = check->next;

check->next = newNode;

newNode = newAdjListNode(src);

if (graph->array[dest].head == NULL) {

newNode->next = graph->array[dest].head;

graph->array[dest].head = newNode;

else {

check = graph->array[dest].head;

while (check->next != NULL) {

check = check->next;

check->next = newNode;

}
void printGraph(struct Graph* graph)

int v;

for (v = 0; v < graph->V; ++v) {

struct AdjListNode* pCrawl = graph->array[v].head;

printf("\n Adjacency list of vertex %d\n head ", v);

while (pCrawl) {

printf("-> %d", pCrawl->dest);

pCrawl = pCrawl->next;

printf("\n");

int main()

int V = 5;

struct Graph* graph = createGraph(V);

addEdge(graph, 0, 1);

addEdge(graph, 0, 4);

addEdge(graph, 1, 2);

addEdge(graph, 1, 3);

addEdge(graph, 1, 4);

addEdge(graph, 2, 3);

addEdge(graph, 3, 4);
printGraph(graph);

return 0;

You might also like