0% found this document useful (0 votes)
31 views76 pages

CS3362 - CPDS Lab Manual - 1

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

CS3362 - CPDS Lab Manual - 1

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

ARM COLLEGE OF ENGINEERING AND TECHNOLOGY

SATTAMANGALAM, MARAIMALAI NAGAR, CHENNAI, TAMIL NADU. PIN-603 209.

ARMCET
(Approved by AICTE & Affiliated to Anna University)

CS3362 – C PROGRAMMING AND DATA STRUCTURE LABORATORY

Name of the Student :

Registration Number :

Department :

Year of Study :

Semester :
ARM COLLEGE OF ENGINEERING AND TECHNOLOGY
SATTAMANGALAM, MARAIMALAI NAGAR, CHENNAI, TAMIL NADU. PIN-603 209.

ARMCET
(Approved by AICTE & Affiliated to Anna University)

BONAFIDE CERTIFICATE

Reg. No.

Certified that this is a Bonafide Record of Practical Work done by


Mr. /Ms ……………………………………………………………………………………………...
of B.E/ B.Tech ………………………………………………………………………………….
of………Semester in ……………………………………………………………………………….
during the academic year…………………

Signature of Lab-In charge Signature of Head of Dept.

Submitted for the practical Examination held on: …./…./…….

Internal Examiner External Examiner


INDEX

S. No DATE NAME OF THE EXPERIMENT PAGE SIGN


NO.
S. No DATE NAME OF THE EXPERIMENT PAGE SIGN
NO.
S. No DATE NAME OF THE EXPERIMENT PAGE SIGN
NO.
Ex. No.1.
Date: Program using c
a) using if b) 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)
{
/* This statement will only execute if the
* above condition (age>=18) returns true
*/
printf("You are eligible for voting");
}
else
{
/* This statement will only execute if the
* condition specified in the "if" returns false.
*/
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
ALGORITHM:
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 y\n");
}
if(x<y)
{
printf("x is less than y\n");
}
if(x==y)
{
printf("x is equal to y\n");
}
printf("End of Program");
return0;
}

OUTPUT:
enter the value of x:20
enter 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 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 other wise print it is not divisible by 3
PROGRAM:
#include <stdio.h>

int main() {

// variable to store the given number


int n;

//take input from the user


scanf("%d",&n);

//if else condition to check whether the number is even or odd


if (n % 2 == 0){

//the number is even


printf("Even ");
//nested if else condition to check if n is divisible by 4 or not
if (n % 4 == 0) {
//the number is divisible by 4
printf("and divisible by 4");
} else {
//the number is not divisible by 4
printf("and not divisible by 4");
}
} else {
//the number is odd
printf("Odd ");

//nested if else condition to check if n is divisible by 3 or not


if(n % 3 == 0) {
//the number is divisible by 3
printf("and divisible by 3");
} else {
//the number is not divisible by 3
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 operands 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

RESULT:
Thus the program implementation using file has been executed successfully
Ex.No: 2 Practice a C programming using Functions & Array

Date:

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
score2.And assign the values to that array

3. And declare integer variable score

4. Declare the function find Average with function variable int[], and int

5.And write the function functions in a function


6.In that function declare the local variables int i, and float sum=0 and avg=0
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: %f\n", avg);
return 0;
}
float findAverage(int arr[], int size) {
// variables
int i;
float sum = 0, avg = 0;
// find total
for (i = 0; i < size; i++)

{
sum += arr[i];
}
// find average
avg = sum / size;

// return average
}

OUTPUT:
Average: 80.000000

RESULT:
Thus the program implementation using file has been executed successfully
b)Function with Two 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
3. And declare integer variable score

4. Declare the function print Average with function variable int[][3], and int,

5.And write the function functions in a function


6. In that function declare the local variables int r,c, and float sum, avg
7.check it in condition in for loop
8. 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) {
// variables
int 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 = %f\n", (r + 1), avg);
}
}

OUTPUT:
Average on Day #1 = 70.000000
Average on Day #2 = 70.000000
Average on Day #3 = 76.666664
Average on Day #4 = 85.333336
Average on Day #5 = 71.666664

RESULT:
Thus the program implementation using file has been executed successfully
Ex.No: 3
Date: Implement C Program using Pointers and Structure

AIM:
write a program to implement a structure union a pointer variable
ALGORITHM:
1. Create the structure employee with its variable name[30],id age, and character gender[30],and
city[40]
2. And create the structure pointers *p1 and *p2 and its corresponding structure variable emp1 and
emp2
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>

//create Employee structure

struct Employee

//define the member of the structure

char name[30];

int id;

int age;

char gender[30];

char city[40];

};

//define the variables of the Structure with pointers

struct Employee emp1,emp2,*ptr1,*ptr2;

int main()
{

//store the address of the emp1 and emp2 structure variable

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: %s\n", ptr1->name);

printf("Id:%d\n",ptr1->id);

printf("Age:%d\n",ptr1->age);

printf("Gender:%s\n",ptr1->gender);

printf("City:%s\n",ptr1->city);

printf ("\n Details of the Employee (emp2)\n");

printf("Name: %s\n", ptr2->name);

printf("Id: %d\n", ptr2->id);

printf("Age: %d\n", ptr2->age);

printf("Gender:%s\n",ptr2->gender);

printf("City:%s\n",ptr2->city);

return 0;

OUTPUT:
Enter the name of the Employee (emp1): John
Enter the id of the Employee (emp1): 1099
Enter the age of the Employee (emp1): 28
Enter the gender of the Employee (emp1): Male
Enter the city of the Employee (emp1): California
Second Employee:
Enter the name of the Employee (emp2): Maria
Enter the id of the Employee (emp2): 1109
Enter the age of the Employee (emp2): 23
Enter the gender of the Employee (emp2): Female
Enter the city of the Employee (emp2): Los Angeles
Display the Details of the Employee using Structure Pointer
Details of the Employee (emp1)
Name: John
Id: 1099
Age: 28
Gender: Male
City: California
Details of the Employee (emp2) Name: Maria
Id: 1109
Age: 23
Gender: Female
City: Los Angeles

RESULT:
Thus the implementation of pointer structure was executed successfully
Ex.No:4

Date: 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 file\n");
exit (1);
} // read file contents till end of file
while(fread(&input, sizeof(struct person), 1, infile))
printf ("id = %d name = %s %s\n", input.id,
input.fname, input.lname);
// close file
fclose (infile);
return 0;
}
OUTPUT:
d = 1 name = rohan sharma
id = 2 name = mahendra dhoni

RESULT:
Thus the program implementation using file has been executed successfully
Ex.No:5
Date: Implementation of C program in real time
AIM:
Write a c program 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.
8.2 If present then display the contents of the file.
9. Append()
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("\n\t\t***** TEXT EDITOR *****");
printf("\n\n\tMENU:\n\t ---- \n ");
printf("\n\t1.CREATE\n\t2.DISPLAY\n\t3.APPEND\n\t4.DELETE\n\t5.EXIT\n");
printf("\n\tEnter 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("\n\tEnter the text and press '.' to save\n\n\t");
while(1)
{
c=getchar();fputc(c,fp1);
if(c == '.')
{
fclose(fp1);
printf("\n\tEnter 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("\n\tEnter the file name: ");
scanf("%s",fn);
fp1=fopen(fn,"r");
if(fp1==NULL)
{
printf("\n\tFile not found!");
goto end1;
}
while(!feof(fp1))
{
c=getc(fp1);
printf("%c",c);
}
end1:
fclose(fp1);
printf("\n\n\tPress any key to continue...");
getch();
}
void Delete()
{
printf("\n\tEnter the file name: ");
scanf("%s",fn);
fp1=fopen(fn,"r");
if(fp1==NULL)
{
printf("\n\tFile not found!");
goto end2;
}
fclose(fp1);
if(remove(fn)==0)
{
printf("\n\n\tFile has been deleted successfully!");
goto end2;
}
else
printf("\n\tError!\n");
end2: printf("\n\n\tPress any key to continue...");
getch();
}
void Append()
{
printf("\n\tEnter the file name: ");
scanf("%s",fn);
fp1=fopen(fn,"r");
if(fp1==NULL)
{
printf("\n\tFile not found!");
goto end3;
}
while(!feof(fp1))
{
c=getc(fp1);
printf("%c",c);
}
fclose(fp1);
printf("\n\tType 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("\n\t");
fputc(c,fp1);
}
else
{
printf("%c",c);
fputc(c,fp1);
}
}
end3: fclose(fp1);
getch();
}

OUTPUT:
FILE CREATION:

DISPLAY:

APPENDAGE:
DISPLAY (AFTER APPENDAGE):

FILE DELETION:

RESULT:
Thus the implementation of text editor was successfully created and executed successfully
Ex.No:6
Date: 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 structure
list

ALGORITHAM
1. create a file named larray.h

2. I n 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("\n\n1.Create\n2.Insert\n3.Delete\n4.Display\n5.MakeEmpty\n6.Find\n7.IsEmpty\n8.IsFull\n9.
Deletelist\n10.Exit\n");
A:
printf("\n Enter Ur Option:\t");
scanf("%d",&choice);
switch(choice)
{
case 1:
if(L==NULL)
L=Createlist(5);
else
printf("\nList is already created");
break;
case 2:
if(L==NULL)
printf("\nList is not yet created");
else
{
printf("\nEnter the Element to insert:\t");
scanf("%d",&element);
if(L->size==0)
Insert(element,L,0);

else
{
printf("\n where u want to insert?\t1:Front\t2:Back\t3:middle\t::: ");
scanf("%d",&ch);
if(ch==1)
Insert(element,L,0);
else
if(ch==2)
Insert(element,L,L->size);
else
if(ch==3)
{
printf("\nWhere you want to insert:\t");
scanf("%d",&a);
P=Find(a,L);
if(P<L->size)
Insert(element,L,P);
else
printf("\nElement is not in the list");
}
else
printf("\n Ur choice is not available");
}
}
break;
case 3:
if(L==NULL)
printf("\nList is not yet created");
if(Isempty(L))
printf("\nList is empty");
else
{
printf("\nEnter the element to delete:\t");
scanf("%d",&a);
Delete(a,L);
}
break;
case 4:
if(L==NULL)
printf("\nList is not yet created");
else
if(Isempty(L))
printf("\nList is empty");
else
{
printf("\nElements present in the list are:");
Display(L);
}
break;
case 5:
if(L==NULL)
printf("\n List is not yet created ");

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

OUTPUT:
1.Create
2.Insert
3.Delete
4. Display
5. MakeEmpty
6.Find
7.IsEmpty
8.IsFull
9.Deletelist
10.Exit

Enter Ur Option: 1
List is created successfully

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

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

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

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

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

Enter Ur Option: 4
Elements present in the list are
100
200
300
400
500

Enter Ur Option: 7
List is not empty

Enter Ur Option: 6
Which element is to find: 500
Element at 4 [0 to 4 – present] [5 – not present]

Enter Ur Option: 3
Enter the element to delete: 300

Enter Ur Option: 4
Elements present in the list are:
100
200
400
500

Enter Ur Option: 8
List is not Full

Enter Ur Option: 5
Now List becomes Empty

Enter Ur Option: 9
List is Deleted

Enter Ur Option: 2
List is not yet created

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

RESULT:
Thus the program implementation using file has been executed successfully
Ex.No:7(a)
Date: Array implementation of stack

Aim:

Write a program that implement Stack (its operations) using Arrays


ALGORITHM:
1. Create a stack st[max]

2. write 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 isplays 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.push\n2.pop\n3.display\n4.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;

Output:

RESULT:
Thus the stack operation of push and pop operation was performed successfully
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("%d\t",queue[i]);
}
}

void main()
{
int value, choice;
while(1){
printf("\n\n***** MENU *****\n");
printf("1. Insertion\n2. Deletion\n3. Display\n4. 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!!!");
}
}

Output:

RESULT:
Thus the queue operations are performed successfully
Ex.No:8(a)
Date: 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(),stck_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.Whenwe 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;
}

OUTPUT:
1 - Push
2 - Pop
3 - Top
4 - Empty
5 - Exit
6 - Dipslay
7 - Stack Count
8 - Destroy stack
Enter choice : 1
Enter data : 56

Enter choice : 1
Enter data : 80

Enter choice : 2

Popped value : 80
Enter choice : 3
Top element : 56
Enter choice : 1
Enter data : 78

Enter choice : 1
Enter data : 90

Enter choice : 6
907856
Enter choice : 7

No. of elements in stack : 3


Enter choice : 8

All stack elements destroyed


Enter choice : 4

Stack is empty
Enter choice : 5

RESULT:
Thus the program for stack using linked list has been implemented successfully.
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 Queue\n");
else
printf("Queue is not Empty\n");
}
/*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 : %d\n", temp->data);
free(temp);

}
}
/*Print's Queue*/
void printQueue() {
struct node *temp = front;
if ((front == NULL) && (back == NULL)) {
printf("Queue is Empty\n");
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 : %d\n", getQueueSize());
/* Printing front and rear element of Queue */
printf("Front Element : %d\n", getFrontElement());
printf("Rear Element : %d\n", getBackElement());

/* Removing Elementd from Queue */


dequeue();
dequeue();
dequeue();
dequeue();
dequeue();
dequeue();
return 0;
}

OUTPUT:

1-->3-->7-->5-->10
Size of Queue : 5
Front Element : 1
Rear Element : 10
Removed Element : 1
Removed Element : 3
Removed Element : 7
Removed Element : 5
Removed Element : 10

Queue is Empty

RESULT:
Thus the program to implement the queue using linked list has been implemented sucessfully
Ex.No:9

Date: Applications of list, stack and queue ADT’s

i) Conversion 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.In the main program create the character variable size of 100
5. Create the pointer variable for that
6. Based on that we can call the function puh and pop
7.Execute that in a while statement
8.Print that case statement output
9.Stop the pogram

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

OUTPUT:

Output Test Case 1:


Enter the expression : a+b*c

a bc*+
Output Test Case 2:
Enter the expression : (a+b)*c+(d-a)

ab+c*da -+
Output Test Case 3:
Enter the expression : ((4+8)(6-5))/((3-2)(2+2))
48+65-32-22+/

RESULT:
Thus the implementation of infix to postfix using stack operation was performed successfully
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() f
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 100
void enqueue();
void dequeue();
void show();
int inp_arr[SIZE];
int Rear = - 1;
int Front = - 1;
main()
{
int ch;
while (1)
{
printf("1.Enqueue Operation\n");
printf("2.Dequeue Operation\n");
printf("3.Display the Queue\n");
printf("4.Exit\n");
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 Queue\n : ");
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: %d\n", 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");
}
}

OUTPUT:

1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 1
Element to be inserted in the Queue: 10

1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 1
Element to be inserted in the Queue: 20

1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 3
Queue:
10 20

1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 2
Element deleted from the Queue: 10

1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations: 3
Queue:
20

RESULT:
Thus the application of the queue operation has been implemented successfully
Ex.No:

Date: Implementation of binary 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 /*item to be deleted has rchild */
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.Insert\n");
printf("2.Delete\n");
printf("3.Inorder Traversal\n");
printf("4.Preorder Traversal\n");
printf("5.Postorder Traversal\n");
printf("6.Display\n");
printf("7.Quit\n");
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 choice\n");
}/*End of switch */
}/*End of while */
}/*End of main()*
OUTPUT:

RESULT:
Thus the C program for Implementation of Implement Binary-Tree Algorithm was written, executed andthe
output was verified successful
Ex.No.11 Implementation of binary search tree

Date:

AIM:
Write a program to implement to a binary search tree

ALGORITHM:

1.Start the program


2.create the structure BST
3.create 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);
}
}
OUTPUT

RESULT:

Thus the c program for binary search tree has been implemented successfully
EX.NO.12 Implementation of searching techniques
Date:

AIM:
Write a program to implement searching techniques in a tree

ALGORITHM:

1. It 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.

4. mid holds the middle value calculated by adding high and low and dividing it by 2.

5. n is the number of elements in the array.

6. key is the element to search.

7. 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;
}
OUTPUT:

If the key is present:

If Key is not present:


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

OUTPUT:

RESULT:
Thus the tree search program was executed successfully
EX.NO.13 Implementation of sorting algorithm

Date: i)insertion sort ii) Quick sort iii) Merge sort

i) Insertion sort:

ALGORITHM:

Step 1: 89 17 8 12 0 (the bold elements are sorted list and non-bold unsorted list)
Step 2: 17 89 8 12 0 (each element will be removed from unsorted list and placed at the right
position in the sorted list)
Step 3: 8 17 89 12 0
Step 4: 8 12 17 89 0
Step 5: 0 8 12 17 89

PROGRAM:

#include<stdio.h>
int main(){

/* Here i & j for loop counters, temp for swapping,


* count for total number of elements, number[] to
* store the input numbers in array. You can increase
* or decrease the size of number array as per requirement
*/
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;
}
OUTPUT:

ii) Quick sort algorithm:

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 < = V
left 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 + 1]......... 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);
}
OUTPUT

RESULT:

Thus the quick sort program in c was executed successfully


iii) 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 sorting\n");
for(i =0; i <= max; i++)printf("%d ", a[i]);
sort(0, max);
printf("\nList after sorting\n");
for(i =0; i <= max; i++)printf("%d ", a[i]);
}
OUTPUT:

List before sorting


10 14 19 26 27 31 33 35 42 44 0
List after sorting
0 10 14 19 26 27 31 33 35 42 44

RESULT:

Thus the merge sort algorithm of c program has been executed successfully
EX.NO.14 Implementation of hashing techniques
Date:
AIM:
Write a program to implement of hashing techniques
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 not
match given key.
6. To display all the elements of hash table, data at each index is extracted and elements (key and
value) are read and printed.
7. To remove a key from hash table, we will first calculate its index and extract its data, delete the key
in 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) and
value(%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 \n\n");
printf("MENU-: \n1.Inserting item in the Hash Table"
"\n2.Removing item from the Hash Table"
"\n3.Check the size of Hash Table"
"\n4.Display a Hash Table"
"\n\n Please enter your choice -:");
scanf("%d",&choice);
switch(choice)
{

case1:

printf("Inserting element in Hash Table\n");


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-:%d\n", n);

break;

case4:

display();

break;

default:

printf("Wrong Input\n");

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


scanf("%d",&c);

}while(c ==1);
getch();
}

OUTPUT:

Implementation of Hash Table in C


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

Please enter your choice-: 3


Size of Hash Table is-: 0

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


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

Please enter your choice-: 1


Inserting element in Hash Table
Enter key -: 1

key (1) and value (1) has been inserted

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


Implementation of Hash Table in C chaining with singly linked list
MENU-:
1. Inserting item in the Hash Table
2. Removing item from the Hash Table
3. Check the size of Hash Table
4. Display Hash Table

Please enter your choice-: 4


array[0] has no elements
array[1] has no elements key = 1 and value = 1
array[2] has no elements
array[3] has no elements
array[4] has no elements
array[5] has no elements
array[6] has no elements
array[7] has no elements
array[8] has no elements
array[9] has no elements
*****************************

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


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

Please enter your choice-: 2


Deleting key from Hash Table
Enter the key to delete-: 3

This key does not exist.

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


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

Please enter your choice-: 2


Deleting key from Hash Table
Enter the key to delete-: 1
Key 1 has been removed.

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

RESULT:
Thus the c program for hash table has been executed successfully

You might also like