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

Final Ece Lab Manual

The document describes programs implementing various data structures and algorithms in C language. It includes programs for arrays, functions, pointers, structures, file handling, and array implementation of list abstract data type (ADT). The array implementation of list ADT program uses functions like insert, locate, retrieve, delete, make null, first etc. to perform operations on dynamically allocated array representing a list. The file handling program demonstrates how to create a file, write data to it and close the file after writing.

Uploaded by

jithendrapkkvr
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)
33 views

Final Ece Lab Manual

The document describes programs implementing various data structures and algorithms in C language. It includes programs for arrays, functions, pointers, structures, file handling, and array implementation of list abstract data type (ADT). The array implementation of list ADT program uses functions like insert, locate, retrieve, delete, make null, first etc. to perform operations on dynamically allocated array representing a list. The file handling program demonstrates how to create a file, write data to it and close the file after writing.

Uploaded by

jithendrapkkvr
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/ 74

EX.

NO:1
PROGRAM USING STATEMENTS, EXPRESSIONS, DECISION MAKING AND
DATE: ITERATIVE STATEMENTS

AIM:
To write a program in C to implement statements, Expressions, Decision Making & Iterative
Statements.

ALGORITHM:
i) START the program
ii) Take integer variable A
iii) Assign value to the variable
iv) Check if A is greater than or equal to 0
v) If true print A is positive
vi) If false print A is negative
vii) STOP the program

PROGRAM FOR STATEMENT:


#include <stdio.h>
void main()
{
Int num;
printf("Input a number :");
scanf("%d", &num);
if (num>= 0)
printf("%d is a positive number \n", num);
else
printf("%d is a negative number \n", num);
}

OUTPUT:
Input a number : 15
15 is a positive number

Input a number : 10
-10 is a negative number
PROGRAM FOR EXPRESSION:
ALGORITHM:
i) Start the program
ii) Ask the user to enter an integer to find the factorial
iii) Read the integer and assign it to a variable
iv) From the value of the integer up to 1, multiply each digit and update the final value
v) The final value at the end of all the multiplication till 1 is the factorial
vi) End program

Program:
#include<stdio.h>
#include<conio.h>
int main()
{
int x,fact=1,n;
clrscr();
printf("Enter a number to find factorial: ");
scanf("%d",&n);
for(x=1;x<=n;x++)
fact=fact*x;
printf("Factorial of %d is: %d",n,fact);
getch();
return 0;
}
Output:
Enter a number to find Factorial: 5
Factorial of 5 is:120

PROGRAM FOR DECISION MAKING & ITERATIVE STATEMENT:


ALGORITHM:
1. Start the program
2. int i, sum = 0, n
3. input positive number
4. i = 0
do
sum = sum + i
i=i+1
5. iterate the value of i< = n
6. display the sum of the first natural number.
7. End the Program.

Program:
#include <stdio.h>
#include<conio.h>
int main() {
int n, i, sum = 0;
clrscr();
printf("Enter a positive integer: ");
scanf("%d", &n);
i = 1;
while (i<= n) {
sum += i;
++i;
}
printf("Sum = %d", sum);
getch();
return 0;
}

Output
Enter a positive integer: 100
Sum = 5050

RESULT:
Thus a C programming using statements, expressions, decision making and iterative statements was
implemented successfully.
EX.NO: 2
PROGRAM USING FUNCTIONS AND ARRAYS
DATE:

AIM:
To write a program in C to implement Functions & Arrays.

ALGORITHM:
Step 1: Start the program
Step 2: Take the total number of observations as input from the user.
Step 3: Dynamically allocate memory to an array of size equal to the total number of observations
entered by the user.
Step 4: Take the value of all n observations as input from the user.
Step 5: Calculate the sum of all the n observations using for loop.
Step 6: Calculate average using the formula average=sum/n.
Step 7: Return the values and print the result.

PROGRAM:
#include <stdio.h>
float findAverage(int [], int);
int main(void) {
int score[5] = {90, 80, 70, 75, 85};
int papers = 5;
float avg = findAverage(score, papers);
printf("Average: %f\n", avg);
return 0;
}
float findAverage(int arr[], int size) {
// variables
int i;
float sum = 0, avg = 0;
// find total
for (i = 0; i < size; i++) {
sum += arr[i];
}
// find average
avg = sum / size;
// return average
return avg;
}

OUTPUT:
Average=80.00000

RESULT:
Thus a C programming for Functions & arrays was implemented successfully.
EX.NO:03
PROGRAMS USING POINTERS AND STRUCTURES
DATE:

AIM:
To write a program in C to implement Pointers & structures concept.

ALGORITHM:
Step 1: Start the program
Step 2: Initialize the structure variables
Step 3: Access the members of the structure using dot operator(.)
Step 4: Create pointers for the structure & assign the variable to the pointer.
Step 5: Accessing the members of a structure via pointer
Step 6: Stop the program.

PROGRAM:
#include<stdio.h>
struct person{
int age;
float weight;
};
int main(){
struct person *personPtr, person1;
personPtr = &person1;
printf("Enter age: ");
scanf("%d", &personPtr->age);
printf("Enter weight: ");
scanf("%f", &personPtr->weight);
printf("Displaying:");
printf("Age: %d", personPtr->age);
printf("weight: %f", personPtr->weight);
return 0;
}

OUTPUT:
Enter age: 45
Enter weight: 60
Displaying:
Age: 45
weight: 60.000000

Result:
Thus a C programming has been verified & implemented successfully by using the pointers &
structures concept.
EX NO: 4 PROGRAM TO CREATE A FILE AND WRITE DATA INTO FILE

Date:

AIM:
To write a C program to create a file & Write data into a file by using File Handling.

ALGORITHM:
Step 1: Declare a FILE type pointer variable to store reference of file, say FILE * fPtr = NULL;.
Step 2: Create or open file using fopen() function.
fopen() function is used to open a file in different mode. You can open a file in basic three
different mode r(read), w(write) and a(append) mode. We will use w file mode to create a file.
fopen("file-name", "read-mode"); function accepts two parameter first file name to
read/create/write/append data, next is file open mode. On success it return pointer to FILE type
otherwise NULL pointer.
Step 3: Input data from user to write into file, store it to some variable say data.
C provides several functions to perform IO operation on file. For this post to make things
simple I will use fputs() function to write data to file. fputs("content-to-write", stream) function
accepts two parameters.
First string data to write into file, next pointer to FILE type that specifies where to write data.
Use fputs() function to write data to fPtr i.e. perform fputs(data, fPtr);.
Step 4: Finally after completing all operations you must close file, to save data written on file.
Use fclose(fPtr) function to close file.

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#define DATA_SIZE 1000
int main()
{
char data[DATA_SIZE];

FILE * fPtr;
fPtr = fopen("data/file1.txt", "w");
if(fPtr == NULL)
{
printf("Unable to create file.\n");
exit(EXIT_FAILURE);
}
printf("Enter contents to store in file : \n");
fgets(data, DATA_SIZE, stdin);
fputs(data, fPtr);
fclose(fPtr);
printf("File created and saved successfully. :) \n");
return 0;
}
OUTPUT:
Enter contents to store in file :
Hurray!!! I learned to create file in C programming.
I also learned to write contents to file.
Next, I will learn to read contents from file on Codeforwin. Happy coding ;)
File created and saved successfully. :)

RESULT:
Thus by using C Programming the File handling operations has been used and executed successfully.
EX.NO:6 ARRAY IMPLEMENTATION OF LIST ADT
DATE:

AIM:
To implement C program array implementation of List ADT.

ALGORITHM:
STEP 1: Insert (x, p, L) Insert x at position p in list L. ...
STEP 2: Locate (x, L) returns position of x on L. ...
STEP 3: Retrieve (p, L) returns element at position p on L. ...
STEP 4: Delete (p, L) delete element at position p in L. ...
STEP 5: Next (p, L) ...
STEP 6: Prev (p, L) ...
STEP 7: Makenull (L) ...
STEP 8: First (L)

PROGRAM:
#include"Larray.h"
#include<stdlib.h>
void main()
{
LIST L=NULL;
POSITION P;
int a,choice,ch,element;
clrscr();
printf("\n\n1.Create\n2.Insert\n3.Delete\n4.Display\n5.MakeEmpty\n6.Find\n7.IsEmpty\n8.IsFull\n9.
Deletelist\n10.Exit\n");
A:
printf("\n Enter Ur Option:\t");
scanf("%d",&choice);
switch(choice)
{
case 1:
if(L==NULL)
L=Createlist(5);
else
printf("\nList is already created");
break;
case 2:
if(L==NULL)
printf("\nList is not yet created");
else
{
printf("\nEnter the Element to insert:\t");
scanf("%d",&element);
if(L->size==0)
Insert(element,L,0);
else
{
printf("\n where u want to insert?\t1:Front\t2:Back\t3:middle\t::: ");
scanf("%d",&ch);
if(ch==1)
Insert(element,L,0);
else
if(ch==2)
Insert(element,L,L->size);
else
if(ch==3)
{
printf("\nWhere you want to insert:\t");
scanf("%d",&a);
P=Find(a,L);
if(P<L->size)
Insert(element,L,P);
else
printf("\nElement is not in the list");
}
else
printf("\n Ur choice is not available");
}
}
break;
case 3:
if(L==NULL)
printf("\nList is not yet created");
if(Isempty(L))
printf("\nList is empty");
else
{
printf("\nEnter the element to delete:\t");
scanf("%d",&a);
Delete(a,L);
}
break;
case 4:
if(L==NULL)
printf("\nList is not yet created");
else
if(Isempty(L))
printf("\nList is empty");
else
{
printf("\nElements present in the list are:");
Display(L);
}
break;
case 5:
if(L==NULL)
printf("\n List is not yet created ");

else
MakeEmpty(L);
break;
case 6:
if(L==NULL)
printf("\n Not yet created");
else
if(Isempty(L))
printf("\n List is empty");
else
{
printf("\n which element is to find:\t");
scanf("%d",&a);
P=Find(a,L);
printf("\n Element is at %d\t[0 to 4 means present]\t[5 means not present]",P);
}
break;
case 7:
if(L==NULL)
printf("\n Not yet created");
else
if(Isempty(L))
printf("\n List is empty");
else
printf("\n List is not empty");
break;
case 8:
if(L==NULL)
printf("\n Not yet created");
else
if(Isfull(L))
printf("\n List is FULL");
else
printf("\n List is not FULL");
break;
case 9:
if(L==NULL)
printf("\n Not yet created");
else
{
L=Deletelist(L);
printf("\n List is Deleted");
}
break;
case 10:
exit (0);
break;
default:
printf("\n\n *******WRONG ENTRY*******");
break;
}
goto A;
}
OUTPUT:
1.Create
2.Insert
3.Delete
4.Display
5.MakeEmpty
6.Find
7.IsEmpty
8.IsFull
9.Deletelist
10.Exit

Enter Ur Option: 1
List is created successfully

Enter Ur Option: 2
Enter the element to insert: 300

Enter Ur Option: 2
Enter the element to insert: 100
Where U want to insert? 1.Front 2.Back 3.Middle ::::: 1

Enter Ur Option: 2
Enter the element to insert: 200
Where U want to insert? 1.Front 2.Back 3.Middle ::::: 3

Enter Ur Option: 2
Enter the element to insert: 400
Where U want to insert? 1.Front 2.Back 3.Middle ::::: 2

Enter Ur Option: 2
Enter the element to insert: 500
Where U want to insert? 1.Front 2.Back 3.Middle ::::: 2

Enter Ur Option: 2
Enter the element to insert: 600
Where U want to insert? 1.Front 2.Back 3.Middle ::::: 1
List is Full

Enter Ur Option: 4
Elements present in the list are
100
200
300
400
500
Enter Ur Option: 7
List is not empty
Enter Ur Option: 6
Which element is to find: 500
Element at 4 [0 to 4 – present] [5 – not present]
Enter Ur Option: 3
Enter the element to delete: 300
Enter Ur Option: 4
Elements present in the list are:
100
200
400
500

Enter Ur Option: 8
List is not Full

Enter Ur Option: 5
Now List becomes Empty

Enter Ur Option: 9
List is Deleted

Enter Ur Option: 2
List is not yet created

Enter Ur Option: 12
*******WRONG ENTRY*******

Enter Ur Option: 10

RESULT:
Thus the C program to implement c program for using list ADT has successfully executed.
EX.NO:7A ARRAY IMPLEMENTATION OF STACK ADTs
DATE:

AIM:
Aim is to write a program in C to implement the stack ADT using array concept that performs all the
operations of stack.

ALGORITHM:
STEP 1: Define an array to store the element.
STEP 2: Get the users’ choice.
STEP 3: If the option is 1 perform creation operation and goto step4. If the option is 2 perform
insertion operation and goto step5. If the option is 3 perform deletion operation and goto step6. If the
option is 4 perform display
operation and goto step7.
STEP 4: Create the stack. Initially get the limit of stack and the get the items. If the limit of stack is
exceeds print the message unable to create the stack.
STEP 5: Get the element to be pushed. If top pointer exceeds stack capacity. Print Error message
that the stack overflow. If not, increment the top pointer by one and store the element in the position
which is denoted by top pointer.
STEP 6: If the stack is empty, then print error message that stack is empty. If not fetch the element
from the position which is denoted by top pointer and decrement the top pointer by one
STEP 7: If the top value is not less than the 0 the stack is display otherwise print the message
“stack is empty”.
STEP 8: Stop the execution.

PROGRAM:
#include<stdio.h>
#include<conio.h>
#define max 20
int opt, a[20],i,top=0,n;
void main()
{
void create(),push(),pop(),disp();
int wish;
do
{
clrscr();
printf("\nMENU");
printf("\n1.Create\n2.Push\n3.pop\n4.Display\n5.Exit\n");
printf("\nEnter your option");
scanf("%d",&opt);
switch(opt)
{
case 1:create();break;
case 2:push();break;
case 3:pop();break;
case 4:disp();break;
case 5:exit();break;
}
printf("\nDo u want to continue(1/0):");
scanf("%d",&wish);
}while(wish==1);}
void create()
{
printf("\n Enter the limit of stack");
scanf("%d",&n);if(n<max)
{
printf("\nEnter the items");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
top=n-1;
}
else
printf("\nUnable to create the stack");
}
void push()
{
int x;
if(top<max){
printf("\nEnter the element to be pushed:");
scanf("%d",&x);
top=top+1;
a[top]=x;
n=top;
}
else
printf("\n Stack is full");
}
void pop()
{
if(top<0)
printf("\n Stack is empty");
else
{
printf("\nThe element popped is %d",a[top]);
top=top-1;
n=top;
}}
void disp()
{
if(top<0)
printf("\n Stack is empty");
else
{
printf("\n The elements in the stack are:");
for(i=top;i>=0;i--)
printf("\n%d",a[i]);
}
}

OUTPUT:

RESULT:
Thus a C program for Stack using ADT was implemented successfully.
EX.NO:7B ARRAY IMPLEMENTATION OF QUEUE ADTs
DATE:

AIM:
To write a program for Queue using array implementation.

ALGORITHM:
1. Define a array which stores queue elements.
2. The operations on the queue are
a) INSERT data into the queue
b) DELETE data out of queue
3. INSERT DATA INTO queue
i) Enter the data to be inserted into queue.
ii) If TOP is NULL
a) The input data is the first node in queue.
The link of the node is NULL. TOP points to that node.
iii) If TOP is NOT NULL
b) The link of TOP points to the new node. TOP points to that node.
4. DELETE DATA FROM queue
i) If TOP isNULL, the queue is empty
ii) If TOP is NOT NULL
The link of TOP is the currentTOP. The pervious TOP is popped from queue.

5. The queue represented by linkedlist is traversed to display its content.

PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define SIZE 5
int front = - 1;
int rear = - 1;
int q[SIZE];
void insert( );
void del( );
void display( );
void main( )
{
int choice;
do
{
printf("\t Menu");
printf("\n 1. Insert");
printf("\n 2. Delete");
printf("\n 3. Display ");
printf("\n 4. Exit");
printf("\n Enter Your Choice:");
scanf("%d", &choice);
switch(choice)
{
case 1:
insert( ); display( ); break;
case 2:
del( ); display( ); break;
case 3:display( );
break;
case 4:
printf("End of Program....!!!!");
exit(0);
}}while(choice != 4);}
void insert( )
{
int no;
printf("\n Enter No.:");
scanf("%d", &no);
if(rear < SIZE - 1)
{
q[++rear]=no;
if(front == -1)
front=0;// front=front+1;
}
else
{
printf("\n Queue overflow");
}}
void del( )
{
if(front == - 1)
{
printf("\n Queue Underflow");
return;
}
else
{
printf("\n Deleted Item:-->%d\n", q[front]);
}
if(front == rear)
{
front = - 1;
rear = - 1;
}
else
{front = front + 1;
}}
void display( )
{
int i;
if( front == - 1)
{
printf("\nQueue is empty....");
return;
}
for(i = front; i<=rear; i++)
printf("\t%d",q[i]);}
OUTPUT:

RESULT:
Thus a C program for Queue using ADT was implemented successfully
Ex No:8A PROGRAM FOR THE IMPLEMENTATION OF LIST ADT
Date:

Aim:
To write a c program for the implementation of LIST ADT.

Algorithm:
Step 1: The first step of creating linked list of n nodes starts from defining node structure.
Step 2: Input number of nodes to create from user, store it in some variable say n.
Step 3: Declare two more helper variable of node type, say struct node *newNode, *temp;.
If n > 0 then, create our first node i.e. head node. Use dynamic memory allocation to allocate
memory for a node. Say head = (struct node*)malloc(sizeof(struct node));.
If there is no memory to allocate for head node i.e. head == NULL. Then print some error
message and terminate program, otherwise move to below step.
Step 4: Input data from user and assign to head using head->data = data;.
Step 5: At first head node points to NULL. Hence, assign head->next = NULL;.
Step 6: Allocate memory and assign memory reference to newNode, say newNode = (struct
node*)malloc(sizeof(node));.
Step 7: If memory got allocated successfully then read data from user and assign to data section of
new node. Say newNode->data = data;.
Step 8: Make sure new node points to NULL.
Step 9: Now link previous node with newly created node i.e. temp->next = newNode;.
Step 10: Make current node as previous node using temp = temp->next;.

Program:
#include<stdio.h>
#include<stdlib.h>
void create();
void display();
void insert_begin();
void insert_end();
void insert_pos();
void delete_begin();
void delete_end();
void delete_pos();
struct node* head = NULL;
struct node
{
int data;
struct node* next;
};
int main()
{
int choice;
while(1)
{
printf("\n*****\n");
printf("0. Create\n");
printf("1. display\n");
printf("2. Insert Node at beginning\n");
printf("3. Insert Node in specific position\n");
printf("4. Insert Node at end of LinkedList\n");
printf("5. Delete Node at beginning\n");
printf("6. Delete Node at end\n");
printf("7. Delete Node at position\n");
printf("8. ** To exit **");

printf("\n Enter your choice: ");


scanf("%d",&choice);
switch(choice)
{
case 0: create();
break;
case 1: display();
break;
case 2: insert_begin();
break;
case 3: insert_pos();
break;
case 4: insert_end();
break;
case 5: delete_begin();
break;
case 6: delete_end();
break;
case 7: delete_pos();
break;
case 8: exit(0);
default:printf("\n Wrong Choice");
break;
}
}
}
//creates a node
void create()
{
struct node* temp;
//creating new node
temp = (struct node*)malloc(sizeof(struct node));
printf("Enter node data: ");
scanf("%d",&temp->data);
temp->next = NULL;
if(head==NULL) {
head = temp;
}
else{
struct node* ptr = head;
while(ptr->next!=NULL)
{
ptr = ptr->next;
}
ptr->next = temp; //inserting at end of List
}
}
// prints the entire LinkedList
void display()
{
if(head==NULL)
{
printf("Linked List is Empty\n");
return;
}
printf("LinkedList: ");
struct node* ptr = head;
while(ptr!=NULL) // start from first node
{
printf("%d ",ptr->data);
ptr = ptr->next;
}
printf("\n");
}
// to insert node at start of LinkedList
void insert_begin()
{
struct node* temp;
// creating a new node
temp = (struct node*)malloc(sizeof(struct node));
printf("Enter node data: ");
scanf("%d",&temp->data);
temp->next = NULL;
if(head==NULL)
{
head = temp;
return;
}
else
{
temp->next = head; //point it to old head node
head = temp; //point head to new first node
}
}
// to insert node at given position
void insert_pos()
{
struct node* temp;
// creating a new node
temp = (struct node*)malloc(sizeof(struct node));
printf("Enter node data: ");
scanf("%d",&temp->data);
temp->next = NULL;
if(head==NULL) // if list empty we return
{
head = temp;
return;
}
else
{
struct node* prev_ptr;
struct node* ptr = head;
int pos;
printf("Enter position: ");
scanf("%d",&pos);
for(int i=0;i<pos;i++)
{
prev_ptr = ptr;
ptr = ptr->next;
}
//new node pointing to node in that pos
temp->next = ptr;
//prevptr pointing to new node
prev_ptr->next = temp;
}
}
// to insert node at end of LinkedList
void insert_end()
{
struct node* temp;
//creating new node
temp = (struct node*)malloc(sizeof(struct node));
printf("Enter node data: ");
scanf("%d",&temp->data);
temp->next = NULL;
if(head==NULL)
{
head = temp; //if list is empty, we return
return;
}
else{
struct node* ptr = head;
while(ptr->next!=NULL)
{
ptr = ptr->next;
}
// tail node pointing to new node
ptr->next = temp;
}
}
// to delete first node of LinkedList
void delete_begin()
{
if(head==NULL) //if List is empty we return
{
printf("Linked List is empty | Nothing to delete \n");
return;
}
else
{
struct node* ptr = head;
head = head->next; // head node pointing to second node
free(ptr); // deleting prev head node
printf("Node Deleted \n");
}
}
// to delete last node of LinkedList
void delete_end()
{
if(head==NULL) //if List is empty we return
{
printf("Linked List is empty | Nothing to delete \n");
return;
}
else if(head->next==NULL)
{
struct node* ptr = head;
head = ptr->next;
free(ptr);
}
else
{
struct node* ptr = head;
struct node* prev_ptr = NULL;
while(ptr->next!=NULL)// traverse till last but one node
{
prev_ptr = ptr;
ptr = ptr->next;
}
prev_ptr->next = NULL; // next field of last but one field is made as NULL
free(ptr); // deleting last node
}
}
// to delete node at given position
void delete_pos()
{
int pos;
printf("Enter node position to delete: ");
scanf("%d",&pos);
struct node* ptr=head;
if(head==NULL) //we return if List is empty
{
printf("Linked List is empty \n");
return;
}
else if(pos == 0)
{
ptr = head;
head=ptr->next; // head pointing to second node
free(ptr); // deleting old first node
}
else
{
struct node* prev_ptr;
for(int i=0;i<pos;i++)
{
prev_ptr = ptr;
ptr = ptr->next;
}
prev_ptr->next = ptr->next; //prev node pointing to pos+1 node
free(ptr); //deleting node at pos
}
}

Output:
0. Create
1. display
2. Insert Node at beginning
3. Insert Node in specific position
4. Insert Node at end of LinkedList
5. Delete Node at beginning
6. Delete Node at end
7. Delete Node at position
8. ** To exit **
Enter your choice: 0
Enter node data: 12
*****

0. Create
1. display
2. Insert Node at beginning
3. Insert Node in specific position
4. Insert Node at end of LinkedList
5. Delete Node at beginning
6. Delete Node at end
7. Delete Node at position
8. ** To exit **
Enter your choice: 1
LinkedList: 12
*****

0. Create
1. display
2. Insert Node at beginning
3. Insert Node in specific position
4. Insert Node at end of LinkedList
5. Delete Node at beginning
6. Delete Node at end
7. Delete Node at position
8. ** To exit **
Enter your choice: 2
Enter node data: 13
*****

0. Create
1. display
2. Insert Node at beginning
3. Insert Node in specific position
4. Insert Node at end of LinkedList
5. Delete Node at beginning
6. Delete Node at end
7. Delete Node at position
8. ** To exit **
Enter your choice: 3
Enter node data: 25
Enter position: 1

*****
0. Create
1. display
2. Insert Node at beginning
3. Insert Node in specific position
4. Insert Node at end of LinkedList
5. Delete Node at beginning
6. Delete Node at end
7. Delete Node at position
8. ** To exit **
Enter your choice: 4
Enter node data: 39
*****

0. Create
1. display
2. Insert Node at beginning
3. Insert Node in specific position
4. Insert Node at end of LinkedList
5. Delete Node at beginning
6. Delete Node at end
7. Delete Node at position
8. ** To exit **
Enter your choice: 5
Node Deleted
*****

0. Create
1. display
2. Insert Node at beginning
3. Insert Node in specific position
4. Insert Node at end of LinkedList
5. Delete Node at beginning
6. Delete Node at end
7. Delete Node at position
8. ** To exit **
Enter your choice: 6
Last Node Deleted
*****

0. Create
1. display
2. Insert Node at beginning
3. Insert Node in specific position
4. Insert Node at end of LinkedList
5. Delete Node at beginning
6. Delete Node at end
7. Delete Node at position
8. ** To exit **
Enter your choice: 7
Enter node position to delete: 2
Node at pos: 2 deleted

RESULT:
Thus the implementation of C program for LIST ADT has been executed successfully.
EX. NO: 8B STACK ADT USING LINKED LIST
DATE:
AIM:
To write a C program for stack ADT using linked list implementation.
ALGORITHM:
1. Define a struct for each node in the stack. Each node in the stack contains data
and link to the next node. TOP pointer points to last node inserted in the stack.
2. The operations on the stackare
a. PUSH data into thestack
b. POP data out ofstack
3. PUSH DATA INTOSTACK
a. Enter the data to be inserted into stack.
b. If TOP isNULL
i. The input data is the first node instack.
ii. The link of the node isNULL.
iii. TOP points to thatnode.
c. If TOP is NOTNULL
i. The link of TOP points to the newnode.
ii. TOP points to thatnode.
4. POP DATA FROMSTACK
a. 4a.If TOP isNULL
i. the stack isempty
b. 4b.If TOP is NOTNULL
i. The link of TOP is the currentTOP.
ii. The pervious TOP is popped fromstack.
5. The stack representedby linked list is traversed to display its content.

PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int data;
struct node *next;
}*top,*new1,*first;
void main()
{
int wish,opt;
void create(),push(),pop(),view();
do
{
clrscr();
printf("Stack using linked list menu");
printf("\n1.Create\n2.Push\n3.Pop\n4.View\n5.Exit\n");
printf("\nEnter your option(1,2,3,4,5):");
scanf("%d",&wish);
switch(wish)
{
case 1: create(); break;
case 2: push(); break;
case 3: pop(); break;
case 4: view(); break;
case 5: exit(0);
}
printf("\nDo you wnat to continue(0/1):");
scanf("%d",&opt);
}while(opt==1);
}
void create()
{
int ch;
top=(struct node*)malloc(sizeof(struct node));
top->next=NULL;
do
{
clrscr();
printf("Enter the data:\n");
scanf("%d",&top->data);
printf("Do you want to insert another(1/0)\n");
scanf("%d",&ch);
if(ch==1)
{
new1=(struct node*)malloc(sizeof(struct node));
new1->next=top;
top=new1;
first=top;
}
else
break;
}while(ch==1);
}
void push()
{
top=first;
new1=(struct node*)malloc(sizeof(struct node));
printf("Enter the element to be pushed:");
scanf("%d",&new1->data);
new1->next=top;
top=new1;
first=top;
}
void pop()
{
clrscr();
top=first;
if(top==NULL)
printf("\n Stack is empty");
else
{
printf("\nThe element popped out from stack is %d",top->data);
top=top->next;
first=top;
}}
void view()
{
printf("\nStack contents\n");
while(top->next!=NULL)
{printf("%d->",top->data);
top=top->next;}
printf("%d\n",top->data);
getch();}

OUTPUT:
RESULT:
Thus the C program for Linked list implementation of Stack ADT was created, executed and output
was verified successfully
EX. NO :8C QUEUE ADT USING LINKED LIST
DATE:
AIM:
To write a C program for Queue using Linked implementation.
ALGORITHM:
1. Define a struct for each node in the queue. Each node in the queue

contains data and link to the next node. Front and rear pointer points to first
and last node inserted in the queue.

2. The operations on the queue are


a. INSERT data into the queue
b. DELETE data out of queue
3. INSERT DATA INTO queue
a. Enter the data to be inserted into queue.
b. If TOP is NULL
i. The input data is the first node in queue. ii. The link of the node
is NULL.
iii. TOP points to that node. c. If TOP is NOTNULL
i. The link of TOP points to the new node.
ii. TOP points to that node.
4. DELETE DATA FROM queue

i) If TOP is NULL-the queue is empty


b. If TOP is NOT NULL
i. The link of TOP is the current TOP.
ii. The pervious TOP is popped from queue.
5. The queue represented by linked list is traversed to display its content.

PROGRAM:
#include<stdio.h>
#include<conio.h>
struct node
{
int info;
struct node *link;
}*front = NULL, *rear = NULL;
void insert();
void delet();
void display();
int item;
void main()
{
int ch;
do
{
printf("\n\n1.\tEnqueue\n2.\tDequeue\n3.\tDisplay\n4.\tExit\n");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1:
insert();
break;
case 2:
delet();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("\n\nInvalid choice. Please try again...\n");
}
} while(1);
getch();
}
void insert()
{
printf("\n\nEnter ITEM: ");
scanf("%d", &item);
if(rear == NULL)
{
rear = (struct node *)malloc(sizeof(struct node));
rear->info = item;
rear->link = NULL;
front = rear;
}
else{
rear->link = (struct node *)malloc(sizeof(struct node));
rear = rear->link;
rear->info = item;
rear->link = NULL;
}}
void delet(){
struct node *ptr;
if(front == NULL)
printf("\n\nQueue is empty.\n");
else{
ptr = front;
item = front->info;
front = front->link;
free(ptr);
printf("\nItem deleted: %d\n", item);
if(front == NULL)
rear = NULL;
}}
void display()
{
struct node *ptr = front;
if(rear == NULL)
printf("\n\nQueue is empty.\n");
else
{
printf("\n\n");
while(ptr != NULL)
{
printf("%d\t",ptr->info);
ptr = ptr->link;
}}}
OUTPUT:
RESULT:
Thus the C program for Linked list implementation of Queue ADT was created, executed and output
was verified successfully
EX. NO: 10 IMPLEMENTATION OF BINARY TREES
DATE:
AIM:
To write a C program to implementation of binary tree and its operations.
ALGORITHM:
1. A new binary tree is created and values are assigned
2. Write a function insert() in such a way that node and key will be two parameters and check for
below conditions,
a. If rootNode == NULL,
then return new node to calling function.
b. If rootNode => data < keyValue,
then call insert() with rootNode => rightNode and assign return value in rootNode =>
rightNode.
c. If rootNode => data > keyValue,
then call insert() with rootNode => leftNode and assign return value in rootNode =>
leftNode
3. Then finally, we can return original rootNode pointer to calling function.

Program:
#include <stdio.h>
#include <stdlib.h>
struct BTnode {
int data;
struct BTnode* leftNode;
struct BTnode* rightNode;
};
void inorder(struct BTnode* rootNode) {
if (rootNode == NULL) return;
inorder(rootNode->leftNode);
printf("%d ->", rootNode->data);
inorder(rootNode->rightNode);
}
void preorder(struct BTnode* rootNode) {
if (rootNode == NULL) return;
printf("%d ->", rootNode->data);
preorder(rootNode->leftNode);
preorder(rootNode->rightNode);
}
void postorder(struct BTnode* rootNode) {
if (rootNode == NULL) return;
postorder(rootNode->leftNode);
postorder(rootNode->rightNode);
printf("%d ->", rootNode->data);
}
struct BTnode* createNode(value) {
struct BTnode* newNode = malloc(sizeof(struct BTnode));
newNode->data = value;
newNode->leftNode = NULL;
newNode->rightNode = NULL;
return newNode;
}
struct BTnode* insertLeftNode(struct BTnode* rootNode, int value) {
rootNode->leftNode = createNode(value);
return rootNode->leftNode;
}
struct BTnode* insertRightNode(struct BTnode* rootNode, int value) {
rootNode->rightNode = createNode(value);
return rootNode->rightNode;
}
int main() {
struct BTnode* rootNode = createNode(7);
insertLeftNode(rootNode, 4);
insertRightNode(rootNode, 8);
insertLeftNode(rootNode->leftNode, 1);
insertRightNode(rootNode->rightNode, 5);
insertLeftNode(rootNode->leftNode, 6);
insertRightNode(rootNode->rightNode, 3);
printf("Inorder \n");
inorder(rootNode);
printf("\nPreorder \n");
preorder(rootNode);
printf("\nPostorder \n");
postorder(rootNode);
}

output:
Inorder: 6->4->7->8->3->
Preorder: 7-> 4-> 6-> 8-> 3->
Postorder: 6-> 4-> 3-> 8-> 7->

Result:
Thus the C program for binary tree was created, executed and output was verified successfully.
EX. NO: 11 IMPLEMENTATION OF BINARY SEARCH TREES
DATE:
AIM:
To write a C program to implementation of binary search tree.
ALGORITHM:
1. Declare function create(),search(),delete(),Display().
2. Create a structure for a tree contains left pointer and right pointer.
3. Insert an element is by checking the top node and the leaf
node and the operation will be performed.
4. Deleting an element contains searching the tree and deleting the item.
5. Display the Tree elements.

PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<alloc.h>
struct tree
{
int data;
struct tree *lchild;
struct tree *rchild;
}*t,*temp;
int element;
void inorder(struct tree *);
void preorder(struct tree *);
void postorder(struct tree *);
struct tree * create(struct tree *, int);
struct tree * find(struct tree *, int);
struct tree * insert(struct tree *, int);
struct tree * del(struct tree *, int);
struct tree * findmin(struct tree *);
struct tree * findmax(struct tree *);
void main()
{
int ch;
do
{
printf("\n\t\t\tBINARY SEARCH TREE");
printf("\n\t\t\t****** ****** ****");
printf("\nMain Menu\n");
printf("\n1.Create\n2.Insert\n3.Delete\n4.Find\n5.FindMin\n6.FindMax")
;
printf("\n7.Inorder\n8.Preorder\n9.Postorder\n10.Exit\n");
printf("\nEnter ur choice :");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter the data:");
scanf("%d",&element);
t=create(t,element);
inorder(t);
break;
case 2:
printf("\nEnter the data:");
scanf("%d",&element);
t=insert(t,element);
inorder(t);
break;
case 3:
printf("\nEnter the data:");
scanf("%d",&element);
t=del(t,element);
inorder(t);
break;
case 4:
printf("\nEnter the data:");
scanf("%d",&element);
temp=find(t,element);
if(temp->data==element)
printf("\nElement %d is at %d",element,temp);
else
printf("\nElement is not found");
break;
case 5:
temp=findmin(t);
printf("\nMax element=%d",temp->data);
break;
case 6:
temp=findmax(t);
printf("\nMax element=%d",temp->data);
break;
case 7:
inorder(t);
break;
case 8:
preorder(t);
break;
case 9:
postorder(t);
break;
case 10:
exit(0);
}
}while(ch<=10);
}
struct tree * create(struct tree*t, int elements)
{
t=(struct tree *)malloc(sizeof(struct tree));
t->data=element;
t->lchild=NULL;
t->rchild=NULL;
return t;
}
struct tree * find(struct tree *t, int element)
{
if(t==NULL)
return NULL;
if(element<t->data)
return(find(t->lchild,element));
else
if(element>t->data)
return(find(t->rchild,element));
else
return t;
}
struct tree *findmin(struct tree *t)
{
if(t==NULL)
return NULL;
else
if(t->lchild==NULL)
return t;
else
return(findmin(t->lchild));
}
struct tree *findmax(struct tree *t)
{
if(t!=NULL)
{
while(t->rchild!=NULL)
t=t->rchild;
}
return t;
}
struct tree *insert(struct tree *t,int element)
{
if(t==NULL)
{
t=(struct tree *)malloc(sizeof(struct tree));
t->data=element;
t->lchild=NULL;
t->rchild=NULL;
return t;
}
else
{
if(element<t->data)
{
t->lchild=insert(t->lchild,element);
}
else
if(element>t->data)
{
t->rchild=insert(t->rchild,element);
}
else
if(element==t->data)
{
printf("element already present\n");
}
return t;
}
}
struct tree * del(struct tree *t, int element)
{
if(t==NULL)
printf("element not found\n");
else
if(element<t->data)
t->lchild=del(t->lchild,element);
else
if(element>t->data)
t->rchild=del(t->rchild,element);
else
if(t->lchild&&t->rchild)
{
temp=findmin(t->rchild);
t->data=temp->data;
t->rchild=del(t->rchild,t->data);
}
else
{
temp=t;
if(t->lchild==NULL)
t=t->rchild;
else
if(t->rchild==NULL)
t=t->lchild;
free(temp);
}
return t;
}
void inorder(struct tree *t)
{
if(t==NULL)
return;
else
{
inorder(t->lchild);
printf("\t%d",t->data);
inorder(t->rchild);
}
}
void preorder(struct tree *t)
{
if(t==NULL)
return;
else
{
printf("\t%d",t->data);
preorder(t->lchild);
preorder(t->rchild);
}
}
void postorder(struct tree *t)
{
if(t==NULL)
return;
else
{
postorder(t->lchild);
postorder(t->rchild);
printf("\t%d",t->data);}}
OUTPUT:
RESULT:
Thus the C program for binary search tree was created, executed and output was verified successfully.
EX. NO: 12 A IMPLEMENTATION OF SEARCHING TECHNIQUES-LINEAR SEARCH

DATE:
AIM:
To write a C program to implementation of Linear search using searching techniques
ALGORITHM:
Step1: Take input of the element that is going to be searched. It can be referred to as a key element.
Step 2: Compare every element of the list with the key element starting from the leftmost end of the
list.
Step 3: If any element of the list matches with the key, return the index of that element.
Step 4: If the entire list has been traversed and none of the elements matched with the key, then return
-1, which specifies the key element is not present in the list.
Program:
#include<stdio.h>
int main() {
int arr[20], size, key, i, index;
printf("Number of elements in the list: ");
scanf("%d", &size);
printf("Enter elements of the list: ");
for (i = 0; i < size; i++)
scanf("%d", &arr[i]);
printf("Enter the element to search ie. key element: ");
scanf("%d", &key);
for (index = 0; index < size; index++)
if (arr[index] == key) // comparing each element with the key element
break;
if (index < size)
printf("Key element found at index %d", index);
else
printf("Key element not found");

return 0;
}
Output:
Number of elements in the list: 5
Enter elements of the list: 1 2 3 4 5
Enter the element to search ie. key element: 4
A key element found at index 3

Result:
Thus C program to implementation of Linear search using searching techniques has been executed
successfully
EX. NO: 12 B IMPLEMENTATION OF SEARCHING TECHNIQUES-BINARY SEARCH

DATE:
AIM:
To write a C program to implementation of Binary search using searching techniques
Algorithm:
Step 1: Binary Search Algorithm can be implemented in two ways which are discussed below.
1. Iterative Method
2. Recursive Method
Step 2: The recursive method follows the divide and conquer approach.
Step 3: The general steps for both methods are discussed below.
i) The array in which searching is to be performed is:
3456789
Let x = 4 be the element to be searched.
ii) Set two pointers low and high at the lowest and the highest positions respectively.
iii) Find the middle element mid of the array ie. arr[(low + high)/2] = 6.
iv) If x == mid, then return mid.Else, compare the element to be searched with m.
v) If x > mid, compare x with the middle element of the elements on the right side of mid.
This is done by setting low to low = mid + 1.
vi) Else, compare x with the middle element of the elements on the left side of mid. This is
done by setting high to high = mid - 1.
vii) Repeat steps 3 to 6 until low meets high.
viii) x = 4 is found.
Step 4: Stop the program.
Program:
#include <stdio.h>
int binarySearch(int array[], int x, int low, int high) {
while (low <= high) {
int mid = low + (high - low) / 2;

if (array[mid] == x)
return mid;

if (array[mid] < x)
low = mid + 1;

else
high = mid - 1;
}
return -1;
}

int main(void) {
int array[] = {3, 4, 5, 6, 7, 8, 9};
int n = sizeof(array) / sizeof(array[0]);
int x = 4;
int result = binarySearch(array, x, 0, n - 1);
if (result == -1)
printf("Not found");
else
printf("Element is found at index %d", result);
return 0;
}

Output:
Element is found at index 1

Result:
Thus C program to implementation of Binary search using searching techniques has been executed
successfully
EX.NO:13A IMPLEMENTATION OF INSERTION SORT

DATE:

AIM:

To write a C Program to implement insertion sort.


ALGORITHM:
Step 1 - If the element is the first element, assume that it is already sorted. Return 1.
Step2 - Pick the next element, and store it separately in a key.
Step3 - Now, compare the key with all elements in the sorted array.
Step 4 - If the element in the sorted array is smaller than the current element, then move to the next
element. Else, shift greater elements in the array towards the right.
Step 5 - Insert the value.
Step 6 - Repeat until the array is sorted.
PROGRAM:
#include <stdio.h>
void insert(int a[], int n)
{
int i, j, temp;
for (i = 1; i < n; i++)
{
temp = a[i];
j = i - 1;
while(j>=0 && temp <= a[j])
{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp;
}
}
void printArr(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}
int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
insert(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
return 0;
}

OUTPUT:

RESULT:
Thus the C Program for the insertion sort has been implemented & verified successfully.
EX.No:13B MERGE SORT
DATE:
AIM:
To write a C program to implement the concept of merge sort.
ALGORITHM:
STEP 1: Start.
STEP 2: First you divide the number of elements by 2 and seperate them as two.
STEP 3: Divide those two which are divided by 2.
STEP 4: Divide them until you get a single element.
STEP 5: Start comparing the starting two pair of elements with each other and place them in ascending
order
STEP 6: When you combine them compare them so that you make sure they are sorted.
STEP 7: When all the elements are compared the array will be surely sorted in an ascending order.
STEP 8:Stop
PROGRAM:
#include<stdio.h>
#include<conio.h>
void merge(int [],int ,int ,int );
void part(int [],int ,int );
void main()
{
int arr[30];
int i,size;
printf("\n\t------- Merge sorting method -------\n\n");
printf("Enter total no. of elements : ");
scanf("%d",&size);
for(i=0; i<size; i++)
{
printf("Enter %d element : ",i+1);
scanf("%d",&arr[i]);
}
part(arr,0,size-1);
printf("\n\t------- Merge sorted elements -------\n\n");
for(i=0; i<size; i++)
printf("%d ",arr[i]);
getch();
}
void part(int arr[],int min,int max)
{
int mid;
if(min<max)
{
mid=(min+max)/2;
part(arr,min,mid);
part(arr,mid+1,max);
merge(arr,min,mid,max);
}
}
void merge(int arr[],int min,int mid,int max)
{
int tmp[30];
int i,j,k,m;
j=min;
m=mid+1;
for(i=min; j<=mid && m<=max ; i++)
{
if(arr[j]<=arr[m])
{
tmp[i]=arr[j];
j++;
}
else
{
tmp[i]=arr[m];
m++;
}
}
if(j>mid)
{
for(k=m; k<=max; k++)
{
tmp[i]=arr[k];
i++;
}
}
else
{
for(k=j; k<=mid; k++)
{
tmp[i]=arr[k];
i++;
}
}
for(k=min; k<=max; k++)
arr[k]=tmp[k];
}
OUTPUT:

RESULT:
Thus a C program for the concept of merge sort was implemented successfully
EX.No:13C QUICK SORT
DATE:
AIM:
To write a C program to implement the concept of Quick sort.
Algorithm:
Step 1: Start the program
Step 2: Pick an element from an array, call it as pivot element.
Step 3: Divide an unsorted array element into two arrays.
Step 4: If the value less than pivot element come under first sub array, the remaining elements with
value greater than pivot come in second sub array.
QUICKSORT (array A, start, end)
{
1 if (start < end)
2{
3 p = partition(A, start, end)
4 QUICKSORT (A, start, p - 1)
5 QUICKSORT (A, p + 1, end)
6}
}

Program:
#include<stdio.h>
void quicksort(int number[25],int first,int last)
{
int i, j, pivot, temp;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j)
{
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}
int main()
{
int i, count, number[25];
printf("How many elements are u going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
quicksort(number,0,count-1);
printf("Order of Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}

Output:

Result:
Thus a C program for the concept of Quick sort was implemented & verified successfully
EX No: 14-A Implementation of Hashing- Linear Probing
Date:
Aim:
This is a C Program to Implement Hash Tables with Linear Probing.
Problem Description:
A hash table is a data structure used to implement an associative array, a structure that can map keys to
values. A hash table uses a hash function to compute an index into an array of buckets or slots. Due to
collision of keys while inserting elements into the hash table, idea of Linear Probing is used to probe
the through the subsequent elements (looping back) of array starting from hash code value (index of
the key) where key collision occurs.

Problem Solution
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 where not a single data has been entered
(means data does not exist in the hash table).
9. Exit

Program:
#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);

getch();

Output:
Implementation of Hash Table in C with Linear Probing
MENU-:
1. Inserting item in the Hashtable
2. Removing item from the Hashtable
3. Check the size of Hashtable
4. Display Hashtable

Please enter your choice-: 3


Size of Hashtable is-: 0
Do you want to continue-:(press 1 for yes) 1

Implementation of Hash Table in C with Linear Probing


MENU-:
1. Inserting item in the Hashtable
2. Removing item from the Hashtable
3. Check the size of Hashtable
4. Display Hashtable

Please enter your choice-: 1


Inserting element in Hashtable
Enter key and value-: 12 10

Key (12) has been inserted


Do you want to continue-:(press 1 for yes) 1

Implementation of Hash Table in C with Linear Probing


MENU-:
1. Inserting item in the Hashtable
2. Removing item from the Hashtable
3. Check the size of Hashtable
4. Display Hashtable

Please enter your choice-: 1


Inserting element in Hash table
Enter key and value-: 122 4

Key (122) has been inserted


Do you want to continue-:(press 1 for yes) 1

Implementation of Hash Table in C with Linear Probing


MENU-:
1. Inserting item in the Hashtable
2. Removing item from the Hashtable
3. Check the size of Hashtable
4. Display Hashtable
Please enter your choice-: 3
Size of Hashtable is-: 2
Do you want to continue-:(press 1 for yes) 1

Implementation of Hash Table in C with Linear Probing


MENU-:
1. Inserting item in the Hashtable
2. Removing item from the Hashtable
3. Check the size of Hashtable
4. Display Hashtable

Please enter your choice-: 4


Array[0] has no elements

Array[1] has no elements

Array[2] has elements-:


12 (key) and 10 (value)

Array[3] has elements-:


122(key) and 5(value)

Array[4] has no elements

Array[5] has no elements

Array[6] has no elements

Array[7] has no elements

Array[8] has no elements

Array[9] has no elements

Do you want to continue-:(press 1 for yes) 1


Implementation of Hash Table in C with Linear Probing
MENU-:
1. Inserting item in the Hashtable
2. Removing item from the Hashtable
3. Check the size of Hashtable
4. Display Hashtable
Please enter your choice-: 2
Deleting in Hashtable
Enter the key to delete-: 122

Key (122) has been removed

Do you want to continue-:(press 1 for yes) 1

Implementation of Hash Table in C with Linear Probing


MENU-:
1. Inserting item in the Hashtable
2. Removing item from the Hashtable
3. Check the size of Hashtable
4. Display Hashtable

Please enter your choice-: 2


Deleting in Hashtable
Enter the key to delete-: 56

This key does not exist

Do you want to continue-:( press 1 for yes) 2

RESULT:

Thus implementation of Hashing- Linear Hashing has been executed & implemented successfully.
EX No: 14-B Implementation of Hashing- Double Hashing
Date:
Aim:
This is a C Program to implement Hash Tables with Double Hashing.

Problem Description
A hash table is a data structure used to implement an associative array, a structure that can map keys to
values. A hash table uses a hash function to compute an index into an array of buckets or slots. To
prevent the collision of two keys ,the idea of Double Hashing is used. In case any collision occurs
when we just use traditional hash code evaluating function, another hash code is generated by some
other function and both the hash codes are used to find a free space by probing through array elements.

Problem Solution
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: Here, unlike quadratic and linear probing, we will first calculate another hash code of same key
using formula-: hashcode2 = primeNum – (key % primeNum) , where primeNum is largest prime
number less that array size
Probing formula after calculating hashcode2 -:
(hashcode1 + (h * hashcode2)) % arraySize , h = 1, 2, 3, 4 and so on
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 (using above formula) until we find key or an empty space where not a single
data has been entered
9. Exit

Program/Source Code
#include<stdio.h>
#include<conio.h>
#include<math.h>

struct data
{
int key;
int value;
};

struct hashtable_item
{
int flag;
struct data *item;

};

struct hashtable_item *array;


int max = 7;
int size = 0;
int prime = 3;

int hashcode1(int key)


{
return (key % max);
}

int hashcode2(int key)


{
return (prime - (key % prime));
}

void insert(int key, int value)


{
int hash1 = hashcode1(key);
int hash2 = hashcode2(key);

int index = hash1;

struct data *new_item = (struct data*) malloc(sizeof(struct data));


new_item->key = key;
new_item->value = value;
if (size == max)
{
printf("\n Hash Table is full, cannot insert more items \n");
return;
}

while (array[index].flag == 1) {
if (array[index].item->key == key)
{
printf("\n Key already present, hence updating its value \n");
array[index].item->value = value;
return;
}
index = (index + hash2) % max;
if (index == hash1)
{
printf("\n Add is failed \n");
return;
}
printf("\n probing \n");

}
array[index].item = new_item;
array[index].flag = 1;
size++;
printf("\n Key (%d) has been inserted \n", key);

}
void remove_element(int key)
{
int hash1 = hashcode1(key);
int hash2 = hashcode2(key);
int index = hash1;

if (size == 0)
{
printf("\n Hash Table is empty \n");
return;
}

while (array[index].flag != 0)
{
if (array[index].flag == 1 && array[index].item->key == key)
{
array[index].item = NULL;
array[index].flag = 2;
size--;
printf("\n Key (%d) has been removed \n", key);
return;
}
index = (index + hash2) % max;
if (index == hash1)
{
break;
}
}

printf("\n Key (%d) does not exist \n", key);

int size_of_hashtable()
{
return size;
}

void display()
{
int i;
for (i = 0; i < max; i++)
{
if (array[i].flag != 1)
{
printf("\n Array[%d] has no elements \n", i);
}
else
{
printf("\n Array[%d] has elements \n Key (%d) and Value (%d) \n", i, array[i].item->key,
array[i].item->value);
}
}
}

void init_array()
{
int i;
for(i = 0; i < max; i++)
{
array[i].item = NULL;
array[i].flag = 0;
}
prime = get_prime();
}

int get_prime()
{
int i,j;
for (i = max - 1; i >= 1; i--)
{
int flag = 0;
for (j = 2; j <= (int)sqrt(i); j++)
{
if (i % j == 0)
{
flag++;
}
}
if (flag == 0)
{
return i;
}
}
return 3;

}
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 Double Hashing.\n\n");
printf("MENU-: \n1.Inserting item in the Hash Table"
"\n2.Removing item from the Hash Table"
"\n3.Check the size of Hash Table"
"\n4.Display Hash Table"
"\n\n Please enter your choice-:");

scanf("%d", &choice);

switch(choice)
{
case 1:
printf("Inserting element in Hash Table\n");
printf("Enter key and value-:\t");
scanf("%d %d", &key, &value);
insert(key, value);
break;
case 2:
printf("Deleting in Hash Table \n Enter the key to delete-:");
scanf("%d", &key);
remove_element(key);
break;
case 3:
n = size_of_hashtable();
printf("Size of Hash Table is-:%d\n", n);
break;
case 4:
display();
break;
default:
printf("Wrong Input\n");
}
printf("\n Do you want to continue-:(press 1 for yes)\t");
scanf("%d", &c);
}while(c == 1);
getch();

Output:

Implementation of Hash Table in C with Double Hashing


MENU-:
1. Inserting item in the Hash Table
2. Removing item from the Hash Table
3. Check the size of Hash Table
4. Display Hash Table

Please enter your choice-: 3


Size of hash table is-: 0

Do you want to continue-:(press 1 for yes) 1

Implementation of Hash Table in C with Double Hashing


MENU-:
1. Inserting item in the Hash Table
2. Removing item from the Hash Table
3. Check the size of Hash Table
4. Display Hash Table

Please enter your choice-: 1


Inserting element in hash table
Enter key and value-: 12 1

Key (12) has been inserted

Do you want to continue-:(press 1 for yes) 1

Implementation of Hash Table in C with Double Hashing


MENU-:
1. Inserting item in the Hash Table
2. Removing item from the Hash Table
3. Check the size of Hash Table
4. Display Hash Table

Please enter your choice-: 1


Inserting element in Hash Table
Enter key and value-: 47 1
Key (47) has been inserted

Do you want to continue-:(press 1 for yes) 1

Implementation of Hash Table in C with Double Hashing


MENU-:
1. Inserting item in the Hash Table
2. Removing item from the Hash Table
3. Check the size of Hash Table
4. Display Hash Table

Please enter your choice-: 1


Inserting element in Hash Table
Enter key and value-: 61 1
Key (61) has been inserted

Do you want to continue-:(press 1 for yes) 1

Implementation of Hash Table in C with Double Hashing


MENU-:
1. Inserting item in the Hash Table
2. Removing item from the Hash Table
3. Check the size of Hash Table
4. Display Hash Table

Please enter your choice-: 3


Size of hash table is-: 3

Do you want to continue-:(press 1 for yes) 1

Implementation of Hash Table in C with Double Hashing


MENU-:
1. Inserting item in the Hash Table
2. Removing item from the Hash Table
3. Check the size of Hash Table
4. Display Hash Table

Please enter your choice-: 4

Array[0] has no elements

Array[1] has elements-:


47 (key) and 1 (value)

Array[2] has elements-:


61 (key) and 1 (value)

Array[3] has elements-:

Array[4] has no elements

Array[5] has elements-:


12 (key) and 1 (value)

Array[6] has no elements

Do you want to continue-:(press 1 for yes) 1


Implementation of Hash Table in C with Double Hashing
MENU-:
1. Inserting item in the Hash Table
2. Removing item from the Hash Table
3. Check the size of Hash Table
4. Display Hash Table

Please enter your choice-: 2


Deleting in hash table
Enter the key to delete-: 61
Key (61) has been removed
Do you want to continue-:(press 1 for yes) 1

Implementation of Hash Table in C with Double Hashing


MENU-:
1. Inserting item in the Hash Table
2. Removing item from the Hash Table
3. Check the size of Hash Table
4. Display a Hash Table

Please enter your choice-: 2


Deleting in hash table
Enter the key to delete-: 61

This key does not exist

Do you want to continue-:(press 1 for yes) 2

RESULT:

Thus implementation of Hashing- Double hashing has been executed & implemented successfully.

You might also like