SlideShare a Scribd company logo
PERI INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
CS3362- C PROGRAMMING AND DATA STRUCTURES LABORATORY2021-
REGULATIONS
BE ECE III SEMESTER
PERI Institute of Technology
Department of Computer Science and Engineering
VISION AND MISSION OF THE INSTITUTION
Vision of the Institute
PERI Institute of Technology visualizes growing in future to an internationally recognized seat of higher
learning in engineering, technology & science. It also visualizes being a research incubator for academicians,
industrialists and researchers from across the world, enabling them to work in an environment with the
sophisticated and state of the art equipment and amenities provided at the institute.
Mission of the Institute
In the process of realization of its Vision, PERIIT strives to provide quality technical education at
affordable cost in a challenging & stimulating environment with state-of-the-art facilities and a global team of
dedicated and talented academicians, without compromising in its core values of honesty, transparency and
excellence.
VISION AND MISSION OF THE DEPARTMENT
Vision of the Department
The vision of the department is to prepare industry-ready competent professionals with moral
values by imparting scientific knowledge and skill-based education.
Mission of the Department
a)To provide exposure of latest tools and technologies in the broad area of computing.
b)To promote research-based projects / activities in the emerging areas of technology.
c)To enhance Industry Institute Interaction program to get acquainted with corporate culture and to
develop entrepreneurship skills
d)To induce ethical values and spirit of social commitment.
CS3362 C PROGRAMMING AND DATA STRUCTURES LABORATORY L T P C
0 0 3 1.5
COURSE OBJECTIVES:
To develop applications in C.
To implement linear and non-linear data structures.
To understand the different operations of search trees.
To get familiarized to sorting and searching algorithms.
LIST OF EXPERIMENTS
1. Practice of C programming using statements, expressions, decision making and iterative
statements.
2. Practice of C programming using Functions and Arrays.
3. Implement C programs using Pointers and Structures.
4. Implement C programs using Files.
5. Development of real time C applications.
6. Array implementation of List ADT.
7. Array implementation of Stack and Queue ADTs.
8. Linked list implementation of List, Stack and Queue ADTs.
9. Applications of List, Stack and Queue ADTs.
10.Implementation of Binary Trees and operations of Binary Trees.
11. Implementation of Binary Search Trees.
12. Implementation of searching techniques.
13. Implementation of Sorting algorithms : Insertion Sort, Quick Sort, Merge Sort.
14. Implementation of Hashing – any two collision techniques.
TOTAL: 45 PERIODS
COURSE OUTCOMES:
At the end of the course, the students will be able to:
CO1 Use different constructs of C and develop applications.
CO2 Write functions to implement linear and non-linear data structure operations.
CO3 Suggest and use the appropriate linear / non-linear data structure operations for a given
problem.
CO4 Apply appropriate hash functions that result in a collision free scenario for data storage and
Retrieval.
CO5 Implement Sorting and searching algorithms for a given application
a) using ifb) using if else c) using if else ladder d) Nested if else e) Switch
case
a) Using if
Aim:
Write a program to check the variable using if condition
Algorithm:
1.Create a two integer variable x,y.
2.Assign the values to that variable.
3.check the condition.
4.condition is true print the value.
Program:
#include<stdio.h>
int main()
{
int x = 20;
int y = 22;
if (x<y)
{
printf("Variable x is less than y");
}
return 0;
}
OUTPUT:
Variable x is less than y
b)If else
Aim:
Write a program to check the variable using else if condition.
Algorithm:
1.Create a two integer variable x,y.
2.Assign the values to that variable.
3.Check the condition using else if.
4.Condition is true execute if otherwise execute else statement.
PROGRAM:
#include<stdio.h>
int main()
{
int age;
printf("Enter your age:");scanf("%d",&age);
if(age >=18)
{
printf("You are eligible for voting");
}
else
{
printf("You are not eligible for voting");
}
return0;
}
OUTPUT:
Enter your age:14
You are not eligible for voting
c)If else ladder:
Aim:
Write a program to implement a if else ladder
Alogrithm:
1.Create a variable x & y.
2.Get the values of X& Y from user.
3.First check the condition if it satisfies it will proceed to next level of if.
4.Again it checks the condition if it satisfies it will proceed to next level.
5.Print the values.
Program:
#include<stdio.h>
int main()
{
int x, y;
printf("Enter the value of x:");
scanf("%d",&x);
printf("Enter the value of y:");
scanf("%d",&y);
if(x>y)
{
printf("X is greater than yn");
}
if(x<y)
{
printf("X is less than yn");
}
if(x==y)
{
printf("X is equal to yn");
}
printf("End of Program");return0;
}
OUTPUT:
Enter the value of x:20Enter the value of y:20
X is equal to y
End of Program
d)Nested if else
Aim:
Write a program to implement a nested if else
Algorithm:
1. Declare the integer variable n and get the value for n.
2. First check the the value even or not and then print the value.
3. And the check in nested if else it is advisable by 4 or not.
4. If it is divisible by 4 means print it is even other print it is odd.
5. else check it is divisible by 3 or not.
6. If it is divisible by 3 means print it is printable by 3 otherwise print it is not divisible by 3.
PROGRAM:
#include <stdio.h>
int main()
{
int n;
scanf("%d",&n);
if (n % 2 == 0)
{
printf("Even ");
if (n % 4 == 0)
{
printf("and divisible by 4");
}
else
{
printf("and not divisible by 4");
}
}
else
{
printf("Odd ");
if(n % 3 == 0)
{
printf("and divisible by 3");
}
else
{
printf("and not divisible by 3");
}
}
return 0;
}
Input
14
Output
Even and not divisible by 4
e) switch case:
AIM:
Write a program to check whether the operator is available not in a switch case.
ALGORITHM:
1.Declare the two variable n1,n2.
2.Get the operator and operand from user.
3.Open the switch case operation.
4.In each case check whether the operator available or not.
5.Otherwise print the default case statement.
PROGRAM:
// Program to create a simple calculator
#include <stdio.h>
int main()
{
char operation;
double n1, n2;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operation);
printf("Enter two operands: ");
scanf("%lf %lf",&n1, &n2);
switch(operation)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);break;
case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);break;
// operator doesn't match any case constant +, -, *, /
default:
printf("Error! operator is not correct");
}
return 0;
}
OUTPUT:
Enter an operator (+, -, *, /): -
Enter two operands: 32.5 12.4
32.5 - 12.4 = 20.1
2.Practice a C programming using Functions & Array
a) Function with one dimensional array
AIM:
Write a program to implement a function using an one dimensional array.
ALGORITHM:
1. Declare the one dimensional array named score.
2.And assign the values to that array.
3.And declare integer variable score.
4.Declare the function findAverage with function variable int[], and int.
5.And write the function functions in a function.
6.In that functiondeclare the local variables int i, and float sum=0 and avg=07.
7.Check it in condition in for loop.
8.It will find the total and average of the given number.
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: %fn", avg);
return 0;
}
float findAverage(int arr[], int size)
{
// variablesint i;
float sum = 0, avg = 0;
// find total
for (i = 0; i < size; i++)
{
sum += arr[i];
}
// find average avg = sum / size;
// return average
}
b)Function with Twos dimensional array
AIM:
Write a program to implement a function using an two dimensional array.
ALGORITHM:
1. Declare the two dimensional array named score[5][3].
2. And assign the values to that array And declare integer variable score.
3. Declare the function print Average with function variable int[][3], and int.
4. And write the function functions in a function.
5. In that function declare the local variables int r,c, and float sum, avg.
6. Check it in condition in for loop.
7. It will find the total and average of the given number.
PROGRAM:
#include <stdio.h>
void printAverage(int [][3], int, int);
int main(void)
{
// variables
int ROWS = 5, COLS = 3;
int score[5][3] = {
{60, 70, 80},
{90, 50, 70},
{80, 75, 75},
{90, 85, 81},
{60, 75, 80}
};
printAverage(score, ROWS, COLS);
return 0;
}
void printAverage(int arr[][3], int rows, int cols)
{
// variablesInt r, c;
Float sum, avg;
// find average and print it
for (r = 0; r < rows; r++)
{
sum = 0;
for (c = 0; c < cols; c++)
{
sum += arr[r][c];
}
avg = sum / cols;
printf("Average on Day #%d = %fn", (r + 1), avg);
}
}
3)Implement C Program using Pointers and Structure
AIM:
writer a program to implement a structure using a pointer variable
ALGORITHM:
1.Create the structure employee with its variable name[30],id age, and character
gender[30],andcity[40].
2.And create the structure pointers *p1 and *p2 and its corresponding structure variable
emp1 andemp2.
3.Store the address of the emp1 and emp2 structure variable.
4. Assign the each and every data to the variables.
5.And print the assigned the variables data in a output.
PROGRAM:
include<stdio.h>
struct Employee
{
char name[30];
int id;
int age;
char gender[30];
char city[40];
};
struct Employee emp1,emp2,*ptr1,*ptr2;
int main()
{
ptr1=&emp1;
ptr2=&emp2;
printf (" Enter the name of the Employee(emp1):");
scanf("%s",&ptr1->name);
printf("Enter the id of the Employee (emp1): ");
scanf("%d",&ptr1->id);
printf("Enter the age of the Employee (emp1):");
scanf("%d",&ptr1->age);
printf("Enter the gender of the Employee(emp1):");
scanf("%s",&ptr1->gender);
printf("Enter the city of the Employee (emp1):");
scanf("%s",&ptr1->city);
printf("n Second Employee: n");
printf(" Enter the name of the Employee (emp2):");
scanf("%s",&ptr2->name);
printf("Enter the id of the Employee (emp2):");
scanf("%d",&ptr2->id);
printf("Enter the age of the Employee (emp2):");
scanf("%d",&ptr2->age);
printf("Enter the gender of the Employee (emp2): ");
scanf("%s",&ptr2->gender);
printf("Enter the city of the Employee (emp2): ");
scanf("%s", &ptr2->city);
printf("n Display the Details of the Employee using Structure Pointer");
printf ("n Details of the Employee (emp1)n");
printf(" Name: %sn", ptr1->name);
printf("Id:%dn",ptr1->id);
printf("Age:%dn",ptr1->age);
printf("Gender:%sn",ptr1->gender);
printf("City:%sn",ptr1->city);
printf ("n Details of the Employee (emp2)n");
printf("Name: %sn", ptr2->name);
printf("Id: %dn", ptr2->id);
printf("Age: %dn", ptr2->age);
printf("Gender:%sn",ptr2->gender);
printf("City:%sn",ptr2->city);
return 0;
}
4. Implement C program using Files
AIM:
Write a Program in C to Read and Write the Contents of a File.
ALGORITHM:
1: Start the Program.
2: Initialize the File Pointer.
3: Open the File in the Write Mode Using File Pointer.
4: Enter the Data.
5: Store the input data in the file using the putc() Statement.
6: Close the File.
7: Open the File in the Read Mode using the File Pointer.
8: Print the data in the file.
SOURCE CODE :
#include<stdio.h>
#include <stdlib.h>
struct person
{
int id;
char fname[20];
char lname[20];
};
int main ()
{
FILE *infile; struct person input;
// Open person.dat for reading infile = fopen ("person.dat", "r");
if (infile == NULL)
{
fprintf(stderr, "nError opening filen");
exit (1);
} // read file contents till end of file
while(fread(&input, sizeof(struct person), 1, infile))
printf ("id = %d name = %s %sn", input.id, input.fname, input.lname);
// close file
fclose (infile);
return 0;
}
5.Implementation of C program in real time
AIM:
Write a c porgram to implement the real time implementation by creating a text editor.
ALGORITHM:
1.Display options new, open and exit and get choice.
2.If choice is 1 , call Create() function.
3.If choice is 2, call Display() function.
4.If choice is 3, call Append() function.
5.If choice is 4, call Delete() function.
6.If choice is 5, call Display() function.
7.Create() Get the file name and open it in write mode.Get the text from the user to write it.
8.Display()Get the file name from user.Check whether the file is present or not.
9 If present then display the contents of the file.
10Append()Get the file name from user.Check whether the file is present or not.
If present then append the file by getting the text to add with the existing file.
10. Delete()
Get the file name from user.
Check whether the file is present or not.
If present then delete the existing file.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<process.h>
int i,j,ec,fg,ec2;
char fn[20],e,c;
FILE *fp1,*fp2,*fp;
void Create();
void Append();
void Delete();
void Display();
void main()
{
do
{
clrscr();
printf("ntt***** TEXT EDITOR *****");
printf("nntMENU:nt - n ");
printf("nt1.CREATEnt2.DISPLAYnt3.APPENDnt4.DELETEnt5.EXITn");
printf("ntEnter your choice: ");
scanf("%d",&ec);
switch(ec)
{
case 1:
Create();
break;
case 2:
Display();
break;
case 3:
Append();
break;
case 4:
Delete();
break;
case 5:
exit(0);
}
}while(1);
}
void Create()
{
fp1=fopen("temp.txt","w");
printf("ntEnter the text and press '.' to savennt");
while(1)
{
c=getchar();
fputc(c,fp1);
if(c == '.')
{
fclose(fp1);
printf("ntEnter then new filename: ");
scanf("%s",fn);
fp1=fopen("temp.txt","r");
fp2=fopen(fn,"w");
while(!feof(fp1))
{
c=getc(fp1);
putc(c,fp2);
}
fclose(fp2);
break;
}
}
}
void Display()
{
printf("ntEnter the file name: ");
scanf("%s",fn);
fp1=fopen(fn,"r");
if(fp1==NULL)
{
printf("ntFile not found!");
goto end1;
}
while(!feof(fp1))
{
c=getc(fp1);
printf("%c",c);
}
end1:
fclose(fp1);
printf("nntPress any key to continue...");
getch();
}
void Delete()
{
printf("ntEnter the file name: ");
scanf("%s",fn);
fp1=fopen(fn,"r");
if(fp1==NULL)
{
printf("ntFile not found!");
goto end2;
}
fclose(fp1);
if(remove(fn)==0)
{
printf("nntFile has been deleted successfully!");
goto end2;
}
else
printf("ntError!n");
end2:
printf("nntPress any key to continue...");
getch();
}
void Append()
{
printf("ntEnter the file name: ");
scanf("%s",fn);
fp1=fopen(fn,"r");
if(fp1==NULL)
{
printf("ntFile not found!");
goto end3;
}
while(!feof(fp1))
{
c=getc(fp1);
printf("%c",c);
}
fclose(fp1);
printf("ntType the text and press 'Ctrl+S' to append.n");
fp1=fopen(fn,"a");
while(1)
{
c=getch();
if(c==19)
goto end3;
if(c==13)
{
c='n';
printf("nt");
fputc(c,fp1);
}
else
{
printf("%c",c);
fputc(c,fp1);
}
}
end3:
fclose(fp1);
getch();
}
6) Array implementation of List ADT:
AIM:
Write a program to implement a list ADT c program to create and edit the list by using
the structurelist.
ALGORITHM:
1. create a file named larray.h.
2. In this file create a structure pointer.
3. create the position pointer.
4. In this file only we can insert delete modify the lists.
.
5. write a larray.c main() program.
6. In a main program we ca create insert edit and modify are all performed in a switch case.
PROGRAM:
“Larray.h”File:
#include<stdio.h>
#include<alloc.h>
#include<conio.h>
struct list
{
int
capacity;
int size;
int *array;
};
typedef struct list *ptrToNode;
typedef ptrToNode LIST;
typedef int POSITION;
int Isempty(LIST L)
{
return L->size==0;
}
void MakeEmpty(LIST L)
{
if(Isempty(L))
printf("n LIST is already
Empty");else
{
L->size=0;
printf("n Now List becomes Empty");
}
}
LIST Createlist(int max)
{
LIST L;
L=(struct list*)malloc(sizeof(struct list));
if(L==NULL)
printf("n Fatal Error");
else
{
L->capacity=max;
L->array=(int*)malloc(sizeof(int)*max);
if(L->array==NULL)
printf("n Fatal Error");
else
{
L->size=0;
printf("n List is Created successfully");
}
}
return L;
}
int Isfull(LIST L)
{
return L->size==L->capacity;
}
void Insert(int x,LIST L,POSITION P)
{
int i; if(Isfull(L))
printf("n List is Full");
else
{
for(i=L->size-1;i>=P;i--)
L->array[i+1]=L->array[i];
L->size++;
L->array[P]=x;
}
}
POSITION Findprevious(int x,LIST L)
{
POSITION
P;
P=-1;
while(P!=L->size&&L->array[P+1]!=x)
{
P++;
}
return P;
}
POSITION Find(int x,LIST L)
{
POSITION P;
P=0;
while(P!=L->size&&L->array[P]!=x)
{
P++;
}
return P;
}
void Delete(int x,LIST L)
{
int i;
POSITION
P;
P=Find(x,L);
if(P==L->size)
printf("n Element not found in the list");
else
{
for(i=P;i<L->size;i++)
L->array[i]=L-
>array[i+1];L->size--;
}
}
LIST Deletelist(LIST L)
{
MakeEmpty(
L);free(L);
L=NULL;
return L;
}
void Display(LIST L)
{
int i;
for(i=0;i<L->size;i++)
printf("n %d",L-
>array[i]);
}
“Larray.c” File:
#include"Larray.h"
#include<stdlib.h>
void main()
{
LIST L=NULL;POSITION P;
int a,choice,ch,element;
clrscr();
printf("nn1.Createn2.Insertn3.Deleten4.Displayn5.MakeEmptyn6.Findn7.IsEmptyn8.I
sFulln9.Deletelistn10.Exitn");
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:Frontt2:Backt3:middlet::: ");
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 %dt[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("nn *******WRONG ENTRY*******");
break;
}
goto A;
}
7) a)Array implementation of stack
Aim:
Write a program that implement Stack (its operations) using Arrays.
ALGORITHM:
1. Create a stack st[max].
2. wite a separate operation for stack operation.
3. write a push() function this is used to insert the value to the stack.
4. write a pop() function this is used to retrieve the stack value.
5. These are all performed by the stack pointer.
6. If the stack pointer reach the top of the stack it displays stack is full.
7. If the stack pointer reach the bottom of the stack it displays stack is empty.
Source Code:
#include<stdio.h>
#include<conio.h>
#define max 5
int st[max],top=-1;
void push()
{
int x;
if(top==max-1)
{
printf("stack is full");
return;
}
printf("enter element");
scanf("%d",&x);
top++;
st[top]=x;
}
void pop()
{
int x; if(top==-1)
{
printf("stack is empty");
return;
}
printf("enter element");
scanf("%d",&x);
top--;
printf("enter deleted element=%d",x);
}
void display()
{
int i;
if(top==-1)
{
printf("stack is empty");
return;
}
for(i=top;i>=0;i--)
{
printf("%d",st[i]);
}
}
int main()
{
int ch;
while(1)
{
printf("enter n1.pushn2.popn3.displayn4.exit");
scanf("%d",&ch);
switch(ch)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(1);
break;
}
}
return 1;
}
b) Array implementation using queue
Aim:
Write a program that implement Queue (its operations) using Arrays.
ALGORITHM:
1. First create a queue with size.
2. And then mention the front and rear.
3. If the front reaches the firs position in the queue the rear will be added by 1.
4. If the rear reaches the last position of the queue it indicates thus the queue reached the last
position.
5. And then it displays thus the insertion is not possible.
6. In this thus the void display() function is used to display the queue items.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define SIZE 5
int queue[SIZE], front = -1, rear = -1;
void enQueue(int value)
{
if(rear == SIZE-1)
printf("nQueue is Full!!! Insertion is not possible!!!");
else
{
if(front == -1)
front = 0;
rear++;
queue[rear] = value;
printf("nInsertion success!!!");
}
}
void deQueue()
{
if(front == rear)
printf("nQueue is Empty!!! Deletion is not possible!!!");
else{
printf("nDeleted : %d", queue[front]);
front++;
if(front == rear)
front = rear = -1;
}
void display()
{
if(rear == -1)
printf("nQueue is Empty!!!");
else
{
int i;
printf("nQueue elements are:n");
for(i=front; i<=rear; i++)
printf("%dt",queue[i]);
}
}
void main()
{
int value, choice;while(1){
printf("nn***** MENU *****n");
printf("1. Insertionn2. Deletionn3. Displayn4. Exit");
printf("nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter the value to be insert: ");
scanf("%d",&value);
enQueue(value);
break;
case 2:
deQueue();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("nWrong selection!!! Try again!!!");
}
}
8) i)Linked list implementation of list stack
AIM:
Write a program to implement the stack operation using the liked list
ALGORITHM:
1. Create a structure named node.
2. And create a functions named push(),pop(),empty(),display(),stack_count().
3. These functions are all performed in a while condition to insert or delete or display our stack
operation.
4. If the stack pointer reaches the top of the stack value thus it indicates thus the stack. is full.
5. When we remove the one value from the stack the stack pointer value is decremented by one.
6. When we enter the one element in a stack the stack pointer has been incremented by one.
7. If the stack pointer reaches the top it tells us stack is full we cannot add the value to the stack.
8. If it reaches the bottom of the stack it indicates thus the stack is empty.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*top,*top1,*temp;
int topelement();
void push(int data);
void pop();
void empty();
void display();
void destroy();
void stack_count();
void create();
int count =0;
void main()
{
int no, ch, e;
printf("n 1 - Push");
printf("n 2 - Pop");
printf("n 3 - Top");
printf("n 4 - Empty");
printf("n 5 - Exit");
printf("n 6 - Dipslay");
printf("n 7 - Stack Count");
printf("n 8 - Destroy stack");
create();
while(1)
{
printf("n Enter choice : ");
scanf("%d",&ch);
switch(ch)
{
case1:
printf("Enter data : ");
scanf("%d",&no);
push(no);
break;
case2:
pop();
break;
case3:
if(top == NULL)
printf("No elements in stack");
else
{
e = topelement();
printf("n Top element : %d", e);
}
break;
case4:
empty();
break;
case5:
exit(0);
case6:
display();
break;
case7:
stack_count();
break;
case8:
destroy();
break;
default:
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
}
/* Create empty stack */
void create()
{
top = NULL;
}
/* Count stack elements */
void stack_count()
{
printf("n No. of elements in stack : %d", count);
}
.
/* Push data into stack */
void push(int data)
{
if(top == NULL)
{
top =(struct node *)malloc(1*sizeof(struct node));
top->ptr = NULL;
top->info = data;
}
else
{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->ptr = top;
temp->info = data; top = temp;
}
count++;
}
/* Display stack elements */
void display()
{
top1 = top;
if(top1 == NULL)
{
printf("Stack is empty");
return;
}
while(top1 != NULL)
{
printf("%d ", top1->info);
top1 = top1->ptr;
}
}
/* Pop Operation on stack */
void pop()
{
top1 = top;
if(top1 == NULL)
{
printf("n Error : Trying to pop from empty stack");
return;
}
else
top1 = top1->ptr;
printf("n Popped value : %d", top->info);
free(top);
top = top1;
count--;
}
/* Return top element */
int topelement()
{
return(top->info);
}
/* Check if stack is empty or not */
void empty()
{
if(top == NULL) printf("n Stack is empty");
else
printf("n Stack is not empty with %d elements", count);
}
/* Destroy entire stack */
void destroy()
{
top1 = top;
while(top1 != NULL)
{
top1 = top->ptr; free(top);
top = top1;
top1 = top1->ptr;
}
free(top1); top = NULL;
printf("n All stack elements destroyed");
count =0;
}
b)program using queue:
AIM:
Write a program to implement a linked list operation by using a queue.
ALGORITHM:
1. Create a structure node with structure pointer front and back.
2. And create a queue to insert and delete the queue with the queue size.
3. If the front of the queue is null and thus the queue is ready to intake the input.
4. And the back of the queue is full it indicates thus the queue if full.
5. Thus the front and back of the queue is indicates thus the stack pointer.
6. If it moves front means thus the stack pointer is incremented by one.
7. If it moves back means in the queue thus the stack pointer is decremented by one.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
} *front, *back;
/* Create an empty queue */
void initialize()
{
front = back = NULL;
}
/* Returns queue size */
int getQueueSize()
{
struct node *temp = front;
int count = 0;
if(front == NULL && back == NULL)
return 0;
while(temp != back)
{
count++;
temp = temp->next;
}
if(temp == back)
count++;
return count;
}
/* Returns Frnt Element of the Queue */
int getFrontElement()
{
return front->data;
}
/* Returns the Rear Element of the Queue */
int getBackElement()
{
return back->data;
}
/*Check's if Queue is empty or not */
void isEmpty()
{
if (front == NULL && back == NULL)
printf("Empty Queuen");
else
printf("Queue is not Emptyn");
}
/*Adding elements in Queue*/
void enqueue(int num)
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp->data = num;
temp->next = NULL;
if (back == NULL)
{
front = back = temp;
} else {
back->next = temp;back = temp;
}
}
/*Removes an element from front of the queue*/
void dequeue()
{
struct node *temp;
if (front == NULL)
{
printf("nQueue is Empty n");
return;
}
else
{
temp = front;
front = front->next;
if(front == NULL)
{
back = NULL;
}
printf("Removed Element : %dn", temp->data);
free(temp);
}
}
/*Print's Queue*/
void printQueue()
{
struct node *temp = front;
if ((front == NULL) && (back == NULL))
{
printf("Queue is Emptyn");
return;
}
while (temp != NULL)
{
printf("%d", temp->data);
temp = temp->next;
if(temp != NULL) printf("-->");
}
}
int main() {
/* Initializing Queue */initialize();
/* Adding elements in Queue */
enqueue(1);
enqueue(3);
enqueue(7);
enqueue(5);
enqueue(10);
/* Printing Queue */
printQueue();
/* Printing size of Queue */
printf("nSize of Queue : %dn", getQueueSize());
/* Printing front and rear element of Queue */
printf("Front Element : %dn", getFrontElement());
printf("Rear Element : %dn", getBackElement());
/* Removing Elementd from Queue */dequeue();
dequeue();
dequeue();
dequeue();
dequeue();
dequeue();
return 0;
}
9.Applications of list ,stack and queue ADT’s
i)Convertion of infix to postfix using stack:
AIM:
Write a program to implement a infix to postfix using the stack operation
ALGORITHM:
1. Start the program.
2. create the stack size of 100.
3. An create the push and pop operation to insert and remove the element from stack.
4. 4.In the main program create the character variable size of 100.
5. Create the pointer variable for that based on that we can call the function puh and pop.
6. .
.
Execute that in a while statement.
7
. Print that case statement output.
8. .
Stop the program.
PROGRAM:
#include<stdio.h>
#include<ctype.h>
char stack[100];
int top =-1;
voidpush(char x)
{
stack[++top]= x;
}
charpop()
{
if(top ==-1)
return-1;
else
return stack[top--];
}
intpriority(char x)
{
if(x =='(')return0;
if(x =='+'|| x =='-')
return1;
if(x =='*'|| x =='/')
return2;
return0;
}
intmain()
{
char exp[100];char*e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("n");e = exp;
while(*e !='0')
{
if(isalnum(*e))
printf("%c ",*e);
elseif(*e =='(')push(*e);
elseif(*e ==')')
{
while((x =pop())!='(')
printf("%c ", x);
}
else
{
while(priority(stack[top])>=priority(*e))
printf("%c ",pop());
push(*e);
} e++;
}
while(top !=-1)
{
printf("%c ",pop());
}return0;
}
ii)Queue application:
AIM:
Write a program to implement a queue application to display the queue items.
ALGORITHM:
1. Start the program
2. Create the function enqueue(), and dequeue(), and show()
3. .Based on the enqueuer() we can add the element in the queue
4. In the dequeuer() is used to revoke the elment in the queue
5. The show() is used to display the elements available in the queue
6. And then the final exit function is used to terminate the queue items
PROGRAM:
#include <stdio.h>
# define SIZE 100void enqueue();
void dequeue();
void show();
int inp_arr[SIZE];
int Rear = - 1;
int Front = - 1;
main()
{
int ch; while (1)
{
printf("1.Enqueue Operationn");
printf("2.Dequeue Operationn");
printf("3.Display the Queuen");
printf("4.Exitn");
printf("Enter your choice of operations : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
enqueue();
break;
case 2:
dequeue();
break;
case 3:
show();
break;
case 4:
exit(0);
default:
printf("Incorrect choice n");
}
}
}
void enqueue()
{
int insert_item;
if (Rear == SIZE - 1)
printf("Overflow n");
else
{
if (Front == - 1)
Front = 0;
printf("Element to be inserted in the Queuen : ");
scanf("%d", &insert_item);
Rear = Rear + 1;
inp_arr[Rear] = insert_item;
}
}
void dequeue()
{
if (Front == - 1 || Front > Rear)
{
printf("Underflow n");
return ;
}
else
{
printf("Element deleted from the Queue: %dn", inp_arr[Front]);
Front = Front + 1;
}
}
void show()
{
if (Front == - 1)
printf("Empty Queue n");else
{
printf("Queue: n");
for (int i = Front; i <= Rear; i++)
printf("%d ", inp_arr[i]);
printf("n");
}
}
10.Implementation of binry tree with its operation
AIM:
Write a program to implement the binary tree with its operations.
ALGORITHM:
1: Start the Program.
2: Declare a Template for Key and Elements.
3: Insert the Key-Element Pair into the Tree, overwriting Existing pair, if any, with same key.
4: Find place to Insert. While P != NULL.
5: Examine Element pointed to by Pair. Move P to a Child
6: If Pair First Element is Less Than Element of first P, assign P as Left Child.
7: If Pair First Element is Greater than Element of first P, assign P as Right Child
8: Else, Replace Old Value
9: Retrieve a Node for the Pair and assign to Pair Pointer Element
10: If Root != NULL, the tree is not Empty.
11: Now, Handle Input Operation – Insert, Delete, ListOrder Accordingly
12: If Pair First Element is Less Than Pair Pointer First Element; LeftChildNode = NewNode.
13: Else, Pair Pointer First Element RightChildNode = NewNode. Else, Root = NewNode
14: Insert Operation Into Tree Successful.
15: Stop
PROGRAM:
# include <stdio.h>
# include <malloc.h>
struct node
{
int info;
struct node *lchild;
struct node *rchild;
}*root;
void find(int item,struct node **par,struct node **loc)
{
struct node *ptr,*ptrsave;
if(root==NULL) /*tree empty*/
{
*loc=NULL;
*par=NULL;
return;
}
if(item==root->info) /*item is at root*/
{
*loc=root;
*par=NULL;
return;
}
/*Initialize ptr and ptrsave*/
if(item<root-
>info)ptr=root-
>lchild; else
ptr=root->rchild;
ptrsave=root;
while(ptr!=NULL)
{
if(item==ptr->info)
{ *loc=ptr;
*par=ptrsave;
return;
}
ptrsave=ptr;
if(item<ptr->info)
ptr=ptr->lchild;
else
ptr=ptr->rchild;
}/*End of while */
*loc=NULL; /*item not found*/
*par=ptrsave;
}/*End of find()*/
void insert(int item)
{
struct node *tmp,*parent,*location;
find(item,&parent,&location);
if(location!=NULL)
{
printf("Item already present");
return;
}
tmp=(struct node *)malloc(sizeof(struct node));
tmp->info=item;
tmp->lchild=NULL;
tmp->rchild=NULL;
if(parent==NULL) root=tmp;
else
if(item<parent->info)
parent->lchild=tmp;
else
parent->rchild=tmp;
}/*End of insert()*/
void case_a(struct node *par,struct node *loc )
{
if(par==NULL) /*item to be deleted is root
node*/root=NULL;
else
if(loc==par->lchild)
par->lchild=NULL;
else
par->rchild=NULL;
}/*End of case_a()*/
void case_b(struct node *par,struct node *loc)
{
struct node *child;
/*Initialize child*/
if(loc->lchild!=NULL)
/*item to be deleted has lchild */
child=loc->lchild;
else
child=loc->rchild;
if(par==NULL ) /*Item to be deleted is root node*/
root=child;
else
if( loc==par->lchild)
/*item is lchild of its parent*/
par->lchild=child;
else /*item is rchild of its parent*/
par->rchild=child;
}/*End of case_b()*/
void case_c(struct node *par,struct node *loc)
{
struct node *ptr,*ptrsave,*suc,*parsuc;
/*Find inorder successor and its parent*/
ptrsave=loc;
ptr=loc->rchild;
while(ptr->lchild!=NULL)
{
ptrsave=ptr;
ptr=ptr->lchild;
}
suc=ptr;
parsuc=ptrsave;
if(suc->lchild==NULL && suc->rchild==NULL)
case_a(parsuc,suc);
else
case_b(parsuc,suc);
if(par==NULL) /*if item to be deleted is root node */
root=suc;
else
if(loc==par->lchild)
par->lchild=suc;
else
par->rchild=suc;
suc->lchild=loc-
>lchild;suc-
>rchild=loc->rchild;
}/*End of case_c()*/
int del(int item)
{
struct node *parent,*location;
if(root==NULL)
{
printf("Tree empty");
return 0;
}
find(item,&parent,&location);
if(location==NULL)
{
printf("Item not present in tree");
return 0;
}
if(location->lchild==NULL && location->rchild==NULL)
case_a(parent,location);
if(location->lchild!=NULL && location->rchild==NULL)
case_b(parent,location);
if(location->lchild==NULL && location-.>rchild!=NULL)
case_b(parent,location);
if(location->lchild!=NULL && location-..>rchild!=NULL)
case_c(parent,location);
free(location);
}/*End of del()*/
int preorder(struct node *ptr)
{
if(root==NULL)
{
printf("Tree is empty");
return 0;
}
if(ptr!=NULL)
{
printf("%d ",ptr-..>info);
preorder(ptr->lchild);
preorder(ptr->rchild);
}
}/*End of preorder()*/
void inorder(struct node *ptr)
{
if(root==NULL)
{
printf("Tree is empty");
return;
}
if(ptr!=NULL)
{
inorder(ptr->lchild);
printf("%d ",ptr->info);
inorder(ptr->rchild);
}
}/*End of inorder()*/
void postorder(struct node *ptr)
if(location==NULL)
{
printf("Item not present in tree");
return 0;
}
if(location->lchild==NULL && location->rchild==NULL)
case_a(parent,location);
if(location->lchild!=NULL && location->rchild==NULL)
case_b(parent,location);
if(location->lchild==NULL && location->rchild!=NULL)
case_b(parent,location);
if(location->lchild!=NULL && location->rchild!=NULL)
case_c(parent,location);
free(location);
}/*End of del()*/
int preorder(struct node *ptr)
{
if(root==NULL)
{
printf("Tree is empty");
return 0;
}
if(ptr!=NULL)
{
printf("%d ",ptr->info);
preorder(ptr->lchild);
preorder(ptr->rchild);
}
}/*End of preorder()*/
void inorder(struct node *ptr)
{
if(root==NULL)
{
printf("Tree is empty");
return;
}
if(ptr!=NULL)
{
inorder(ptr->lchild);
printf("%d ",ptr->info);
inorder(ptr->rchild);
}
}/*End of inorder()*/
void postorder(struct node *ptr)
{
if(root==NULL)
{
printf("Tree is empty");
return;
}
if(ptr!=NULL)
{
postorder(ptr->lchild);
postorder(ptr->rchild);
printf("%d ",ptr->info);
}
}/*End of postorder()*/
void display(struct node *ptr,int level)
{
int i;
if ( ptr!=NULL )
{
display(ptr->rchild,
level+1);printf("n");
for (i = 0; i < level; i++)
printf("");
printf("%d", ptr->info);
display(ptr->lchild, level+1);
}/*End of if*/
}/*End of display()*/
main()
{
int choice,num;root=NULL;
while(1)
{
printf("n");
printf("1.Insertn");
printf("2.Deleten");
printf("3.Inorder Traversaln");
printf("4.Preorder Traversaln");
printf("5.Postorder Traversaln");
printf("6.Displayn");
printf("7.Quitn");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter the number to be inserted : ");
scanf("%d",&num);
insert(num);
break;
case 2:
printf("Enter the number to be deleted : ");
scanf("%d",&num);
del(num);
break;
case 3:
inorder(root);
break;
case 4:
preorder(root);
break;
case 5:
postorder(root);
break;
case 6:
display(root,1);
break;
case 7:
break;
default:
printf("Wrong choicen");
}/*End of switch */
}/*End of while */
}/*End of main()*
EX.NO.11 Implementation of binary search tree
AIM:
Write a program to implement to a binary search tree.
ALGORITHM:
1. Start the program.
2. Create the structure BST.
3. Create the the structure pointer *left an *right.
4. Create structure variable node.
5. In this if the root is empty insert the value to the root nod.
6. And find the left and right node by using the left and right pointer.
7. Once the tree element insertion is completed we have to search the element in the tree
8. In this left search and right search has been made.
9. Stop the program.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
typedef struct BST
{
int data;
struct BST *left;
struct BST *right;
}node;
node *create();
void insert(node *,node *);
void preorder(node *);
int main()
{
char ch;
node *root=NULL,*temp;
do
{
temp=create();
if(root==NULL)
root=temp;
else insert(root,temp);
printf("nDo you want to enter more(y/n)?");
getchar();
scanf("%c",&ch);
}while(ch=='y'|ch=='Y');
printf("nPreorder Traversal: ");
preorder(root);
return 0;
}
node *create()
{
node *temp;
printf("nEnter data:");
temp=(node*)malloc(sizeof(node));
scanf("%d",&temp->data);
temp->left=temp->right=NULL;
return temp;
}
void insert(node *root,node *temp)
{
if(temp->data<root->data)
{
if(root->left!=NULL)
insert(root->left,temp);
else
root->left=temp;
}
if(temp->data>root->data)
{
if(root->right!=NULL)
insert(root->right,temp);
else
root->right=temp;
}
}
void preorder(node *root)
{
if(root!=NULL)
{
printf("%d ",root->data);
preorder(root->left);
preorder(root->right);
}
}
EX.NO.12 Implementation of searching techniques
AIM:
Write a program to implement a searching techniques in a tree.
ALGORITHM:
1. i is used for iteration through the array.
2. low is used to hold the first array index. 3.high is used to hold the last array index.
3. mid holds the middle value calculated by adding high and low and dividing it by 2.
4. n is the of elements in the array.
5. key is the element to search.
6. array is the array element of size 100.
i)Normal search tree
PROGRAM:
#include <stdio.h>
int main()
{
int i, low, high, mid, n, key, array[100];
printf("Enter number of elementsn");
scanf("%d",&n);
printf("Enter %d integersn", n);
for(i = 0; i < n; i++)
scanf("%d",&array[i]);
printf("Enter value to findn");
scanf("%d", &key);
low = 0;
high = n - 1;
mid = (low+high)/2;
while (low <= high)
{
if(array[mid] < key)
low = mid + 1;
else if (array[mid] == key)
{
printf("%d found at location %d.n", key,
mid+1);
break;
}
else
high = mid - 1;
mid = (low + high)/2;
}
if(low > high)
printf("Not found! %d isn't present in the list.n",
key);return 0;
}
ii)Binary search tree using Recursive function:
PROGRAM:
#include <stdio.h>
int binaryScr(int a[], int low, int high, int m)
{
if (high >= low)
{
int mid = low + (high - low) / 2;
if (a[mid] == m)
return mid;
if(a[mid] > m)
return binaryScr(a, low, mid - 1, m);
return binaryScr(a, mid + 1, high, m);
}
return -1;
}
int main(void)
{
int a[] = { 12, 13, 21, 36, 40 };
int i,m;
for(i=0;i<5;i++)
{
printf(" %d",a[i]);
}
printf(" n");
int n = sizeof(a) / sizeof(a[0]);
printf("Enter the number to be searchedn");
scanf("%d", &m);
int result = binaryScr(a, 0, n - 1, m);
(result == -1) ? printf("The element is not present in array")
printf("The element is present at index %d",
result);
return 0;
}
EX.NO.13 Implementation of sorting algorithm
i)insertion sort ii) Quick sort iii) Merge sort
i) insertion sort:
AIM:
Write a c porgram to implement the insertion sort.
.
ALGORITHM:
1: 89 17 8 12 0 (the bold elements are sorted list and non-bold unsorted list)
2: 17 89 8 12 0 (each element will be removed from unsorted list and placed at the
rightposition in the sorted list)
3: 8 17 89 12 0
4: 8 12 17 89 0
5: 0 8 12 17 89
PROGRAM:
#include<stdio.h>
int main()
{
int i, j, count, temp, number[25];
printf("How many numbers u are going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
// This loop would store the input numbers in array
for(i=0;i<count;i++)
scanf("%d",&number[i]);
// Implementation of insertion sort algorithm
for(i=1;i<count;i++)
{
temp=number[i];
j=i-1;
while((temp<number[j])&&(j>=0))
{
number[j+1]=number[j];
j=j-1;
}
number[j+1]=temp;
}
printf("Order of Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return0;
}
Quick sort algorithm:.
Aim:
Write a c porgram to implement the Quicksort.
Algorithm:
1.If n < = 1, then return.
2. Pick any element V in a[]. This is called the pivot.
3. Rearrange elements of the array by moving all elements xi > V right of V and all elements
xi < = Vleft of V. If the place of the V after re-arrangement is j, all elements with value less
than V, appear in a[0], a[1] . . . . a[j – 1] and all those with value greater than V appear in a[j
+a[n – 1].
4. Apply quick sort recursively to a[0] . . . . a[j – 1] and to a[j + 1] a[n – 1].
PROGRAM:
#include <stdio.h>
void quick_sort(int[],int,int);int partition(int[],int,int);
int main()
{
int a[50],n,i;
printf("How many elements?");
scanf("%d",&n);
printf("nEnter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
quick_sort(a,0,n-1);
printf("nArray after sorting:");
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
void quick_sort(int a[],int l,int u)
{
int j;
if(l<u)
{
j=partition(a,l,u);
quick_sort(a,l,j-1);
quick_sort(a,j+1,u);
}
}
int partition(int a[],int l,int u)
{
int v,i,j,temp;v=a[l];
i=l; j=u+1;
do
{
do
i++;.
while(a[i]<v&&i<=u
)
do
j--;
while(v<a[j]);
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}while(i<j);
a[l]=a[j];
a[j]=v;
return(j);
}
ii) Merge sort:
program:
#include<stdio.h>
#define max 10
int a[11]={10,14,19,26,27,31,33,35,42,44,0};
int b[10];
void merging(int low,int mid,int high)
{
int l1, l2, i;
for(l1 = low, l2 = mid +1, i = low; l1 <= mid && l2 <= high; i++)
{
if(a[l1]<= a[l2])
b[i]= a[l1++];
else
b[i]= a[l2++];
}
while(l1 <= mid)
b[i++]= a[l1++];
while(l2 <= high)
b[i++]= a[l2++];
for(i = low; i <= high; i++)
a[i]= b[i];
}
void sort(int low,int high)
{
int mid;
if(low < high)
{
mid =(low + high)/2;
sort(low, mid);
sort(mid+1, high);
merging(low, mid, high);
}
else
{
return;
}
}
int main()
{
int i;
printf("List before sortingn");
for(i =0; i <= max; i++)
printf("%d ", a[i]);
sort(0, max);
printf("nList after sortingn");
for(i =0; i <= max; i++)
printf("%d ", a[i]);
}
EX.NO.14 Implementation of hashing
AIM..
Write a c porgram to implement the Hashing.
ALGORITHM:
1. Create an array of structure, data (i.e a hash table).
2. Take a key to be stored in hash table as input.
3. Corresponding to the key, an index will be generated.
4. In case of absence of data in that index of array, create one and insert the data item (key
and value)into it and increment the size of hash table.
5. In case the data already exists, the new data cannot be inserted if the already present data
does notmatch given key.
6. To display all the elements of hash table, data at each index is extracted and elements
(key andvalue) are read and printed.
7. To remove a key from hash table, we will first calculate its index and extract its data,
delete the keyin case it matches the given key.
8. Exit
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
struct data
{
int key; int value;
};
struct data *array;int capacity =10;
int size =0;
/* this function gives a unique hash code to the given key */
int hashcode(int key)
{
return(key % capacity);
}
/* it returns prime number just greater than array capacity */
int get_prime(int n)
{
if(n %2==0)
{
n++;
}
for(;!if_prime(n); n +=2);
return n;
}
/* to check if given input (i.e n) is prime or not */
int if_prime(int n)
{
int i;
if( n ==1|| n ==0)
{
return0;
}
for(i =2; i < n; i++)
{
{
if(n % i ==0)
return0;
}
return1;
} void init_array()
{
int i;
capacity = get_prime(capacity);
array =(struct data*)malloc(capacity *sizeof(struct data));
.
for(i =0; i < capacity; i++)
{
array[i].key=0;
array[i].value=
0;
}
}
/* to insert a key in the hash table */
void insert(int key)
{
int index = hashcode(key);
if(array[index].value==0)
{
/* key not present, insert it */
array[index].key= key;
array[index].value=1;
size++;
printf("n Key (%d) has been inserted n", key);
}
elseif(array[index].key== key)
{
/* updating already existing key */
printf("n Key (%d) already present, hence updating itsvalue
n", key);array[index].value+=1;
}
else
{
/* key cannot be insert as the index is alreadycontaining some
other key */
printf("n ELEMENT CANNOT BE INSERTED n");
}
}
/* to remove a key from hash table */
void remove_element(int key)
{
int index = hashcode(key);
if(array[index].value==0)
{
printf("n This key does not exist n");
}
else{
array[index].key=0;
array[index].value=0;
size--;
printf("n Key (%d) has been removed n", key);
}
}
/* to display all the elements of a hash table */
void display()
{
int i;
for(i =0; i < capacity; i++)
{
if(array[i].value==0)
{
printf("n Array[%d] has no elements n");
}
else
{
printf("n array[%d] has elements -:n key(%d) andvalue(%d) t", i,
array[i].key, array[i].value);
}
}
}
int size_of_hashtable()
{
return size;
}
void main()
{
int choice, key, value,
n, c;clrscr();
init_array(
);
do{
printf("n Implementation of Hash Table in C nn");
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 a Hash
Table""nn Please enter your choice -:");
scanf("%d",&choice);
switch(choice)
{
case1:
printf("Inserting element in Hash Tablen");
printf("Enter key -:t");
scanf("%d",&key);
insert(key);
break;
case2:
printf("Deleting in Hash Table n Enter the key to delete-:");
scanf("%d",&key);
remove_element(key);
break;
case3:
n = size_of_hashtable();
printf("Size of Hash Table is-:%dn", n);
break;
case4:
display();
. break;
default:
. printf("Wrong Inputn");
}
printf("n Do you want to continue-:(press 1 for yes)t");
scanf("%d",&c);
}
while(c ==1);
getch();
}

More Related Content

What's hot (20)

PPT
Filter- IIR - Digital signal processing(DSP)
tamil arasan
 
PPTX
Digital and logic designs presentation
Haya Butt
 
PDF
The Fast Fourier Transform (FFT)
Oka Danil
 
PPTX
Line coding
Rina Ahire
 
PPTX
EC8353 ELECTRONIC DEVICES AND CIRCUITS Unit 1
RMK ENGINEERING COLLEGE, CHENNAI
 
PPTX
Amplitude modulation
MOHAMMAD AKRAM
 
PPTX
Butterworth filter design
Sushant Shankar
 
PPT
Noise in AM systems.ppt
infomerlin
 
PPT
Analysis of Hertzian Dipole
Yong Heui Cho
 
PPTX
rms value
2461998
 
PPTX
Adder
anuppatel111
 
PDF
Design of IIR filters
op205
 
PDF
Antennas and Wave Propagation
VenkataRatnam14
 
PPT
Fir filter_utkarsh_kulshrestha
Utkarsh Kulshrestha
 
PDF
Pulse amplitude modulation
Vishal kakade
 
PPT
Losses in optical fiber
Samruddha Parkar
 
PPTX
Ripple Carry Adder
Aravindreddy Mokireddy
 
PPTX
Pin Photodetector
DeekshithaReddy23
 
PDF
Graded index vs. step index
OptoTest
 
PDF
4.Sampling and Hilbert Transform
INDIAN NAVY
 
Filter- IIR - Digital signal processing(DSP)
tamil arasan
 
Digital and logic designs presentation
Haya Butt
 
The Fast Fourier Transform (FFT)
Oka Danil
 
Line coding
Rina Ahire
 
EC8353 ELECTRONIC DEVICES AND CIRCUITS Unit 1
RMK ENGINEERING COLLEGE, CHENNAI
 
Amplitude modulation
MOHAMMAD AKRAM
 
Butterworth filter design
Sushant Shankar
 
Noise in AM systems.ppt
infomerlin
 
Analysis of Hertzian Dipole
Yong Heui Cho
 
rms value
2461998
 
Adder
anuppatel111
 
Design of IIR filters
op205
 
Antennas and Wave Propagation
VenkataRatnam14
 
Fir filter_utkarsh_kulshrestha
Utkarsh Kulshrestha
 
Pulse amplitude modulation
Vishal kakade
 
Losses in optical fiber
Samruddha Parkar
 
Ripple Carry Adder
Aravindreddy Mokireddy
 
Pin Photodetector
DeekshithaReddy23
 
Graded index vs. step index
OptoTest
 
4.Sampling and Hilbert Transform
INDIAN NAVY
 

Similar to C and Data structure lab manual ECE (2).pdf (20)

DOCX
Cs291 assignment solution
Kuntal Bhowmick
 
PPTX
the refernce of programming C notes ppt.pptx
AnkitaVerma776806
 
DOCX
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
vrickens
 
PPTX
Fundamentals of computer programming by Dr. A. Charan Kumari
THE NORTHCAP UNIVERSITY
 
DOC
C important questions
JYOTI RANJAN PAL
 
DOC
c programing
bibek lamichhane
 
PPTX
C decision making and looping.
Haard Shah
 
PPTX
C and C++ programming basics for Beginners.pptx
renuvprajapati
 
PPTX
Unit-IV.pptx
Mehul Desai
 
PPT
Arrays in c programing. practicals and .ppt
Carlos701746
 
PDF
Computer P-Lab-Manual acc to syllabus.pdf
sujathachoudaryn29
 
PDF
Cp manual final
itprasad1237
 
DOCX
C programming Lab 2
Zaibi Gondal
 
PPT
lecture2 (1).ppt variable s and operators
ChittyAvula
 
PPTX
Control structure of c
Komal Kotak
 
PPTX
Programming in C
Nishant Munjal
 
PDF
arraysfor engineering students sdf ppt on arrays
ruvirgandhi123
 
DOC
C-programs
SSGMCE SHEGAON
 
Cs291 assignment solution
Kuntal Bhowmick
 
the refernce of programming C notes ppt.pptx
AnkitaVerma776806
 
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
vrickens
 
Fundamentals of computer programming by Dr. A. Charan Kumari
THE NORTHCAP UNIVERSITY
 
C important questions
JYOTI RANJAN PAL
 
c programing
bibek lamichhane
 
C decision making and looping.
Haard Shah
 
C and C++ programming basics for Beginners.pptx
renuvprajapati
 
Unit-IV.pptx
Mehul Desai
 
Arrays in c programing. practicals and .ppt
Carlos701746
 
Computer P-Lab-Manual acc to syllabus.pdf
sujathachoudaryn29
 
Cp manual final
itprasad1237
 
C programming Lab 2
Zaibi Gondal
 
lecture2 (1).ppt variable s and operators
ChittyAvula
 
Control structure of c
Komal Kotak
 
Programming in C
Nishant Munjal
 
arraysfor engineering students sdf ppt on arrays
ruvirgandhi123
 
C-programs
SSGMCE SHEGAON
 
Ad

Recently uploaded (20)

PDF
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
PPTX
Introduction to Neural Networks and Perceptron Learning Algorithm.pptx
Kayalvizhi A
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PPTX
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
DOC
MRRS Strength and Durability of Concrete
CivilMythili
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PPTX
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PPTX
MobileComputingMANET2023 MobileComputingMANET2023.pptx
masterfake98765
 
PPTX
Hashing Introduction , hash functions and techniques
sailajam21
 
PDF
GTU Civil Engineering All Semester Syllabus.pdf
Vimal Bhojani
 
PPTX
Types of Bearing_Specifications_PPT.pptx
PranjulAgrahariAkash
 
PPTX
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
PPTX
Day2 B2 Best.pptx
helenjenefa1
 
DOCX
8th International Conference on Electrical Engineering (ELEN 2025)
elelijjournal653
 
PPTX
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
DOCX
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
PPTX
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
PDF
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
Introduction to Neural Networks and Perceptron Learning Algorithm.pptx
Kayalvizhi A
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
MRRS Strength and Durability of Concrete
CivilMythili
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
MobileComputingMANET2023 MobileComputingMANET2023.pptx
masterfake98765
 
Hashing Introduction , hash functions and techniques
sailajam21
 
GTU Civil Engineering All Semester Syllabus.pdf
Vimal Bhojani
 
Types of Bearing_Specifications_PPT.pptx
PranjulAgrahariAkash
 
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
Day2 B2 Best.pptx
helenjenefa1
 
8th International Conference on Electrical Engineering (ELEN 2025)
elelijjournal653
 
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
Ad

C and Data structure lab manual ECE (2).pdf

  • 1. PERI INSTITUTE OF TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING CS3362- C PROGRAMMING AND DATA STRUCTURES LABORATORY2021- REGULATIONS BE ECE III SEMESTER
  • 2. PERI Institute of Technology Department of Computer Science and Engineering VISION AND MISSION OF THE INSTITUTION Vision of the Institute PERI Institute of Technology visualizes growing in future to an internationally recognized seat of higher learning in engineering, technology & science. It also visualizes being a research incubator for academicians, industrialists and researchers from across the world, enabling them to work in an environment with the sophisticated and state of the art equipment and amenities provided at the institute. Mission of the Institute In the process of realization of its Vision, PERIIT strives to provide quality technical education at affordable cost in a challenging & stimulating environment with state-of-the-art facilities and a global team of dedicated and talented academicians, without compromising in its core values of honesty, transparency and excellence. VISION AND MISSION OF THE DEPARTMENT Vision of the Department The vision of the department is to prepare industry-ready competent professionals with moral values by imparting scientific knowledge and skill-based education. Mission of the Department a)To provide exposure of latest tools and technologies in the broad area of computing. b)To promote research-based projects / activities in the emerging areas of technology. c)To enhance Industry Institute Interaction program to get acquainted with corporate culture and to develop entrepreneurship skills d)To induce ethical values and spirit of social commitment.
  • 3. CS3362 C PROGRAMMING AND DATA STRUCTURES LABORATORY L T P C 0 0 3 1.5 COURSE OBJECTIVES: To develop applications in C. To implement linear and non-linear data structures. To understand the different operations of search trees. To get familiarized to sorting and searching algorithms. LIST OF EXPERIMENTS 1. Practice of C programming using statements, expressions, decision making and iterative statements. 2. Practice of C programming using Functions and Arrays. 3. Implement C programs using Pointers and Structures. 4. Implement C programs using Files. 5. Development of real time C applications. 6. Array implementation of List ADT. 7. Array implementation of Stack and Queue ADTs. 8. Linked list implementation of List, Stack and Queue ADTs. 9. Applications of List, Stack and Queue ADTs. 10.Implementation of Binary Trees and operations of Binary Trees. 11. Implementation of Binary Search Trees. 12. Implementation of searching techniques. 13. Implementation of Sorting algorithms : Insertion Sort, Quick Sort, Merge Sort. 14. Implementation of Hashing – any two collision techniques. TOTAL: 45 PERIODS COURSE OUTCOMES: At the end of the course, the students will be able to: CO1 Use different constructs of C and develop applications. CO2 Write functions to implement linear and non-linear data structure operations. CO3 Suggest and use the appropriate linear / non-linear data structure operations for a given problem. CO4 Apply appropriate hash functions that result in a collision free scenario for data storage and Retrieval. CO5 Implement Sorting and searching algorithms for a given application
  • 4. a) using ifb) using if else c) using if else ladder d) Nested if else e) Switch case a) Using if Aim: Write a program to check the variable using if condition Algorithm: 1.Create a two integer variable x,y. 2.Assign the values to that variable. 3.check the condition. 4.condition is true print the value. Program: #include<stdio.h> int main() { int x = 20; int y = 22; if (x<y) { printf("Variable x is less than y"); } return 0; } OUTPUT: Variable x is less than y
  • 5. b)If else Aim: Write a program to check the variable using else if condition. Algorithm: 1.Create a two integer variable x,y. 2.Assign the values to that variable. 3.Check the condition using else if. 4.Condition is true execute if otherwise execute else statement. PROGRAM: #include<stdio.h> int main() { int age; printf("Enter your age:");scanf("%d",&age); if(age >=18) { printf("You are eligible for voting"); } else { printf("You are not eligible for voting"); } return0; } OUTPUT: Enter your age:14 You are not eligible for voting
  • 6. c)If else ladder: Aim: Write a program to implement a if else ladder Alogrithm: 1.Create a variable x & y. 2.Get the values of X& Y from user. 3.First check the condition if it satisfies it will proceed to next level of if. 4.Again it checks the condition if it satisfies it will proceed to next level. 5.Print the values. Program: #include<stdio.h> int main() { int x, y; printf("Enter the value of x:"); scanf("%d",&x); printf("Enter the value of y:"); scanf("%d",&y); if(x>y) { printf("X is greater than yn"); } if(x<y) { printf("X is less than yn"); } if(x==y) { printf("X is equal to yn"); } printf("End of Program");return0; } OUTPUT: Enter the value of x:20Enter the value of y:20 X is equal to y End of Program
  • 7. d)Nested if else Aim: Write a program to implement a nested if else Algorithm: 1. Declare the integer variable n and get the value for n. 2. First check the the value even or not and then print the value. 3. And the check in nested if else it is advisable by 4 or not. 4. If it is divisible by 4 means print it is even other print it is odd. 5. else check it is divisible by 3 or not. 6. If it is divisible by 3 means print it is printable by 3 otherwise print it is not divisible by 3. PROGRAM: #include <stdio.h> int main() { int n; scanf("%d",&n); if (n % 2 == 0) { printf("Even "); if (n % 4 == 0) { printf("and divisible by 4"); } else { printf("and not divisible by 4"); } } else { printf("Odd "); if(n % 3 == 0) { printf("and divisible by 3"); } else { printf("and not divisible by 3"); } } return 0; } Input 14 Output Even and not divisible by 4
  • 8. e) switch case: AIM: Write a program to check whether the operator is available not in a switch case. ALGORITHM: 1.Declare the two variable n1,n2. 2.Get the operator and operand from user. 3.Open the switch case operation. 4.In each case check whether the operator available or not. 5.Otherwise print the default case statement. PROGRAM: // Program to create a simple calculator #include <stdio.h> int main() { char operation; double n1, n2; printf("Enter an operator (+, -, *, /): "); scanf("%c", &operation); printf("Enter two operands: "); scanf("%lf %lf",&n1, &n2); switch(operation) { case '+': printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2); break; case '-': printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2); break; case '*': printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);break; case '/': printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);break; // operator doesn't match any case constant +, -, *, / default: printf("Error! operator is not correct"); } return 0; } OUTPUT: Enter an operator (+, -, *, /): - Enter two operands: 32.5 12.4 32.5 - 12.4 = 20.1
  • 9. 2.Practice a C programming using Functions & Array a) Function with one dimensional array AIM: Write a program to implement a function using an one dimensional array. ALGORITHM: 1. Declare the one dimensional array named score. 2.And assign the values to that array. 3.And declare integer variable score. 4.Declare the function findAverage with function variable int[], and int. 5.And write the function functions in a function. 6.In that functiondeclare the local variables int i, and float sum=0 and avg=07. 7.Check it in condition in for loop. 8.It will find the total and average of the given number. 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: %fn", avg); return 0; } float findAverage(int arr[], int size) { // variablesint i; float sum = 0, avg = 0; // find total for (i = 0; i < size; i++) { sum += arr[i]; } // find average avg = sum / size; // return average }
  • 10. b)Function with Twos dimensional array AIM: Write a program to implement a function using an two dimensional array. ALGORITHM: 1. Declare the two dimensional array named score[5][3]. 2. And assign the values to that array And declare integer variable score. 3. Declare the function print Average with function variable int[][3], and int. 4. And write the function functions in a function. 5. In that function declare the local variables int r,c, and float sum, avg. 6. Check it in condition in for loop. 7. It will find the total and average of the given number. PROGRAM: #include <stdio.h> void printAverage(int [][3], int, int); int main(void) { // variables int ROWS = 5, COLS = 3; int score[5][3] = { {60, 70, 80}, {90, 50, 70}, {80, 75, 75}, {90, 85, 81}, {60, 75, 80} }; printAverage(score, ROWS, COLS); return 0; } void printAverage(int arr[][3], int rows, int cols) { // variablesInt r, c; Float sum, avg; // find average and print it for (r = 0; r < rows; r++) { sum = 0; for (c = 0; c < cols; c++) { sum += arr[r][c]; } avg = sum / cols; printf("Average on Day #%d = %fn", (r + 1), avg); } }
  • 11. 3)Implement C Program using Pointers and Structure AIM: writer a program to implement a structure using a pointer variable ALGORITHM: 1.Create the structure employee with its variable name[30],id age, and character gender[30],andcity[40]. 2.And create the structure pointers *p1 and *p2 and its corresponding structure variable emp1 andemp2. 3.Store the address of the emp1 and emp2 structure variable. 4. Assign the each and every data to the variables. 5.And print the assigned the variables data in a output. PROGRAM: include<stdio.h> struct Employee { char name[30]; int id; int age; char gender[30]; char city[40]; }; struct Employee emp1,emp2,*ptr1,*ptr2; int main() { ptr1=&emp1; ptr2=&emp2; printf (" Enter the name of the Employee(emp1):"); scanf("%s",&ptr1->name); printf("Enter the id of the Employee (emp1): "); scanf("%d",&ptr1->id); printf("Enter the age of the Employee (emp1):"); scanf("%d",&ptr1->age); printf("Enter the gender of the Employee(emp1):"); scanf("%s",&ptr1->gender); printf("Enter the city of the Employee (emp1):"); scanf("%s",&ptr1->city); printf("n Second Employee: n"); printf(" Enter the name of the Employee (emp2):"); scanf("%s",&ptr2->name);
  • 12. printf("Enter the id of the Employee (emp2):"); scanf("%d",&ptr2->id); printf("Enter the age of the Employee (emp2):"); scanf("%d",&ptr2->age); printf("Enter the gender of the Employee (emp2): "); scanf("%s",&ptr2->gender); printf("Enter the city of the Employee (emp2): "); scanf("%s", &ptr2->city); printf("n Display the Details of the Employee using Structure Pointer"); printf ("n Details of the Employee (emp1)n"); printf(" Name: %sn", ptr1->name); printf("Id:%dn",ptr1->id); printf("Age:%dn",ptr1->age); printf("Gender:%sn",ptr1->gender); printf("City:%sn",ptr1->city); printf ("n Details of the Employee (emp2)n"); printf("Name: %sn", ptr2->name); printf("Id: %dn", ptr2->id); printf("Age: %dn", ptr2->age); printf("Gender:%sn",ptr2->gender); printf("City:%sn",ptr2->city); return 0; }
  • 13. 4. Implement C program using Files AIM: Write a Program in C to Read and Write the Contents of a File. ALGORITHM: 1: Start the Program. 2: Initialize the File Pointer. 3: Open the File in the Write Mode Using File Pointer. 4: Enter the Data. 5: Store the input data in the file using the putc() Statement. 6: Close the File. 7: Open the File in the Read Mode using the File Pointer. 8: Print the data in the file. SOURCE CODE : #include<stdio.h> #include <stdlib.h> struct person { int id; char fname[20]; char lname[20]; }; int main () { FILE *infile; struct person input; // Open person.dat for reading infile = fopen ("person.dat", "r"); if (infile == NULL) { fprintf(stderr, "nError opening filen"); exit (1); } // read file contents till end of file while(fread(&input, sizeof(struct person), 1, infile)) printf ("id = %d name = %s %sn", input.id, input.fname, input.lname); // close file fclose (infile); return 0; }
  • 14. 5.Implementation of C program in real time AIM: Write a c porgram to implement the real time implementation by creating a text editor. ALGORITHM: 1.Display options new, open and exit and get choice. 2.If choice is 1 , call Create() function. 3.If choice is 2, call Display() function. 4.If choice is 3, call Append() function. 5.If choice is 4, call Delete() function. 6.If choice is 5, call Display() function. 7.Create() Get the file name and open it in write mode.Get the text from the user to write it. 8.Display()Get the file name from user.Check whether the file is present or not. 9 If present then display the contents of the file. 10Append()Get the file name from user.Check whether the file is present or not. If present then append the file by getting the text to add with the existing file. 10. Delete() Get the file name from user. Check whether the file is present or not. If present then delete the existing file.
  • 15. PROGRAM: #include<stdio.h> #include<conio.h> #include<process.h> int i,j,ec,fg,ec2; char fn[20],e,c; FILE *fp1,*fp2,*fp; void Create(); void Append(); void Delete(); void Display(); void main() { do { clrscr(); printf("ntt***** TEXT EDITOR *****"); printf("nntMENU:nt - n "); printf("nt1.CREATEnt2.DISPLAYnt3.APPENDnt4.DELETEnt5.EXITn"); printf("ntEnter your choice: "); scanf("%d",&ec); switch(ec) { case 1: Create(); break; case 2: Display(); break; case 3: Append(); break; case 4: Delete(); break; case 5: exit(0); } }while(1); } void Create() { fp1=fopen("temp.txt","w"); printf("ntEnter the text and press '.' to savennt"); while(1) {
  • 16. c=getchar(); fputc(c,fp1); if(c == '.') { fclose(fp1); printf("ntEnter then new filename: "); scanf("%s",fn); fp1=fopen("temp.txt","r"); fp2=fopen(fn,"w"); while(!feof(fp1)) { c=getc(fp1); putc(c,fp2); } fclose(fp2); break; } } } void Display() { printf("ntEnter the file name: "); scanf("%s",fn); fp1=fopen(fn,"r"); if(fp1==NULL) { printf("ntFile not found!"); goto end1; } while(!feof(fp1)) { c=getc(fp1); printf("%c",c); } end1: fclose(fp1); printf("nntPress any key to continue..."); getch(); } void Delete() { printf("ntEnter the file name: ");
  • 17. scanf("%s",fn); fp1=fopen(fn,"r"); if(fp1==NULL) { printf("ntFile not found!"); goto end2; } fclose(fp1); if(remove(fn)==0) { printf("nntFile has been deleted successfully!"); goto end2; } else printf("ntError!n"); end2: printf("nntPress any key to continue..."); getch(); } void Append() { printf("ntEnter the file name: "); scanf("%s",fn); fp1=fopen(fn,"r"); if(fp1==NULL) { printf("ntFile not found!"); goto end3; } while(!feof(fp1)) { c=getc(fp1); printf("%c",c); } fclose(fp1); printf("ntType the text and press 'Ctrl+S' to append.n"); fp1=fopen(fn,"a"); while(1) { c=getch(); if(c==19) goto end3; if(c==13) {
  • 19. 6) Array implementation of List ADT: AIM: Write a program to implement a list ADT c program to create and edit the list by using the structurelist. ALGORITHM: 1. create a file named larray.h. 2. In this file create a structure pointer. 3. create the position pointer. 4. In this file only we can insert delete modify the lists. . 5. write a larray.c main() program. 6. In a main program we ca create insert edit and modify are all performed in a switch case. PROGRAM: “Larray.h”File: #include<stdio.h> #include<alloc.h> #include<conio.h> struct list { int capacity; int size; int *array; }; typedef struct list *ptrToNode; typedef ptrToNode LIST; typedef int POSITION; int Isempty(LIST L) { return L->size==0; } void MakeEmpty(LIST L) { if(Isempty(L)) printf("n LIST is already Empty");else { L->size=0; printf("n Now List becomes Empty"); } } LIST Createlist(int max)
  • 20. { LIST L; L=(struct list*)malloc(sizeof(struct list)); if(L==NULL) printf("n Fatal Error"); else { L->capacity=max; L->array=(int*)malloc(sizeof(int)*max); if(L->array==NULL) printf("n Fatal Error"); else { L->size=0; printf("n List is Created successfully"); } } return L; } int Isfull(LIST L) { return L->size==L->capacity; } void Insert(int x,LIST L,POSITION P) { int i; if(Isfull(L)) printf("n List is Full"); else { for(i=L->size-1;i>=P;i--) L->array[i+1]=L->array[i]; L->size++; L->array[P]=x; } } POSITION Findprevious(int x,LIST L) { POSITION P; P=-1; while(P!=L->size&&L->array[P+1]!=x)
  • 21. { P++; } return P; } POSITION Find(int x,LIST L) { POSITION P; P=0; while(P!=L->size&&L->array[P]!=x) { P++; } return P; } void Delete(int x,LIST L) { int i; POSITION P; P=Find(x,L); if(P==L->size) printf("n Element not found in the list"); else { for(i=P;i<L->size;i++) L->array[i]=L- >array[i+1];L->size--; } } LIST Deletelist(LIST L) { MakeEmpty( L);free(L); L=NULL; return L; } void Display(LIST L) {
  • 22. int i; for(i=0;i<L->size;i++) printf("n %d",L- >array[i]); } “Larray.c” File: #include"Larray.h" #include<stdlib.h> void main() { LIST L=NULL;POSITION P; int a,choice,ch,element; clrscr(); printf("nn1.Createn2.Insertn3.Deleten4.Displayn5.MakeEmptyn6.Findn7.IsEmptyn8.I sFulln9.Deletelistn10.Exitn"); 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);
  • 23. else { printf("n where u want to insert?t1:Frontt2:Backt3:middlet::: "); 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;
  • 24. 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 %dt[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");
  • 25. else { L=Deletelist(L); printf("n List is Deleted"); } break; case 10: exit (0); break; default: printf("nn *******WRONG ENTRY*******"); break; } goto A; }
  • 26. 7) a)Array implementation of stack Aim: Write a program that implement Stack (its operations) using Arrays. ALGORITHM: 1. Create a stack st[max]. 2. wite a separate operation for stack operation. 3. write a push() function this is used to insert the value to the stack. 4. write a pop() function this is used to retrieve the stack value. 5. These are all performed by the stack pointer. 6. If the stack pointer reach the top of the stack it displays stack is full. 7. If the stack pointer reach the bottom of the stack it displays stack is empty. Source Code: #include<stdio.h> #include<conio.h> #define max 5 int st[max],top=-1; void push() { int x; if(top==max-1) { printf("stack is full"); return; } printf("enter element"); scanf("%d",&x); top++; st[top]=x; } void pop() { int x; if(top==-1) { printf("stack is empty"); return; } printf("enter element"); scanf("%d",&x); top--; printf("enter deleted element=%d",x); } void display() { int i;
  • 27. if(top==-1) { printf("stack is empty"); return; } for(i=top;i>=0;i--) { printf("%d",st[i]); } } int main() { int ch; while(1) { printf("enter n1.pushn2.popn3.displayn4.exit"); scanf("%d",&ch); switch(ch) { case 1: push(); break; case 2: pop(); break; case 3: display(); break; case 4: exit(1); break; } } return 1; }
  • 28. b) Array implementation using queue Aim: Write a program that implement Queue (its operations) using Arrays. ALGORITHM: 1. First create a queue with size. 2. And then mention the front and rear. 3. If the front reaches the firs position in the queue the rear will be added by 1. 4. If the rear reaches the last position of the queue it indicates thus the queue reached the last position. 5. And then it displays thus the insertion is not possible. 6. In this thus the void display() function is used to display the queue items. PROGRAM: #include<stdio.h> #include<conio.h> #define SIZE 5 int queue[SIZE], front = -1, rear = -1; void enQueue(int value) { if(rear == SIZE-1) printf("nQueue is Full!!! Insertion is not possible!!!"); else { if(front == -1) front = 0; rear++; queue[rear] = value; printf("nInsertion success!!!"); } } void deQueue() { if(front == rear) printf("nQueue is Empty!!! Deletion is not possible!!!"); else{ printf("nDeleted : %d", queue[front]); front++; if(front == rear) front = rear = -1; }
  • 29. void display() { if(rear == -1) printf("nQueue is Empty!!!"); else { int i; printf("nQueue elements are:n"); for(i=front; i<=rear; i++) printf("%dt",queue[i]); } } void main() { int value, choice;while(1){ printf("nn***** MENU *****n"); printf("1. Insertionn2. Deletionn3. Displayn4. Exit"); printf("nEnter your choice: "); scanf("%d",&choice); switch(choice) { case 1: printf("Enter the value to be insert: "); scanf("%d",&value); enQueue(value); break; case 2: deQueue(); break; case 3: display(); break; case 4: exit(0); default: printf("nWrong selection!!! Try again!!!"); } }
  • 30. 8) i)Linked list implementation of list stack AIM: Write a program to implement the stack operation using the liked list ALGORITHM: 1. Create a structure named node. 2. And create a functions named push(),pop(),empty(),display(),stack_count(). 3. These functions are all performed in a while condition to insert or delete or display our stack operation. 4. If the stack pointer reaches the top of the stack value thus it indicates thus the stack. is full. 5. When we remove the one value from the stack the stack pointer value is decremented by one. 6. When we enter the one element in a stack the stack pointer has been incremented by one. 7. If the stack pointer reaches the top it tells us stack is full we cannot add the value to the stack. 8. If it reaches the bottom of the stack it indicates thus the stack is empty. PROGRAM: #include <stdio.h> #include <stdlib.h> struct node { int info; struct node *ptr; }*top,*top1,*temp; int topelement(); void push(int data); void pop(); void empty(); void display(); void destroy(); void stack_count(); void create(); int count =0; void main() { int no, ch, e; printf("n 1 - Push"); printf("n 2 - Pop"); printf("n 3 - Top"); printf("n 4 - Empty"); printf("n 5 - Exit"); printf("n 6 - Dipslay");
  • 31. printf("n 7 - Stack Count"); printf("n 8 - Destroy stack"); create(); while(1) { printf("n Enter choice : "); scanf("%d",&ch); switch(ch) { case1: printf("Enter data : "); scanf("%d",&no); push(no); break; case2: pop(); break; case3: if(top == NULL) printf("No elements in stack"); else { e = topelement(); printf("n Top element : %d", e); } break; case4: empty(); break; case5: exit(0); case6: display(); break; case7: stack_count(); break; case8: destroy(); break; default: printf(" Wrong choice, Please enter correct choice "); break; } } }
  • 32. /* Create empty stack */ void create() { top = NULL; } /* Count stack elements */ void stack_count() { printf("n No. of elements in stack : %d", count); } . /* Push data into stack */ void push(int data) { if(top == NULL) { top =(struct node *)malloc(1*sizeof(struct node)); top->ptr = NULL; top->info = data; } else { temp =(struct node *)malloc(1*sizeof(struct node)); temp->ptr = top; temp->info = data; top = temp; } count++; } /* Display stack elements */ void display() { top1 = top; if(top1 == NULL) { printf("Stack is empty"); return; } while(top1 != NULL) { printf("%d ", top1->info); top1 = top1->ptr; } }
  • 33. /* Pop Operation on stack */ void pop() { top1 = top; if(top1 == NULL) { printf("n Error : Trying to pop from empty stack"); return; } else top1 = top1->ptr; printf("n Popped value : %d", top->info); free(top); top = top1; count--; } /* Return top element */ int topelement() { return(top->info); } /* Check if stack is empty or not */ void empty() { if(top == NULL) printf("n Stack is empty"); else printf("n Stack is not empty with %d elements", count); } /* Destroy entire stack */ void destroy() { top1 = top; while(top1 != NULL) { top1 = top->ptr; free(top); top = top1; top1 = top1->ptr; } free(top1); top = NULL; printf("n All stack elements destroyed"); count =0; }
  • 34. b)program using queue: AIM: Write a program to implement a linked list operation by using a queue. ALGORITHM: 1. Create a structure node with structure pointer front and back. 2. And create a queue to insert and delete the queue with the queue size. 3. If the front of the queue is null and thus the queue is ready to intake the input. 4. And the back of the queue is full it indicates thus the queue if full. 5. Thus the front and back of the queue is indicates thus the stack pointer. 6. If it moves front means thus the stack pointer is incremented by one. 7. If it moves back means in the queue thus the stack pointer is decremented by one. PROGRAM: #include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; } *front, *back; /* Create an empty queue */ void initialize() { front = back = NULL; } /* Returns queue size */ int getQueueSize() { struct node *temp = front; int count = 0; if(front == NULL && back == NULL) return 0; while(temp != back) { count++; temp = temp->next; } if(temp == back) count++; return count; } /* Returns Frnt Element of the Queue */ int getFrontElement() {
  • 35. return front->data; } /* Returns the Rear Element of the Queue */ int getBackElement() { return back->data; } /*Check's if Queue is empty or not */ void isEmpty() { if (front == NULL && back == NULL) printf("Empty Queuen"); else printf("Queue is not Emptyn"); } /*Adding elements in Queue*/ void enqueue(int num) { struct node *temp; temp = (struct node *)malloc(sizeof(struct node)); temp->data = num; temp->next = NULL; if (back == NULL) { front = back = temp; } else { back->next = temp;back = temp; } } /*Removes an element from front of the queue*/ void dequeue() { struct node *temp; if (front == NULL) { printf("nQueue is Empty n"); return; } else { temp = front; front = front->next; if(front == NULL) { back = NULL; }
  • 36. printf("Removed Element : %dn", temp->data); free(temp); } } /*Print's Queue*/ void printQueue() { struct node *temp = front; if ((front == NULL) && (back == NULL)) { printf("Queue is Emptyn"); return; } while (temp != NULL) { printf("%d", temp->data); temp = temp->next; if(temp != NULL) printf("-->"); } } int main() { /* Initializing Queue */initialize(); /* Adding elements in Queue */ enqueue(1); enqueue(3); enqueue(7); enqueue(5); enqueue(10); /* Printing Queue */ printQueue(); /* Printing size of Queue */ printf("nSize of Queue : %dn", getQueueSize()); /* Printing front and rear element of Queue */ printf("Front Element : %dn", getFrontElement()); printf("Rear Element : %dn", getBackElement()); /* Removing Elementd from Queue */dequeue(); dequeue(); dequeue(); dequeue(); dequeue(); dequeue(); return 0; }
  • 37. 9.Applications of list ,stack and queue ADT’s i)Convertion of infix to postfix using stack: AIM: Write a program to implement a infix to postfix using the stack operation ALGORITHM: 1. Start the program. 2. create the stack size of 100. 3. An create the push and pop operation to insert and remove the element from stack. 4. 4.In the main program create the character variable size of 100. 5. Create the pointer variable for that based on that we can call the function puh and pop. 6. . . Execute that in a while statement. 7 . Print that case statement output. 8. . Stop the program. PROGRAM: #include<stdio.h> #include<ctype.h> char stack[100]; int top =-1; voidpush(char x) { stack[++top]= x; } charpop() { if(top ==-1) return-1; else return stack[top--]; } intpriority(char x) { if(x =='(')return0; if(x =='+'|| x =='-') return1; if(x =='*'|| x =='/') return2; return0; }
  • 38. intmain() { char exp[100];char*e, x; printf("Enter the expression : "); scanf("%s",exp); printf("n");e = exp; while(*e !='0') { if(isalnum(*e)) printf("%c ",*e); elseif(*e =='(')push(*e); elseif(*e ==')') { while((x =pop())!='(') printf("%c ", x); } else { while(priority(stack[top])>=priority(*e)) printf("%c ",pop()); push(*e); } e++; } while(top !=-1) { printf("%c ",pop()); }return0; }
  • 39. ii)Queue application: AIM: Write a program to implement a queue application to display the queue items. ALGORITHM: 1. Start the program 2. Create the function enqueue(), and dequeue(), and show() 3. .Based on the enqueuer() we can add the element in the queue 4. In the dequeuer() is used to revoke the elment in the queue 5. The show() is used to display the elements available in the queue 6. And then the final exit function is used to terminate the queue items PROGRAM: #include <stdio.h> # define SIZE 100void enqueue(); void dequeue(); void show(); int inp_arr[SIZE]; int Rear = - 1; int Front = - 1; main() { int ch; while (1) { printf("1.Enqueue Operationn"); printf("2.Dequeue Operationn"); printf("3.Display the Queuen"); printf("4.Exitn"); printf("Enter your choice of operations : "); scanf("%d", &ch); switch (ch) { case 1: enqueue(); break; case 2: dequeue(); break; case 3: show(); break; case 4: exit(0); default: printf("Incorrect choice n"); }
  • 40. } } void enqueue() { int insert_item; if (Rear == SIZE - 1) printf("Overflow n"); else { if (Front == - 1) Front = 0; printf("Element to be inserted in the Queuen : "); scanf("%d", &insert_item); Rear = Rear + 1; inp_arr[Rear] = insert_item; } } void dequeue() { if (Front == - 1 || Front > Rear) { printf("Underflow n"); return ; } else { printf("Element deleted from the Queue: %dn", inp_arr[Front]); Front = Front + 1; } } void show() { if (Front == - 1) printf("Empty Queue n");else { printf("Queue: n"); for (int i = Front; i <= Rear; i++) printf("%d ", inp_arr[i]); printf("n"); } }
  • 41. 10.Implementation of binry tree with its operation AIM: Write a program to implement the binary tree with its operations. ALGORITHM: 1: Start the Program. 2: Declare a Template for Key and Elements. 3: Insert the Key-Element Pair into the Tree, overwriting Existing pair, if any, with same key. 4: Find place to Insert. While P != NULL. 5: Examine Element pointed to by Pair. Move P to a Child 6: If Pair First Element is Less Than Element of first P, assign P as Left Child. 7: If Pair First Element is Greater than Element of first P, assign P as Right Child 8: Else, Replace Old Value 9: Retrieve a Node for the Pair and assign to Pair Pointer Element 10: If Root != NULL, the tree is not Empty. 11: Now, Handle Input Operation – Insert, Delete, ListOrder Accordingly 12: If Pair First Element is Less Than Pair Pointer First Element; LeftChildNode = NewNode. 13: Else, Pair Pointer First Element RightChildNode = NewNode. Else, Root = NewNode 14: Insert Operation Into Tree Successful. 15: Stop PROGRAM: # include <stdio.h> # include <malloc.h> struct node { int info; struct node *lchild; struct node *rchild; }*root; void find(int item,struct node **par,struct node **loc) { struct node *ptr,*ptrsave; if(root==NULL) /*tree empty*/ { *loc=NULL; *par=NULL; return; } if(item==root->info) /*item is at root*/ { *loc=root; *par=NULL; return; } /*Initialize ptr and ptrsave*/ if(item<root-
  • 42. >info)ptr=root- >lchild; else ptr=root->rchild; ptrsave=root; while(ptr!=NULL) { if(item==ptr->info) { *loc=ptr; *par=ptrsave; return; } ptrsave=ptr; if(item<ptr->info) ptr=ptr->lchild; else ptr=ptr->rchild; }/*End of while */ *loc=NULL; /*item not found*/ *par=ptrsave; }/*End of find()*/ void insert(int item) { struct node *tmp,*parent,*location; find(item,&parent,&location); if(location!=NULL) { printf("Item already present"); return; } tmp=(struct node *)malloc(sizeof(struct node)); tmp->info=item; tmp->lchild=NULL; tmp->rchild=NULL; if(parent==NULL) root=tmp; else if(item<parent->info) parent->lchild=tmp; else parent->rchild=tmp; }/*End of insert()*/ void case_a(struct node *par,struct node *loc ) { if(par==NULL) /*item to be deleted is root node*/root=NULL; else if(loc==par->lchild) par->lchild=NULL; else par->rchild=NULL;
  • 43. }/*End of case_a()*/ void case_b(struct node *par,struct node *loc) { struct node *child; /*Initialize child*/ if(loc->lchild!=NULL) /*item to be deleted has lchild */ child=loc->lchild; else child=loc->rchild; if(par==NULL ) /*Item to be deleted is root node*/ root=child; else if( loc==par->lchild) /*item is lchild of its parent*/ par->lchild=child; else /*item is rchild of its parent*/ par->rchild=child; }/*End of case_b()*/ void case_c(struct node *par,struct node *loc) { struct node *ptr,*ptrsave,*suc,*parsuc; /*Find inorder successor and its parent*/ ptrsave=loc; ptr=loc->rchild; while(ptr->lchild!=NULL) { ptrsave=ptr; ptr=ptr->lchild; } suc=ptr; parsuc=ptrsave; if(suc->lchild==NULL && suc->rchild==NULL) case_a(parsuc,suc); else case_b(parsuc,suc); if(par==NULL) /*if item to be deleted is root node */ root=suc; else if(loc==par->lchild) par->lchild=suc; else par->rchild=suc; suc->lchild=loc- >lchild;suc- >rchild=loc->rchild;
  • 44. }/*End of case_c()*/ int del(int item) { struct node *parent,*location; if(root==NULL) { printf("Tree empty"); return 0; } find(item,&parent,&location); if(location==NULL) { printf("Item not present in tree"); return 0; } if(location->lchild==NULL && location->rchild==NULL) case_a(parent,location); if(location->lchild!=NULL && location->rchild==NULL) case_b(parent,location); if(location->lchild==NULL && location-.>rchild!=NULL) case_b(parent,location); if(location->lchild!=NULL && location-..>rchild!=NULL) case_c(parent,location); free(location); }/*End of del()*/ int preorder(struct node *ptr) { if(root==NULL) { printf("Tree is empty"); return 0; } if(ptr!=NULL) { printf("%d ",ptr-..>info); preorder(ptr->lchild); preorder(ptr->rchild); } }/*End of preorder()*/ void inorder(struct node *ptr) { if(root==NULL) { printf("Tree is empty"); return; } if(ptr!=NULL) { inorder(ptr->lchild);
  • 45. printf("%d ",ptr->info); inorder(ptr->rchild); } }/*End of inorder()*/ void postorder(struct node *ptr) if(location==NULL) { printf("Item not present in tree"); return 0; } if(location->lchild==NULL && location->rchild==NULL) case_a(parent,location); if(location->lchild!=NULL && location->rchild==NULL) case_b(parent,location); if(location->lchild==NULL && location->rchild!=NULL) case_b(parent,location); if(location->lchild!=NULL && location->rchild!=NULL) case_c(parent,location); free(location); }/*End of del()*/ int preorder(struct node *ptr) { if(root==NULL) { printf("Tree is empty"); return 0; } if(ptr!=NULL) { printf("%d ",ptr->info); preorder(ptr->lchild); preorder(ptr->rchild); } }/*End of preorder()*/ void inorder(struct node *ptr) { if(root==NULL) { printf("Tree is empty"); return; } if(ptr!=NULL) { inorder(ptr->lchild); printf("%d ",ptr->info); inorder(ptr->rchild); } }/*End of inorder()*/ void postorder(struct node *ptr)
  • 46. { if(root==NULL) { printf("Tree is empty"); return; } if(ptr!=NULL) { postorder(ptr->lchild); postorder(ptr->rchild); printf("%d ",ptr->info); } }/*End of postorder()*/ void display(struct node *ptr,int level) { int i; if ( ptr!=NULL ) { display(ptr->rchild, level+1);printf("n"); for (i = 0; i < level; i++) printf(""); printf("%d", ptr->info); display(ptr->lchild, level+1); }/*End of if*/ }/*End of display()*/ main() { int choice,num;root=NULL; while(1) { printf("n"); printf("1.Insertn"); printf("2.Deleten"); printf("3.Inorder Traversaln"); printf("4.Preorder Traversaln"); printf("5.Postorder Traversaln"); printf("6.Displayn"); printf("7.Quitn"); printf("Enter your choice : "); scanf("%d",&choice); switch(choice) { case 1: printf("Enter the number to be inserted : "); scanf("%d",&num); insert(num); break;
  • 47. case 2: printf("Enter the number to be deleted : "); scanf("%d",&num); del(num); break; case 3: inorder(root); break; case 4: preorder(root); break; case 5: postorder(root); break; case 6: display(root,1); break; case 7: break; default: printf("Wrong choicen"); }/*End of switch */ }/*End of while */ }/*End of main()*
  • 48. EX.NO.11 Implementation of binary search tree AIM: Write a program to implement to a binary search tree. ALGORITHM: 1. Start the program. 2. Create the structure BST. 3. Create the the structure pointer *left an *right. 4. Create structure variable node. 5. In this if the root is empty insert the value to the root nod. 6. And find the left and right node by using the left and right pointer. 7. Once the tree element insertion is completed we have to search the element in the tree 8. In this left search and right search has been made. 9. Stop the program. PROGRAM: #include<stdio.h> #include<stdlib.h> typedef struct BST { int data; struct BST *left; struct BST *right; }node; node *create(); void insert(node *,node *); void preorder(node *); int main() { char ch; node *root=NULL,*temp; do { temp=create(); if(root==NULL) root=temp; else insert(root,temp); printf("nDo you want to enter more(y/n)?"); getchar(); scanf("%c",&ch); }while(ch=='y'|ch=='Y'); printf("nPreorder Traversal: "); preorder(root); return 0; }
  • 49. node *create() { node *temp; printf("nEnter data:"); temp=(node*)malloc(sizeof(node)); scanf("%d",&temp->data); temp->left=temp->right=NULL; return temp; } void insert(node *root,node *temp) { if(temp->data<root->data) { if(root->left!=NULL) insert(root->left,temp); else root->left=temp; } if(temp->data>root->data) { if(root->right!=NULL) insert(root->right,temp); else root->right=temp; } } void preorder(node *root) { if(root!=NULL) { printf("%d ",root->data); preorder(root->left); preorder(root->right); } }
  • 50. EX.NO.12 Implementation of searching techniques AIM: Write a program to implement a searching techniques in a tree. ALGORITHM: 1. i is used for iteration through the array. 2. low is used to hold the first array index. 3.high is used to hold the last array index. 3. mid holds the middle value calculated by adding high and low and dividing it by 2. 4. n is the of elements in the array. 5. key is the element to search. 6. array is the array element of size 100. i)Normal search tree PROGRAM: #include <stdio.h> int main() { int i, low, high, mid, n, key, array[100]; printf("Enter number of elementsn"); scanf("%d",&n); printf("Enter %d integersn", n); for(i = 0; i < n; i++) scanf("%d",&array[i]); printf("Enter value to findn"); scanf("%d", &key); low = 0; high = n - 1; mid = (low+high)/2; while (low <= high) { if(array[mid] < key) low = mid + 1; else if (array[mid] == key) { printf("%d found at location %d.n", key, mid+1); break; } else high = mid - 1; mid = (low + high)/2; } if(low > high) printf("Not found! %d isn't present in the list.n", key);return 0; }
  • 51. ii)Binary search tree using Recursive function: PROGRAM: #include <stdio.h> int binaryScr(int a[], int low, int high, int m) { if (high >= low) { int mid = low + (high - low) / 2; if (a[mid] == m) return mid; if(a[mid] > m) return binaryScr(a, low, mid - 1, m); return binaryScr(a, mid + 1, high, m); } return -1; } int main(void) { int a[] = { 12, 13, 21, 36, 40 }; int i,m; for(i=0;i<5;i++) { printf(" %d",a[i]); } printf(" n"); int n = sizeof(a) / sizeof(a[0]); printf("Enter the number to be searchedn"); scanf("%d", &m); int result = binaryScr(a, 0, n - 1, m); (result == -1) ? printf("The element is not present in array") printf("The element is present at index %d", result); return 0; }
  • 52. EX.NO.13 Implementation of sorting algorithm i)insertion sort ii) Quick sort iii) Merge sort i) insertion sort: AIM: Write a c porgram to implement the insertion sort. . ALGORITHM: 1: 89 17 8 12 0 (the bold elements are sorted list and non-bold unsorted list) 2: 17 89 8 12 0 (each element will be removed from unsorted list and placed at the rightposition in the sorted list) 3: 8 17 89 12 0 4: 8 12 17 89 0 5: 0 8 12 17 89 PROGRAM: #include<stdio.h> int main() { int i, j, count, temp, number[25]; printf("How many numbers u are going to enter?: "); scanf("%d",&count); printf("Enter %d elements: ", count); // This loop would store the input numbers in array for(i=0;i<count;i++) scanf("%d",&number[i]); // Implementation of insertion sort algorithm for(i=1;i<count;i++) { temp=number[i]; j=i-1; while((temp<number[j])&&(j>=0)) { number[j+1]=number[j]; j=j-1; } number[j+1]=temp; } printf("Order of Sorted elements: "); for(i=0;i<count;i++)
  • 53. printf(" %d",number[i]); return0; } Quick sort algorithm:. Aim: Write a c porgram to implement the Quicksort. Algorithm: 1.If n < = 1, then return. 2. Pick any element V in a[]. This is called the pivot. 3. Rearrange elements of the array by moving all elements xi > V right of V and all elements xi < = Vleft of V. If the place of the V after re-arrangement is j, all elements with value less than V, appear in a[0], a[1] . . . . a[j – 1] and all those with value greater than V appear in a[j +a[n – 1]. 4. Apply quick sort recursively to a[0] . . . . a[j – 1] and to a[j + 1] a[n – 1]. PROGRAM: #include <stdio.h> void quick_sort(int[],int,int);int partition(int[],int,int); int main() { int a[50],n,i; printf("How many elements?"); scanf("%d",&n); printf("nEnter array elements:"); for(i=0;i<n;i++) scanf("%d",&a[i]); quick_sort(a,0,n-1); printf("nArray after sorting:"); for(i=0;i<n;i++) printf("%d ",a[i]); return 0; } void quick_sort(int a[],int l,int u) { int j; if(l<u) { j=partition(a,l,u); quick_sort(a,l,j-1); quick_sort(a,j+1,u); }
  • 54. } int partition(int a[],int l,int u) { int v,i,j,temp;v=a[l]; i=l; j=u+1; do { do i++;. while(a[i]<v&&i<=u ) do j--; while(v<a[j]); if(i<j) { temp=a[i]; a[i]=a[j]; a[j]=temp; } }while(i<j); a[l]=a[j]; a[j]=v; return(j); }
  • 55. ii) Merge sort: program: #include<stdio.h> #define max 10 int a[11]={10,14,19,26,27,31,33,35,42,44,0}; int b[10]; void merging(int low,int mid,int high) { int l1, l2, i; for(l1 = low, l2 = mid +1, i = low; l1 <= mid && l2 <= high; i++) { if(a[l1]<= a[l2]) b[i]= a[l1++]; else b[i]= a[l2++]; } while(l1 <= mid) b[i++]= a[l1++]; while(l2 <= high) b[i++]= a[l2++]; for(i = low; i <= high; i++) a[i]= b[i]; } void sort(int low,int high) { int mid; if(low < high) { mid =(low + high)/2; sort(low, mid); sort(mid+1, high); merging(low, mid, high); } else { return; } }
  • 56. int main() { int i; printf("List before sortingn"); for(i =0; i <= max; i++) printf("%d ", a[i]); sort(0, max); printf("nList after sortingn"); for(i =0; i <= max; i++) printf("%d ", a[i]); }
  • 57. EX.NO.14 Implementation of hashing AIM.. Write a c porgram to implement the Hashing. ALGORITHM: 1. Create an array of structure, data (i.e a hash table). 2. Take a key to be stored in hash table as input. 3. Corresponding to the key, an index will be generated. 4. In case of absence of data in that index of array, create one and insert the data item (key and value)into it and increment the size of hash table. 5. In case the data already exists, the new data cannot be inserted if the already present data does notmatch given key. 6. To display all the elements of hash table, data at each index is extracted and elements (key andvalue) are read and printed. 7. To remove a key from hash table, we will first calculate its index and extract its data, delete the keyin case it matches the given key. 8. Exit PROGRAM: #include<stdio.h> #include<stdlib.h> struct data { int key; int value; }; struct data *array;int capacity =10; int size =0; /* this function gives a unique hash code to the given key */ int hashcode(int key) { return(key % capacity); } /* it returns prime number just greater than array capacity */ int get_prime(int n) { if(n %2==0) { n++; } for(;!if_prime(n); n +=2); return n; }
  • 58. /* to check if given input (i.e n) is prime or not */ int if_prime(int n) { int i; if( n ==1|| n ==0) { return0; } for(i =2; i < n; i++) { { if(n % i ==0) return0; } return1; } void init_array() { int i; capacity = get_prime(capacity); array =(struct data*)malloc(capacity *sizeof(struct data)); . for(i =0; i < capacity; i++) { array[i].key=0; array[i].value= 0; } } /* to insert a key in the hash table */ void insert(int key) { int index = hashcode(key); if(array[index].value==0) { /* key not present, insert it */ array[index].key= key; array[index].value=1; size++; printf("n Key (%d) has been inserted n", key); } elseif(array[index].key== key) { /* updating already existing key */ printf("n Key (%d) already present, hence updating itsvalue n", key);array[index].value+=1; } else
  • 59. { /* key cannot be insert as the index is alreadycontaining some other key */ printf("n ELEMENT CANNOT BE INSERTED n"); } } /* to remove a key from hash table */ void remove_element(int key) { int index = hashcode(key); if(array[index].value==0) { printf("n This key does not exist n"); } else{ array[index].key=0; array[index].value=0; size--; printf("n Key (%d) has been removed n", key); } } /* to display all the elements of a hash table */ void display() { int i; for(i =0; i < capacity; i++) { if(array[i].value==0) { printf("n Array[%d] has no elements n"); } else { printf("n array[%d] has elements -:n key(%d) andvalue(%d) t", i, array[i].key, array[i].value); } } } int size_of_hashtable() { return size; } void main() {
  • 60. int choice, key, value, n, c;clrscr(); init_array( ); do{ printf("n Implementation of Hash Table in C nn"); 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 a Hash Table""nn Please enter your choice -:"); scanf("%d",&choice); switch(choice) { case1: printf("Inserting element in Hash Tablen"); printf("Enter key -:t"); scanf("%d",&key); insert(key); break; case2: printf("Deleting in Hash Table n Enter the key to delete-:"); scanf("%d",&key); remove_element(key); break; case3: n = size_of_hashtable(); printf("Size of Hash Table is-:%dn", n); break; case4: display(); . break; default: . printf("Wrong Inputn"); } printf("n Do you want to continue-:(press 1 for yes)t"); scanf("%d",&c); } while(c ==1); getch(); }