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

Fods in C Lab Manual

Uploaded by

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

Fods in C Lab Manual

Uploaded by

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

S.

N
PROGRAM NAME Page No.
O
1 Basic c programs – looping, data manipulations, arrays
a) Armstrong number (using while loop)
b) Sum of digits, reverse, palindrome (using while loop)
c) Factorial of a number (using for loop)
d) Prime numbers ( using for loop)
e) Fibonacci series ( do while loop)
f) Area and circumference of the circle
g) Ternary operator
h) Finding the roots of quadratic equation
i) File operations
k) Total of even integers in an array of n numbers.
l) Matrix multiplication
2 String functions
a) String concatenation
b) String comparison
c) String copy
d) Length of the string
3 Structure, union , pointers
a) Employee details using structure
b) Payroll processing using union
c) Print the elements of array using pointers
4 Dynamic memory allocations
5 Using array
a) Implementation of stack using array
b) Implementation of queue using array
6 Using linked list
a) Stack using linked list
b) Queue using linked list
7 Application of stack and queue
a) Convert infix to postfix expression
b) Breadth first search
8 Implementation of tree and tree traversals
9 Implement binary search tree
10 Search
a) Linear search
b) Binary search
11 Sorting
a) Insertion sort
b) Bubble sort
c) Quick sort
d) Merge sort
12a) Hashing techniques
b) Implement Hash Tables with linear Probing
c) Implement Hash Tables with Quadratic Probing
Om Sakthi

ADHIPARASAKTHI COLLEGE OF ENGINEERING


G.B.NAGAR, KALAVAI-632506, VELLORE DISTRICT

Department of Computer Science and Engineering

LAB MANUAL

FOR

EC8381-FUNDAMENTALS OF DATA STRUCTURES IN C LABORATORY


(II YEAR - ECE)
EC8381 FUNDAMENTALS OF DATA STRUCTURES IN C LABORATORY

Objective:
 To understand and implement basic data structures using C.
 To mapply linear and non-linear data structure in problem solving.
 To learn to implement functions and recursive functions by means of data structures.
 To implement searching and sorting algorithms.

Outcome: The students will be able to,


 Write basic and advanced programs in C.
 Implement functions and recursive functions in C.
 Implement data structures using C.
 Choose appropriate sorting algorithm for an application and implement it in a modular way.

LIST OF EXERCISES

1. Basic C Programs – looping, data manipulations, arrays


2. Programs using strings – string function implementation
3. Programs using structures and pointers
4. Programs involving dynamic memory allocations
5. Array implementation of stacks and queues
6. Linked list implementation of stacks and queues
7. Application of Stacks and Queues
8. Implementation of Trees, Tree Traversals
9. Implementation of Binary Search trees
10. Implementation of Linear search and binary search
11. Implementation Insertion sort, Bubble sort, Quick sort and Merge Sort
12. Implementation Hash functions, collision resolution technique
Ex. No: 1a) BASIC C PROGRAMS – LOOPING, DATA MANIPULATIONS, ARRAYS
LOOPING STATEMENT - Armstrong Number (using while loop)
Date :

AIM: To Write a C program to check whether the given number is Armstrong or not.
ALGORITHM:
Step 1: Start the program
Step2: Read the variable N
Step 3: Assign N1=N;
Step 4: Create Set a loop using the condition WHILE(N1!=0), if the condition true
REM=N1%10;
NUM=NUM+REM*REM*REM;
N1=N1/10;
Step 5: Else, check the condition IF(NUM=N), if the condition true
Step6: PRINT “Armstrong Number”
Step 7: Else PRINT “Not Armstrong Number”
Step 8: Stop the program
PROGRAM: /*program to check whether the given number is Armstrong or not.*/

#include <stdio.h>
#include <conio.h>
void main()
{ int n, n1, rem, num=0;
clrscr();
printf("\nCHECK WHETHER A GIVEN NO. IS ARMSTRONG NO. OR NOT");
printf("Enter a positive integer: ");
scanf("%d", &n);
n1=n;
while(n1!=0)
{ rem=n1%10;
num=num+(rem*rem*rem);
n1=n1/10;
}
if(num==n)
printf("%d is an Armstrong number",n);
else
printf("%d is not an Armstrong number",n);
getch();
}

OUTPUT:

RESULT
Thus the C program to check whether the given number is Armstrong or not was
executed and the output was obtained.
Ex. No: 1b) Sum of digits, Reverse, Palindrome (using while loop)
Date :

AIM: To write a C program to find the sum & reverse of digits and Check is Palindrome or not.

ALGORITHM:
Step 1. Start the program
Step 2. Enter the number.
Step 3. Set a loop upto the number is not equal to zero .
Rem num%10 Sum Sum+rem Rnum rnum *10 +rem Num num/10

Step 4. After the end of the loop print the sum and reverse no of the digit.

Step 5. Find whether the reverse no is equal to the input number. If equal, then it is

Palindrome.

Step 6. Stop the program.

PROGRAM : /* program to find the sum & reverse of digits and Check is Palindrome or not.*/

#include<stdio.h>
#include<conio.h>
void main()
{
unsigned long int a,num,sum=0,rnum=0,rem;
clrscr();
printf("\n Enter the No:");
scanf("%ld",&num);
a=num;
while(num!=0)
{
rem=num%10;
sum=sum+rem;
rnum=rnum*10+rem;

num=num/10;
}
printf("\n The Sum of Digits %ldis=%ld\n",a,sum);
printf("\n The Reverse %ld is=%ld\n",a,rnum);
if(a==rnum)
printf("\n The Given number is a Palindrome");
else
printf("\n The Given number is not a Palindrome");
getch();
}

OUTPUT:

RESULT: Thus the C program to find the sum & reverse of digits and to check whether it is
Palindrome or not was executed and verified successfully
Ex. No: 1c) Factorial of a number (using for loop)
Date :

AIM: To write a program to calculate the factorial of the given number using functions.

ALGORITHM:
Step 1: Start the program
Step2: Enter a number.
Step 3: Set a loop to find the factorial of the given no using Fact=fact*i
Step 4: Print the factorial of the given number.
Step 5: Stop the program

PROGRAM: /* program to calculate the factorial of the given number using functions.*/

#include<stdio.h>
void main()
{
int fact=1,i,num;
printf("Enter the number");
scanf("%d",&num);
for(i=1;i<=num;i++)
{
fact=fact*i;
}
printf("the factorial of %dis %d",num,fact); getch();
}

OUTPUT:

RESULT:
Thus the C program to calculate factorial of the given number using function is

calculated successfully and verified.


Ex. No: 1d) Prime Numbers ( using for loop)
Date :

AIM: To write a program to generate all prime numbers up to nth number.

ALGORITHM :

Step 1: start
Step 2: read n
Step 3: set i=1
Step 4: if (i<=n) go to step 5 otherwise got to step 13
Step 5: set factr = 0
Step 6: set j = 1
Step 7: if(j<=i) go to step 8 otherwise go to step 11
Step 8: if( i mod j ==0) go to step 9 otherwise go to step 10
Step 9 factr =factr+1
Step 10: j=j+1,go to step 7
Step 11: if factr = 2, print i as prime number
Step 12: i=i+1 ,goto step 4
Step 13: stop

PROGRAM: /*Program to generate prime numbers till nth number*/


void main()
{
int n,i,factr,j;
printf("enter the range");
scanf("%d",&n);
printf(“Prime numbers are\n”);
for(i=1;i<=n;i++)
{ factr=0;
for(j=1;j<=i;j++)
{ if(i%j==0)
factr++;
}
if(factr==2)
printf("%d “,i);
}
getch();
}

Input Output

Enter the range 10


Prime numbers are 3 5 7

RESULT: Thus the C program to generate prime numbers till nth number is calculated successfully
and verified
Ex. No: 1e) Fibonacci Series ( do while loop)
Date :

AIM: To write a C program to find the Fibonacci series of the given number.
ALGORITHM:

Step 1: start
Step 2: set f=0,f1=0,f2=1,i=1
Step 3: read n
Step 4: Print f
Step 5: f=f1+f2
Step 6: Print f
Step 7:f2=f1; f1=f; i=i+1
Step 5: if (i<n) ,go to step 5 otherwise go to step10
Step 10: stop

PROGRAM: /*Program to print Fibonacci series*/

void main()
{
int i=1,n,f,f1,f2;
printf("enter the number");
scanf("%d",&n);
f=0;
f1=0;
f2=1;
printf(“FIBONACCI SERIES\n”);
do
{ i++;
printf("%d\n",f);
f=f1+f2;
f2=f1;
f1=f;
}while(i<=n);
}

OUTPUT:

RESULT: Thus the C program to find Fibonacci series of the given number was executed and
verified successfully.
Ex. No : 1f) DATA MANIPULATIONS
Area and Circumference of the Circle
Date :

AIM: To write a C program to find the area and circumference of the circle
ALGORITHM:
Step 1: Start the program.
Step 2: Input the radius of the Circle.
Step 3: Find the area and circumference of the circle using the formula
Area =3.14*r*r
Circum=2*3.14*r
Step 4: Print the area and Circumference
Step 5: Stop the Program
PROGRAM: /*program to find the area and circumference of the circle*/

#include<stdio.h>
#include<conio.h>
void main()
{

float r,area,circum;
clrscr();
printf("\n Enter the radius of the Circle");
scanf("%f",&r);
area=3.14*r*r;
circum=2*3.14*r;
printf("\n Area=%f",area);
printf("\n Circumference=%f",circum);
getch();
}

INPUT AND OUTPUT:

RESULT: Thus the C program to find the area and circumference of the circle has been created
successfully and verified.
Ex. No : 1g) Ternary Operator
Date :

AIM: To write a C program to check the largest number among given two numbers.

ALGORITHM:

Step 1: Start the program


Step 2: Declare the necessary variables.
Step 3: Check if(a > b)
Step 4: If true Print a.
Step 5: Otherwise, Print b
Step 6: Stop the program
PROGRAM: /*program to check the largest number among given two numbers*/

#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b,big; clrscr( );
printf("Enter the value of a: ");

scanf("%d",&a);
printf("Enter the value of b");
scanf(“%d”,&b);
big=(a>b)?a:b;
printf("Biggest of the given numbers is %d",big);
getch();
}

OUTPUT:

RESULT: Thus the program for Conditional Statements has been executed successfully and the output
was verified.
Ex. No : 1h) Finding the Roots of Quadratic Equation
Date :

AIM: To write a C Program to find the roots of a Quadratic equation.

ALGORITHM:
Step 1: Start

Step 2: Read the variable a, b, c.

Step 3: Compute d= b*b - 4*a*c.

Step 4: Test the condition, d is greater than 0 using IF statement.

Calculate: r1= (-b + sqrt(d)) / (2*a).

Calculate: r2= (-b - sqrt(d)) / (2*a).

Print the roots r1 and r2.

Step 5: Else, test the condition, d is equal to 0 using IF statement.

Calculate: r1=r2 = -b / (2*a).

Print the roots r1 and r2.

Step 6: Else, compute real and imaginary as

Calculate: real = -b / (2*a).

Calculate imag = sqrt(-d)/(2*a).

Print the real and imag.

Step 7: Stop

PROGRAM: /*Program to find the roots of a Quadratic equation.*/

#include <stdio.h>
#include <math.h>
#include <conio.h>
void main()
{
float a, b, c, d, r1,r2, real, imag; clrscr();
printf("\nTO FIND THE ROOTS OF A QUADRATIC EQUATION");
printf("\nEnter the coefficients a, b and c: ");
scanf("%f%f%f",&a,&b,&c);
d=b*b-4*a*c;
if (d>0)
{
r1= (-b+sqrt(d))/(2*a);
r2= (-b-sqrt(d))/(2*a);
printf("Roots are: %.2f and %.2f.They are real and distinct.", r1 , r2);
}

else if (d==0)
{
r1 = r2 = -b/(2*a);
printf("Roots are: %.2f and %.2f. They are real and equal.", r1, r2);
}
else
{
real= -b/(2*a);
imag = sqrt(-d)/(2*a);
printf("Roots are: %.2f+%.2fi and %.2f-%.2fi. They are complex.", real, imag,
real, imag);
}
getch();
}

OUTPUT:

RESULT:

Thus the C program for finding roots of quadratic equation was executed and output was
obtained.
Ex. No : 1i) File operations
Date :

AIM: To write a C program to writing some of the characters (without taking input from the keyboard)
and reading, printing, written characters

ALGORITHM:

Step 1: Start the program


Step 2: Open the file in write mode
Step 3: Perform write operation in the file and the close it.
Step 4: Open the same file in read mode
Step 5: By reading the content from the file, print them on the display.
Step 6: Close the file.
Step 7: Stop the program

PROGRAM: /* program to writing some of the characters (without taking input from the
keyboard) and reading, printing, written characters */
#include< stdio.h >
int main()
{
FILE *fp; /* file pointer*/
char fName[20];
printf("\nEnter file name to create :");
scanf("%s",fName);
fp=fopen(fName,"w"); /*creating (open) a file*/
if(fp==NULL) /*check file created or not*/
{
printf("File does not created!!!");
exit(0); /*exit from program*/
}
printf("File created successfully.");
putc('A',fp); /*writting into file*/
putc('B',fp);
putc('C',fp);
printf("\nData written successfully.");
fclose(fp);
fp=fopen(fName,"r"); /*again open file to read data*/
if(fp==NULL)
{
printf("\nCan't open file!!!");
exit(0);
}
printf("Contents of file is :\n");
printf("%c",getc(fp));
printf("%c",getc(fp));
printf("%c",getc(fp));
fclose(fp);
return 0;
}

OUTPUT:

Enter file name to create : ok.txt


File created successfully.
Data written successfully.
Contents of file is :
ABC

RESULT: Thus the C program to writing some of the characters (without taking input from the
keyboard) and reading, printing, written characters was executed and output was obtained.
Ex. No : 1j) File Operations
Date :

AIM: To write a C program to writing characters (by taking input from the keyboard) to the file until
new line is not pressed and reading, printing the file.

PROGRAM: /* program to writing characters (by taking input from the keyboard) to the file
until new line is not pressed and reading, printing the file.*/

#include< stdio.h >


int main()
{
FILE *fp; /* file pointer*/
char fName[20];
char ch;
printf("\nEnter file name to create :");
scanf("%s",fName);
fp=fopen(fName,"w"); /*creating (open) a file*/
if(fp==NULL) /*check file created or not*/
{
printf("File does not created!!!");
exit(0); /*exit from program*/
}
printf("File created successfully.");
printf("\nEnter text to write (press < enter > to save & quit):\n"); /*writting into file*/
while( (ch=getchar())!='\n')
{
putc(ch,fp); /*write character into file*/
}
printf("\nData written successfully.");
fclose(fp);
fp=fopen(fName,"r"); /*again open file to read data*/
if(fp==NULL)
{
printf("\nCan't open file!!!");
exit(0);
}
printf("\nContents of file is :\n");
while( (ch=getc(fp))!=EOF ) /*read text untill, end of file is not detected*/
{
printf("%c",ch); /*print character on screen*/
}
fclose(fp);
return 0;
}
OUTPUT:

Enter file name to create : ok.txt


File created successfully.
Enter text to write (press < enter > to save & quit):
Hello Guys! Learn C Programming here.
Data written successfully.
Contents of file is :
Hello Guys! Learn C Programming here.

RESULT: Thus the C program to writing characters (by taking input from the keyboard) to the file until
new line is not pressed and reading, printing the file was executed and output was obtained.
Ex. No: 1k) ONE DIMENSIONAL ARRAY
Total of even Integers in an Array of N Numbers.
Date :

AIM: To write a C Program to find total of even integers in an array of n numbers.

ALGORITHM

step1: start
Step 2: Read n and , n values to array A[]
Step3: initialize sum=0,i=0
Step 4: if(i<n) go to next step otherwise go to step 8
Step 5: if(A[i]%2==0) go to next step otherwise go to step 7
Step 6: sum=sum+A[i]
Step 7: i=i+1, go to step 4
Step8: print sum
Step 9 :stop

PROGRAM: /*Program to find total of even integers*/

#include<stdio.h>
main()
{
int a[20],i,sum=0;
printf("enter5 integers");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
for(i=0;i<5;i++)
{
if(a[i]%2==0)
sum=sum+a[i];
}
prinf("sum =%d",sum);
getch();
}

OUTPUT :

Entger 5 integers
24782
Sum = 16

RESULT: The program is compiled, executed and the output is verified


Ex. No: 1l) TWO DIMENSIONAL ARRAY
Date : Matrix Multiplication

AIM: To write a C program to perform Matrix Multiplication using array.


ALGORITHM:
Step 1: Start the program
Step 2: Declare variables
Step 3: Get the rows and columns of two matrices M, N, O, P respectively.
Step 4: Check N is not equal to O, if go to step 10.
Step 5: Set a loop and get the elements of first matrix A[i][i].
Step 6: Set a loop and get the elements of second matrix B[i][j].
Step 7: Repeat the step 6 until i<m, j<p and k<n.
Step 8: Initialize C[i][j]=0 and multiply the two matrices and store the resultant in
C[i][j]= C[i][j]+A[i][k]*B[k][j].
Step 9: Print the resultant matrix C[i][j] and go to step 11.
Step 10: Print the message “Column of first matrix must be same as row of second
matrix”.
Step 11: Stop the program.

PROGRAM: /* program to perform Matrix Multiplication using array.*/


#include<stdio.h>
#include<conio.h>
#include<stdio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,m,n,o,p;
clrscr();
printf("\nMATRIX MULTIPLICATION\n");
printf("\n-------------------------------\n");
printf("\nEnter the rows & columns of first matrix: ");
scanf("%d %d",&m,&n);
printf("\nEnter the rows & columns of second matrix: ");
scanf("%d %d",&o,&p);
if(n!=o)
{
printf("Matrix mutiplication is not possible");
printf("\nColumn of first matrix must be same as row of second matrix");
}

else
{
printf("\nEnter the First matrix-->");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter the Second matrix-->");
for(i=0;i<o;i++)
{
for(j=0;j<p;j++)
{
scanf("%d",&b[i][j]);

}
}
printf("\n\nThe First matrix is\n"); for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
}
printf("\n\nThe Second matrix is\n");
for(i=0;i<o;i++)
{
printf("\n");
for(j=0;j<p;j++)
{
printf("%d\t",b[i][j]);
}
}
for(i=0;i<m;i++) //row of first matrix
{
for(j=0;j<p;j++) //column of second matrix

{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]= c[i][j]+a[i][k]*b[k][j];
}
}
}
}
printf("\n\nThe multiplication of two matrix is\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<p;j++)
{
printf("%d\t",c[i][j]);
}
}
getch();
}

OUTPUT:

RESULT: Thus the C program to perform Matrix Multiplication was executed successfully and the output
was verified.
Ex. No: 2a) STRING FUNCTIONS IMPLEMENTATION
String Concatenation
Date :

AIM: To write a program to perform the string Concatenation using C.


ALGORITHM:
Step 1: Start the program
Step 2: Declare the variables.
Step 3: Read input str1 and str2.
Step 4: Concatenate the two strings using for loop..
Step 5: Store the concatenated string into str[k]. Print the String
Step 6: Stop the program

PROGRAM: /* program to perform the string Concatenation using C*/


#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k;
char str[10],str1[10],str2[20];
clrscr();
printf("\n Enter the String1:");
gets(str1);
printf("\n Enter the String2:");
gets(str2);
for(i=0,j=0;str1[i]!='\0';i++,j++)
str[j]=str1[i];
for(i=0,k=j;str2[i]!='\0';i++,k++)
str[k]=str2[i];
str[k]='\0';
printf("\n The Concatenated String is %s",str); getch();
}

OUTPUT:

RESULT: Thus the C program to perform String Concatenation is created successfully and the
output was verified.
Ex. No: 2b) String Comparison
Date :
AIM: To write a program to perform the string Comparison using C.

ALGORITHM:
Step 1: Start the program
Step 2: Declare the variables.
Step 3: Read input str1 and str2.
Step 4: Compare the two strings using for loop..
Step5: If the strings are equal then print “Strings are equal”.
Step 6: If the strings are not equal then print “Strings are not equal”.
Step 7: Stop the program
PROGRAM: /* program to perform the string Comparison using C*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
char str1[10],str2[10];
printf("\n Enter the String1:");
gets(str1);
printf("\n Enter the String2:");
gets(str2);
for(i=0;str1[i]!='\0'||str2[i]!='\0';i++)
if(str1[i]!=str2[i])
{ printf("\n Strings are not equal");
break;
}
else
{ printf("\n Strings are equal");
break;
}
getch();
}
OUTPUT:

RESULT: Thus the C program to perform String Comparison is created successfully and the output
was verified.
Ex. No: 2c) String Copy
Date :

AIM: To write a program to perform the string copy using C.

ALGORITHM:

Step 1: Start the program


Step 2: Declare the variables.
Step 3: Read input str1 and str2.
Step 4: Copy the two strings using for loop..
Step5: Store the string into str2. Print the String
Step 6: Stop the program

PROGRAM: /* program to perform the string copy using C.*/


#include<stdio.h>
void main()
{
int i;
char str1[10],str2[10];
clrscr();
printf(" Enter string 1");
gets(str1);
for(i=0;str1[i]!='\0';i++)
str2[i] = str1[i];
str2[i] = '\0';

printf("\n The Input string is %s",str1);


printf("\n The Copied string2 is %s ",str2);
getch();
}

OUTPUT:

RESULT: Thus the C program to perform String Copy is created successfully and the output was
verified.
Ex. No: 2d) Length of the String
Date :
AIM: To write a program to find the length of the string using C.

ALGORITHM:

Step 1: Start the program


Step 2: Declare the variables.
Step 3: Read input str.
Step 4: Find the string length using for loop..
Step5: Print the String length.
Step 6: Stop the program

PROGRAM: program to find the length of the string using C.

#include<stdio.h>
#include<conio.h>
void main()
{
int i;
char str[20];
clrscr();
printf("\n Enter the String");
gets(str);
for(i=0;str[i]!='\0';++i);
printf("\n The no of characters in the String is %d",i);
getch();
}

OUTPUT:

RESULT: Thus the C program to find length of the string was created successfully and the output was
verified.
Ex. No: 3a) STRUCTURE IN C PROGRAM
Employee Details Using Structure
Date :

AIM: To write a C program to print the employee details of employees using structure.

ALGORITHM:

Step 1: Start the program


Step 2: Declare the variables using structure.
Step 3: Read total number of employees n.
Step 4: Read e[i].eno.e[i].ename,e[i].salary
Step5: Print e[i].eno.e[i].ename,e[i].salary
Step 6: Stop the program.

PROGRAM: /* program to print the employee details of employees using structure.*/


#include<conio.h>
struct emp
{
int eno;
char ename[10];
int salary;
} e[10];

void main()
{
int i,n; clrscr();
printf("Enter Upper limit:");
scanf("%d",&n);
printf("Enter employee details:\n");
printf("Enter the EmployeeNo,Name and Salary:\n");
for(i=0;i<n;i++)
scanf("%d%s%d",&e[i].eno,e[i].ename,&e[i].salary);
printf("\n");
printf("Employee details are \n\n");
printf("Employee Id \t Employee Name \t Salary\n");
for(i=0;i<n;i++)
printf("%d\t\t%s\t\t%d\n",e[i].eno,e[i].ename,e[i].salary);
getch();
}
OUTPUT:

RESULT: Thus the program to print the employee details using structure is created
successfully and the output was verified.
Ex. No: 3b) UNION IN C PROGRAM
Date : Payroll Processing using Union
AIM: To write a C Program to create payroll processing using union.
ALGORITHM:

Step 1: Start the program


Step 2: Declare the Union Employee with data members such as name, eno, basic
salary, net salary, gross.
Step 3: Get the details of an employee.
Step 4: Enter the employee details such as Name, Emp No and Basic salary.
Step5: Copy the emp.ename to Name by using STRCPY(NAME,EMP.ENAME) and
assign ID=EMP.ENO, BASIC=EMP.BSAL.
Step 6: Calculate HRA=10%*BASIC, DA=35%*BASIC, and TDS=15%*BASIC
Step 7: Calculate GROSS=BASIC+HRA+DA and NET SALARY=GROSS-TDS
Step 8: Print Employee salary details such as Name, Id, Basic, HRA, DA, TDS,
GROSS and NET SALARY.
Step 9: Stop the program.

PROGRAM: /* Program to create payroll processingusing union.*/

#include<stdio.h>
#include<string.h>
#include<conio.h>
union employee
{
char ename[30];
int eno;
float bsal;
};
void main()
{
union employee emp; char name[30];
int id;
float basic,hra,da,tds,net,gross;
clrscr();
printf("\EMPLOYEE PAYROLL PROCESSING\n");
printf("\----------------------------------\n");
printf("\nDETAILS OF THE EMPLOYEE\n\n");
printf("\nEnter the Employee Name: ");
scanf("%s",emp.ename);
strcpy(name,emp.ename);
printf("\nEnter the Employee Id: ");
scanf("%d",&emp.eno);
id=emp.eno;

printf("\nEnter the Basic Salary: ");


scanf("%f",&emp.bsal);
basic=emp.bsal;
hra=basic*.10;
da=basic*.35;
tds=basic*.15;
gross=basic+hra+da;
net=gross-tds;
printf("\n\nSALARY DETAILS FOR THE MONTH\n"); printf("\
n-----------------------------\n");
printf("\n\nEmployee Name\t: %s",name); printf("\n\nEmployee
No.\t: %d",id);
printf("\n\nBasic salary\t: %.2f",basic);
printf("\n\nHRA\t\t: %.2f",hra);
printf("\n\nDA\t\t: %.2f",da);
printf("\n\nTDS\t\t: %.2f",tds);
printf("\n\nGross Salary\t: %.2f",gross);
printf("\n\nNet Salary\t: %.2f",net);
getch();
}

OUTPUT:

RESULT: Thus a C program to implement the payroll processing using union was executed and
the output was obtained.
Ex. No: 3c) POINTERS IN C PROGRAM
Date: Print the elements of Array using Pointers

AIM: To write a C Program to print the elements of array using pointers

ALGORITHM:

step1: start
step2: Read array a[] with n elements
Step 3: initialize pointer p=&a[0] [or p=a]
Step 4:if i<n go to next step otherwise go to step 7
Step 5: print *(p+i)
Step 6:i=i+1 go to step 4
Step 7: stop

PROGRAM: /*Program to print the elements of array using pointers*

#include<stdio.h>
main()
{
int a[5]={5,4,6,8,9};
int *p=&a[0];
int i;
clrscr();
for(i=0;i<5;i++)
printf("%d ",*(p+i));
getch();
}

OUTPUT :

54689

RESULT: The program was compiled, executed and the output was verified
Ex. No: 4 DYNAMIC MEMORY ALLOCATIONS
Date:

AIM: To write a C program to create memory for int, char and float variable at run time.

ALGORITHM:

Step 1: Start the program.

Step 2: Declare the variable under int, char and float data type.

Step 3: create memory for int, char and float variables at run time using malloc()function

Step 4: release the memory allocated at run time by using free() function.

Step 5: Stop the program.

PROGRAM: /* program to create memory for int, char and float variable at run time.*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *iVar;
char *cVar;
float *fVar;
iVar=(int*)malloc(1*sizeof(int));
cVar=(char*)malloc(1*sizeof(char));
fVar=(float*)malloc(1*sizeof(float));
printf("Enter integer value: ");
scanf("%d",iVar);
printf("Enter character value: ");
scanf(" %c",cVar);
printf("Enter float value: ");
scanf("%f",fVar);
printf("Inputted value are: %d, %c, %.2f\n",*iVar,*cVar,*fVar);
free(iVar);
free(cVar);
free(fVar);
return 0;
}
OUTPUT:
Enter integer value: 100
Enter character value: x
Enter float value: 123.45
Inputted value are: 100, x, 123.45
RESULT: Thus a C program to implement the Dynamic memory allocation was executed and the
output was obtained.

Note: create memory for text string at run time using malloc() function, text string will be inputted
by the user and displayed. Using free() function we will release the occupied memory.

PROGRAM: /*C program to input and print text using Dynamic Memory Allocation.*/

#include <stdio.h>
#include <stdlib.h>

int main()
{
int n;
char *text;
printf("Enter limit of the text: ");
scanf("%d",&n);
text=(char*)malloc(n*sizeof(char)); /*allocate memory dynamically*/
printf("Enter text: ");
scanf(" "); /*clear input buffer*/
gets(text);
printf("Inputted text is: %s\n",text);
free(text); /*Free Memory*/
return 0;
}

OUTPUT:

Enter limit of the text: 100


Enter text: I am mike from California, I am computer geek.
Inputted text is: I am mike from California, I am computer
geek.

RESULT: Thus a C program to implement the Dynamic memory allocation was executed and the
output was obtained.
Ex. No: 5a) IMPLEMENTATION OF STACK USING ARRAY
Date:

AIM: To write a program to create a Stack and manipulate it using one dimensional Array

ALGORITHM:

1. Start
2. Declare an one dimensional array variable
3. Using Switch case statement select one appropriate operation
a. PUSH:
i. Read an element
ii. Store it at the top of the stack
iii. Increment the TOS
b. POP
i. Read the element from the top of the stack
ii. Display it
iii. Decrement the TOS
c. PEEK
i. Read the element from the top of the stack
ii. Display it
4. Stop

PROGRAM: /*Stack Using Arrays*/

#include<stdio.h>
#include<conio.h>
#define SIZE 4
int a[SIZE],top=0,ch=1,i,n;
void display();
void create();
void push();
void pop();
void peek();
void main()
{
clrscr();
printf("\n\t\tStack Using Arrays");
printf("\n\t\t------------------");
printf("\n\t\t 1.Create");
printf("\n\t\t 2.Push");
printf("\n\t\t 3.Pop");
printf("\n\t\t 4.Peek");
printf("\n\t\t 5.Exit\n");
do
{
printf("\t\tEnter Your Choice :");
scanf("%d",&ch);
switch(ch)
{

case 1: create();break;
case 2: push();break;
case 3: pop();break;
case 4: peek();break;
default: printf("\t\tExit");
break;
}
}while(ch!=5);
getch();
}
void create()
{
if(top==0)
{
printf("\t\tNumber of Element:");
scanf("%d",&n);
if(n>SIZE)
printf("\t\tSize of Stack is Large\n");
else
{
printf("\t\tPushing Element :");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
top=n;
display();
}
}
else
{
printf("\tStack Already Exists");
}
}
void push()
{
if(top==SIZE)
printf("\t\tStack Overflow\n");
else
{
printf("\t\tPushing Element :");
scanf("%d",&a[++top]);
display();
}
}
void pop()
{
if(top==0)
printf("\t\tStack Underflow\n");
else

{
printf("\t\tPop Element :%d\n",a[top--]);
display();
}
}
void display()
{
if(top==0)
printf("\t\tStack is Empty");
else
{
printf("\t\tStack Contains :");
for(i=top;i>=1;i--)
printf("%d ",a[i]);
}
printf("\n");
}
void peek()
{
if(top==0)
printf("\t\tStack Empty\n");
else
printf("\t\tTop Element is %d\n",a[top]);
}

OUTPUT:

IMPLEMENTATION OF STACK USING ARRAYS

Choose the option

1. Push
2. Pop
3. Peek
4. Display
5. Exit

Enter your option: 1


Enter the element to be pushed into the stack: 12

Choose the option

1. Push
2. Pop
3. Peek
4. Display
5. Exit

Enter your option: 1


Enter the element to be pushed into the stack: 15

Choose the option

1. Push
2. Pop
3. Peek
4. Display
5. Exit

Enter your option: 1


Enter the element to be pushed into the stack: 34

Choose the option

1. Push
2. Pop
3. Peek
4. Display
5. Exit

Enter your option: 4


The elements in the stack are: 12
15
34
Choose the option

1. Push
2. Pop
3. Peek
4. Display
5. Exit

Enter your option: 2

The Popped value is: 34

Choose the option

1. Push
2. Pop
3. Peek
4. Display
5. Exit

Enter your option: 4


The elements in the stack are: 12
15

RESULT: Thus a C program to implement Stack using Array was executed and the output was
obtained.
Ex. No: 5b) IMPLEMENTATION OF QUEUE USING ARRAY
Date:

AIM: To write a program to create a Queue and manipulate it using one dimensional array

ALGORITHM:

1. Start
2. Read ch and n value
3. check (ch!=4) and if (rear =n) then read value
4. Assign value to q(rear) and increment the rear, else Display as queue if full
5. if (front=rear) then print front value of queue and increment front
Else Display as queue is empty
6. if (rear=0) then assign front to I and write q[i].
Else Display as queue is empty
7. Go to step 3
8. stop

PROGRAM : /* program to create a Queue and manipulate it using one dimensional array*/

#include<stdio.h>
#include<conio.h>
void main()
{
int q[50],i,j,n,op,front,rear,no;
clrscr();
printf("Enter the size of the queue:");
scanf("%d",&n);
printf("QUEUE OPERATIONS:\n1.Insert\n2.Delete\n3.Display\n4.Exit\n");
printf("Enter the operation to be performed:");
scanf("%d",&op);
front=0;rear=-1;
while(op!=4){
switch(op)
{
case 1:{
if(rear==n-1)
printf("\nQueue is full!\n");
else
{ printf("Enter the element to be inserted:");
scanf("%d",&no);
q[++rear]=no;
printf("\n%d is inserted!",no);
}
break; }
case 2: {
if(front==0 && rear==-1)
printf("\nQueue is empty!");
else
{ printf("\n%d is deleted!",q[front]);
q[front]=0;
for(j=front;j<rear;j++)
q[j]=q[j+1];
rear=rear-1;
}
break; }
case 3: {
printf("\nQueue is:\n");
for(i=front;i<=rear;i++)
printf("%d\t",q[i]);
break; }
}
printf("\nEnter the operation to be performed:");
scanf("%d",&op);
}
getch(); }

OUTPUT:

Enter the size of the queue:3


QUEUE OPERATIONS:
1.Insert
2.Delete
3.Display
4.Exit
Enter the operation to be performed:1
Enter the element to be inserted:12

12 is inserted!
Enter the operation to be performed:1
Enter the element to be inserted:32

32 is inserted!
Enter the operation to be performed:3

Queue is:
12 32
Enter the operation to be performed:2

12 is deleted!
Enter the operation to be performed:3

Queue is:
32
Enter the operation to be performed:2

32 is deleted!
Enter the operation to be performed:2

Queue is empty!
Enter the operation to be performed:3

Queue is:

Enter the operation to be performed: 4


RESULT: Thus a C program to implement Queue using Array was executed and the output was
obtained.

Ex. No : 6a)
STACK USING LINKED LIST
Date :

AIM : To write a program to create Stack using Linked list

ALGORITHM :

1. Start
2. Read the value of ch
3. Allocate the malloc size to a variable
4. Get the item and store in data then link to Null value
5. Link the temp to top. Then check the top is Null then display as “ Stack is Empty”
6. If not as Null then print the top value
7. Print data as temp becomes Null
8. Stop

PROGRAM: /* program to create Stack using Linked*/

#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node* link;
}*head,*top,*curr;
void push(int data)
{
curr=(struct node*)malloc(sizeof(struct node));
curr->data=data;
curr->link=NULL;
if(top==NULL)
{
head=curr;
top=curr;
}
else
{
top->link=curr;
top=curr;
}
}
int pop()
{
int d=0;
d=top->data;
curr=head;
if(curr->link==NULL)
{
head=NULL;
top=NULL;
}
else
{

while(curr->link->link!=NULL)
{
curr=curr->link;
}
curr->link=NULL;
top=curr;
}
return d;
}
int peep()
{
return top->data;
}
void main()
{
int op,data;
clrscr();
do
{
printf("\nSTACK OPERATIONS:\n1.Push\n2.Pop\n3.Peep\n4.Exit\n");
printf("Enter the operation to be performed:");
scanf("%d",&op);
switch(op)
{
case 1:
{
printf("Enter the elemen to b pushed:");
scanf("%d",&data);
push(data);
break;
}
1 case 2:
{
printf("Popped element: %d",pop());
break;
}
case 3:
{
printf("Peeped element: %d",peep());
break;
}
case 4:
break;
default:
{
printf("\nEnter a proper option!\n");
}
}
}while(op!=4);
getch();
}
OUTPUT:

STACK OPERATIONS:
1.Push
2.Pop
3.Peep
4.Exit
Enter the operation to be performed:1
Enter the elemen to b pushed:12
STACK OPERATIONS:
1.Push
2.Pop
3.Peep
4.Exit
Enter the operation to be performed:1
Enter the elemen to b pushed:70

STACK OPERATIONS:
1.Push
2.Pop
3.Peep
4.Exit
Enter the operation to be performed:3
Peeped element: 70
STACK OPERATIONS:
1.Push
2.Pop
3.Peep
4.Exit
Enter the operation to be performed:2
Popped element: 70

STACK OPERATIONS:
1.Push
2.Pop
3.Peep
4.Exit
Enter the operation to be performed:3
Peeped element: 12

STACK OPERATIONS:
1.Push
2.Pop
3.Peep
4.Exit
Enter the operation to be performed:4

RESULT: Thus the program to implement stack using linked list has been successfully executed.
Ex. No : 6b)
QUEUE USING LINKED LIST
Date :

AIM: To write a program to create a Queue using Linked list

ALGORITHM:

1. Start
2. Read the value of ch
3. Get the variable temp and set malloc for size
4. Get item and store in data and link as Null
5. Get link of rear to temp. If front as Null and print Queue as Empty
6. Else print front element
7. print the data until the temp get Null
8. Stop

PROGRAM: /* program to create a Queue using Linked list*/

#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node* link;
}*head,*rear,*front,*curr;
void insert(int data)
{
curr=(struct node*)malloc(sizeof(struct node));
curr->data=data;
curr->link=NULL;
if(rear==NULL)
{
rear=curr;
front=curr;
}
else
{
rear->link=curr;
rear=curr;
}
}
int delete()
{
int d=0;
d=front->data;
curr=front;
front=front->link;
free(curr);
return d;
}
void display()
{
curr=front;

if(front==NULL)
printf("\nQueue empty!\n");
else if(front==rear)
printf("\nQueue is:%d",curr->data);
else
{
printf("\nQueue is:\n");
while(curr->link!=NULL)
{
printf("%d\t",curr->data);
curr=curr->link;
}
printf("%d\n",curr->data);
}
}
void main()
{
int op,data;
clrscr();
do
{
printf("\nQUEUE OPERATIONS:\n1.Insert\n2.Delete\n3.Exit\n");
printf("Enter the operation to be performed:");
scanf("%d",&op);
switch(op)
{
case 1:
{
printf("Enter the element to be inserted:");
scanf("%d",&data);
insert(data);
break;
}
case 2:
{
data=delete();
if(data)
printf("Deleted element: %d",data);
break;
}
case 3:
break;
default:
printf("\nEnter a proper option!\n");
}
display();
}while(op!=3);
getch();
}
OUTPUT:

QUEUE OPERATIONS:
1.Insert
2.Delete
3.Exit
Enter the operation to be performed:1
Enter the element to be inserted:34

Queue is:34
QUEUE OPERATIONS:
1.Insert
2.Delete
3.Exit
Enter the operation to be performed:1
Enter the element to be inserted:78

Queue is:
34 78

QUEUE OPERATIONS:
1.Insert
2.Delete
3.Exit
Enter the operation to be performed:1
Enter the element to be inserted:56

Queue is:
34 78 56

QUEUE OPERATIONS:
1.Insert
2.Delete
3.Exit
Enter the operation to be performed:2
Deleted element: 34
Queue is:
78 56

QUEUE OPERATIONS:
1.Insert
2.Delete
3.Exit
Enter the operation to be performed:3

RESULT: Thus the program to implement queue using linked list has been successfully executed.
Ex.NO.: 7a) APPLICATION OF STACK
Date: Convert Infix to Postfix Expression

AIM: To write a ‘C’ program to implement stack and use it to convert infix to postfix expression.

ALGORITHM:

1. Start the program


2. Scan the Infix string from left to right.
3. Initialise an empty stack.
4. If the scannned character is an operand, add it to the Postfix string. If the scanned

character is an operator and if the stack is empty Push the character to stack.

5. If the scanned character is an Operand and the stack is not empty, compare the precedence of
the character with the element on top of the stack (topStack). If topStack has higher
precedence over the scanned character Pop the stack else Push the scanned character to stack.
Repeat this step as long as stack is not empty and topStack has precedence over the character.

a. Repeat this step till all the characters are scanned.

6. (After all characters are scanned, we have to add any character that the stack may have to the
Postfix string.) If stack is not empty add topStack to Postfix string and Pop the stack. Repeat
this step as long as stack is not empty.
7. Return the Postfix string.
8. Terminate the program.

PROGRAM: // proram to implement stack and use it to convert infix to postfix expression.

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
char stack[100];
int top=0;
char exp[100];
struct table
{
char s[2];
int isp;
int icp;
}pr[7];
int isp(char c)
{
int i;

for(i=0;i<=6;i++)
if(pr[i].s[0]==c)
return(pr[i].isp);
return 0;
}
int icp(char c)
{
int i;
for(i=0;i<=6;i++)
if(pr[i].s[0]==c)
return(pr[i].icp);
return 0;
}
void main()
{
int i;
clrscr();
strcpy(pr[0].s,"^");
pr[0].isp=3;
pr[0].icp=4;
strcpy(pr[1].s,"*");
pr[1].isp=2;
pr[1].icp=2;
strcpy(pr[2].s,"/");
pr[2].isp=2;
pr[2].icp=2;
strcpy(pr[3].s,"+");
pr[3].isp=1;
pr[3].icp=1;
strcpy(pr[4].s,"-");
pr[4].isp=1;
pr[4].icp=1;
strcpy(pr[5].s,"(");
pr[5].isp=0;
pr[5].icp=4;
strcpy(pr[6].s,"=");
pr[6].isp=-1;
pr[6].icp=0;
clrscr();
stack[top]='=';
printf("enter the infix expression");
gets(exp);
i=0;
printf("the postfix expression is ")
while(i<strlen(exp))
{
if(isalpha(exp[i])==0)
{

if(exp[i]==')')
{
while(stack[top]!='(')
{
printf("%c",stack[top]);
top--;
}

top--;
}
else
{
while(isp(stack[top])>=icp(exp[i]))
{
printf("%c",stack[top]);
top--;
}
top++;
stack[top]=exp[i];
}
}
else
printf("%c",exp[i]);
i++;
}
while(top>0)
{
printf("%c",stack[top]);
top--;
}
getch();
}

OUTPUT:-
enter the infix expression a*(s+d/f)+c
the postfix expression is asdf/+*c+

RESULT:-
The given program was implemented, executed, tested and verified successfully.
Ex.NO.: 7b) APPLICATION OF QUEUE
Breadth First Search
Date:

AIM: To write a program to traverse the tree using breadth first search.

ALGORITHM:

1. Start
2. Read the size value in choice=1 and get the vertex value
3. Set for loop of condition i=1 and i<n
4. Read the number of edges
5. Set for loop of condition j<= no. of edges and j=1
6. Read the edge position
7. if Ch=2 then check a[i][j]==1
then check v[j]=0
printf v[j]
8. If ch==3 for display set for loop i<=n and print vt[i]
9. Set for loop j<=n and then print the a[i][j]
10. Stop

PROGRAM :

#include<stdio.h>
void insert(int c);
int del();
int front=-1,rear=-1;
int q[30],ans[10],k=0;
void main()
{
int i,j,n,no,a[10][10];
clrscr();
printf("\n Enter the number of Nodes: ");
scanf("%d",&n);
printf("\n Enter the adjacency matrix of the graph:\n ");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
printf("\n Adjacency is: \n ");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("\t %d",a[i][j]);
printf("\n");
}
insert(0);
printf("\bBreadth First Search of the nodes is:\n");
while(rear!=front)
{
i=del();
printf("\t:%d",i+1);
for(j=0;j<n;j++)
{
if (a[i][j]==1)
insert(j);}
}
getch();
}

int del()
{
return q[++front];
}
void insert(int c)
{
int i,count=0;
for(i=0;i<k;i++)

{
if(ans[i]==c)
{
count=1;
break;
}
}
if(count==0)
{
q[++rear]=c;
ans[k++]=c;
}

Expected Output

Enter the number of Nodes: 4

Enter the adjacency matrix of the graph:


0 1 1 0
1 0 1 0
1 1 0 1
1 0 1 0

Adjacency is:
0 1 1 0
1 0 1 0
1 1 0 1
1 0 1 0
Breadth First Search of the nodes is:
:1 :2 :3 :4

RESULT: Thus the program for quick sort has been successfully executed
Ex.No.:8 IMPLEMENTATION OF TREE AND TREE TRAVERSALS

Date:

AIM:-
To write a ‘C’ program to implement an expression tree. Produce its pre-order, in-
order, and post-order traversals.

ALGORITHM:-

Step 1: Start the process.

Step 2: Initialize and declare variables.

Step 3: Enter the choice. Inorder / Preorder / Postorder.

Step 4: If choice is Inorder then


o Traverse the left subtree in inorder.
o Process the root node.
o Traverse the right subtree in inorder.
Step 5: If choice is Preorder then
o Process the root node.
o Traverse the left subtree in preorder.
o Traverse the right subtree in preorder.
Step 6: If choice is postorder then
o Traverse the left subtree in postorder.
o Traverse the right subtree in postorder.
o Process the root node.
Step7: Print the Inorder / Preorder / Postorder traversal.

Step 8: Stop the process.


PROGRAM: // program to implement an expression tree. Produce its pre-order, in-order, and
post-order traversals.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct treenode

{
int data;
struct treenode *left;
struct treenode *right;
}tnode;
tnode *insertion(int,tnode*);
void preorder(tnode *);
void inorder(tnode *);
void postorder(tnode *);

void main()
{
tnode *T=NULL;
int ch1,n;
char ch2;
do
{
clrscr();
printf("\n\t\t****Operation With Tree****");
printf("\n\t1.Insertion");
printf("\n\t2.Inorder Traversal");
printf("\n\t3.Preorder Traversal");
printf("\n\t4.Postorder Traversal");
printf("\n\tEnter Your Choice :");
scanf("%d",&ch1);
switch(ch1)
{
case 1:
printf("\n\nenter the element to be inserted :");
scanf("%d",&n);
T=insertion(n,T);
break;
case 2:
inorder(T);
break;
case 3:
preorder(T);
break;
case 4:
postorder(T);
break;
default:
printf("\n\nInvalid Option");
break;
}
printf("\n\nDo you want to continue y/n : ");
scanf("%s",&ch2);
}while(ch2=='y');
getch();
}
tnode *insertion(int x,tnode *T)
{
if(T==NULL)
{
T=(tnode *)malloc(sizeof(tnode));
if(T==NULL)
printf("\nout of space");
else
{
T->data=x;
T->left=T->right=NULL;
}
}
else

{
if(x<(T->data))
T->left=insertion(x,T->left);
else
{
if(x>T->data)
T->right=insertion(x,T->right);
}
}
return T;
}
void preorder(tnode *T)
{
if(T!=NULL)
{
printf("\t%d",T->data);
preorder(T->left);
preorder(T->right);
}
}

void postorder(tnode *T)


{
if(T!=NULL)
{
postorder(T->left);
postorder(T->right);
printf("\t%d",T->data);
}
}
void inorder(tnode *T)
{
if(T!=NULL)
{
inorder(T->left);
printf("\t%d",T->data);
inorder(T->right);
}
}

RESULT:-
The given program was implemented, executed, tested and verified successfully

Ex.No. 09 IMPLEMENT BINARY SEARCH TREE

Date:

AIM: To write a ‘C’ program to implement binary search tree.

ALGORITHM:-

Step 1: Start the process.

Step 2: Initialize and declare variables.

Step 3: Construct the Tree

Step 4: Data values are given which we call a key and a binary search tree

Step 5: To search for the key in the given binary search tree, start with the root node and
Compare the key with the data value of the root node. If they match, return the
root pointer.

Step 6: If the key is less than the data value of the root node, repeat the process by using
the left subtree.

Step 7: Otherwise, repeat the same process with the right subtree until either a match is
found or the subtree under consideration becomes an empty tree.

Step 8: Terminate

PROGRAM // program to implement binary search tree.

#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<alloc.h>

struct tree
{
int data;
struct tree *lchild;
struct tree *rchild;
}*t,*temp;

int element;
void inorder(struct tree *);
void preorder(struct tree *);
void postorder(struct tree *);
struct tree * create(struct tree *, int);
struct tree * find(struct tree *, int);
struct tree * insert(struct tree *, int);
struct tree * del(struct tree *, int);
struct tree * findmin(struct tree *);
struct tree * findmax(struct tree *);
void main()
{

int ch;
do
{
printf("\n\t\t\tBINARY SEARCH TREE");
printf("\n\t\t\t****** ****** ****");
printf("\nMain Menu\n");
printf("\n1.Create\n2.Insert\n3.Delete\n4.Find\n5.FindMin\n6.FindMax");
printf("\n7.Inorder\n8.Preorder\n9.Postorder\n10.Exit\n");
printf("\nEnter ur choice :");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter the data:");
scanf("%d",&element);
t=create(t,element);
inorder(t);
break;
case 2:
printf("\nEnter the data:");
scanf("%d",&element);
t=insert(t,element);
inorder(t);
break;
case 3:
printf("\nEnter the data:");
scanf("%d",&element);
t=del(t,element);
inorder(t);
break;
case 4:
printf("\nEnter the data:");
scanf("%d",&element);
temp=find(t,element);
if(temp->data==element)
printf("\nElement %d is at %d",element,temp);
else
printf("\nElement is not found");
break;
case 5:
temp=findmin(t);
printf("\nMax element=%d",temp->data);
break;
case 6:
temp=findmax(t);
printf("\nMax element=%d",temp->data);
break;
case 7:
inorder(t);
break;
case 8:
preorder(t);
break;
case 9:
postorder(t);
break;

case 10:
exit(0);
}
}while(ch<=10);
}

struct tree * create(struct tree *t, int element)


{
t=(struct tree *)malloc(sizeof(struct tree));
t->data=element;
t->lchild=NULL;
t->rchild=NULL;
return t;
}

struct tree * find(struct tree *t, int element)


{
if(t==NULL)
return NULL;
if(element<t->data)
return(find(t->lchild,element));
else
if(element>t->data)
return(find(t->rchild,element));
else
return t;
}

struct tree *findmin(struct tree *t)


{
if(t==NULL)
return NULL;
else
if(t->lchild==NULL)
return t;
else
return(findmin(t->lchild));
}

struct tree *findmax(struct tree *t)


{
if(t!=NULL)
{
while(t->rchild!=NULL)
t=t->rchild;
}
return t;
}

struct tree *insert(struct tree *t,int element)


{
if(t==NULL)
{
t=(struct tree *)malloc(sizeof(struct tree));

t->data=element;
t->lchild=NULL;
t->rchild=NULL;
return t;
}
else
{
if(element<t->data)
{
t->lchild=insert(t->lchild,element);
}
else
if(element>t->data)
{
t->rchild=insert(t->rchild,element);
}
else
if(element==t->data)
{
printf("element already present\n");
}
return t;
}
}

struct tree * del(struct tree *t, int element)


{
if(t==NULL)
printf("element not found\n");
else
if(element<t->data)
t->lchild=del(t->lchild,element);
else
if(element>t->data)
t->rchild=del(t->rchild,element);
else
if(t->lchild&&t->rchild)
{
temp=findmin(t->rchild);
t->data=temp->data;
t->rchild=del(t->rchild,t->data);
}
else
{
temp=t;
if(t->lchild==NULL)
t=t->rchild;
else
if(t->rchild==NULL)
t=t->lchild;
free(temp);
}
return t;
}

void inorder(struct tree *t)


{
if(t==NULL)
return;
else
{
inorder(t->lchild);
printf("\t%d",t->data);
inorder(t->rchild);
}
}

void preorder(struct tree *t)


{
if(t==NULL)
return;
else
{
printf("\t%d",t->data);
preorder(t->lchild);
preorder(t->rchild);
}
}

void postorder(struct tree *t)


{
if(t==NULL)
return;
else
{
postorder(t->lchild);
postorder(t->rchild);
printf("\t%d",t->data);
}
}

OUTPUT:

BINARY SEARCH TREE


****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :1

Enter the data:10


10
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :2

Enter the data:20


10 20
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :2

Enter the data:30


10 20 30
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :2

Enter the data:25


10 20 25 30
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :4

Enter the data:25

Element 25 is at 2216
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :5

Max element=10
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :6

Max element=30

BINARY SEARCH TREE


****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :7
10 20 25 30
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :8
10 20 30 25
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :9
25 30 20 10
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :3

Enter the data:10


20 25 30
BINARY SEARCH TREE
****** ****** ****
Main Menu

1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit

Enter ur choice :10

RESULT:-
The given program was implemented, executed, tested and verified successfully.
Ex.No. 10a) LINEAR SEARCH

Date:

AIM: To write a program to find the number using Linear search.

ALGORITHM:

1. Start the program


2. Enter the number of elements in an array.
3. Get the set of number and the number to be searched.
4. Compare the elements in an array
5. Print the result.
6. Stop the program

PROGRAM:

#include <stdio.h>
int main()
{
int array[100], search, c, n;
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter a number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);
return 0;
}

OUTPUT:

RESULT: The given program was implemented, executed, tested and verified successfully
Ex.No. 10b) BINARY SEARCH

Date:

AIM: To write a program to find the number using Binarysearch.

ALGORITHM:

1. Start the program


2. Enter the number of elements in an array.
3. Get the set of number and the number to be searched.
4. Compare the elements in an array
5. Print the result.
6. Stop the program

PROGRAM:
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d",&array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0;
` last = n - 1;
middle = (first+last)/2;
while (first <= last)
{
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search)
{
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);
return 0;
}
OUTPUT:

RESULT: The given program was implemented, executed, tested and verified successfully.
Ex.No. 11a) INSERTION SORT

Date:

AIM: To write a program to sort the given list of elements using Insertion Sort.

ALGORITHM:

1. Start the program.


2. Enter the number of element in an array.
3. Read the n numbers from the keyboard.
4. Sort the elements
5. Print the sorted list.
6. Stop the program
PROGRAM: /* Insertion sort ascending order */
#include <stdio.h>
int main()
{
int n, array[1000], c, d, t;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
{
scanf("%d", &array[c]);
}
for (c = 1 ; c <= n - 1; c++)
{
d = c;
while ( d > 0 && array[d-1] > array[d])
{
t = array[d];
array[d] = array[d-1];
array[d-1] = t;
d--;
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c <= n - 1; c++)
printf("%d\n", array[c]);
return 0;
}

OUTPUT:

RESULT: The given program was implemented, executed, tested and verified successfully.
Ex.No. 11b) BUBBLE SORT

Date:

AIM: To write a program to sort the given list of elements using BUBBLE Sort.

ALGORITHM:

1. Start the program.


2. Enter the number of element in an array.
3. Read the n numbers from the keyboard.
4. Sort the elements
5. Print the sorted list.
6.Stop the program
PROGRAM: /* Bubble sort code */
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < n - 1; c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");

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


printf("%d\n", array[c]);
return 0;
}

OUTPUT:

RESULT: The given program was implemented, executed, tested and verified successfully.
Ex.No. 11c) QUICK SORT

Date:

AIM: To write a program to sort the given list of elements using quick Sort.

ALGORITHM:

1. Read the array elements


2. Set the first element in that array as pivot element.
3. Reorder the list so that all elements which are less than the pivot come before the pivot and so
that all elements greater than the pivot come after it.
4. After this partitioning, the pivot is in its final position. This is called the partition operation.
5. Repeat the steps from 2 to sort the sub-list of lesser elements and the sub-list of greater
elements.

PROGRAM : /*QUIC SORT*/


#include<stdio.h>
#include<conio.h>
#include<math.h>
int i,j,n,pivot,a[20];
void quick(int a[],int left, int right);
void swap(int a[],int i, int j);
void main()
{
int a[20],n,i;
clrscr();
printf("\n\tQUICK SORT");
printf("\nEnter the number of elements:");
scanf(" %d",&n);
printf("Enter the elements:");
for(i=1;i<=n;i++)
scanf(" %d",&a[i]);
quick(a,1,n);
printf("\n The sorted elements in the array are:");
for(i=1;i<=n;i++)
printf(" %d",a[i]);
getch();
}

void quick(int a[],int first,int last)


{
if(first<last)
{
pivot=a[first];
i=first;
j=last;
while(i<j)
{
while(a[i]<=pivot&&i<last)
i++;
while(a[j]>=pivot&&j>first)
j--;
if(i<j)
swap(a,i,j);
}
swap(a,first,j);
quick(a,first,j-1);
ick(a,j+1,last);
}
}
void swap(int a[],int i,int j)
{
int temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}

OUTPUT:

QUICK SORT
Enter the number of elements:5
Enter the elements:7
9
4
3
1

The sorted elements in the array are: 1 3 4 7 9

RESULT: Thus the program for quick sort has been successfully executed.
Ex.No. 11d) MERGE SORT

Date:

AIM: To write a program to sort the given list of elements using MERGE Sort.

ALGORITHM:

1. Start the program.


2. Enter the number of element in an array.
3. Read the n numbers from the keyboard.
4. Sort the elements
5. Print the sorted list.
6.Stop the program
PROGRAM: /*MERGE sort code */

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

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 program for quick sort has been successfully executed.

Ex.No. 12a) HASHING TECHNIQUES

Date:

AIM: To Implement the hashing techniques

ALGORITHM:-

(i) Start the program


(ii) Get the array size.
(iii) Get the elements of the array.
(iv)Get the key value of the element to be searched.
(v) Find the position of the element by taking the remainder of the division of the array size
by the key.
(vi)Print the element in that position.
(vii) Terminate the program.

PROGRAM: // Implement the hashing techniques

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a[125],key,size,i,h;
clrscr();
printf("\n Enter the array size:");
scanf("%d",&size);
printf("\n Enter the array element:");
for(i=0;i<size;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the key value");
scanf("%d",&key);
h=key%size;
while(h!=i)
i++;
printf("The element is %d",a[i]);
getch();
}
OUTPUT:
Enter the array size:4

Enter the array element:23


90
24
12
Enter the key value0
The element is 23

RESULT: Thus the implementation of hashing technique has been successfully executed.
Ex.No. 12b) Implement Hash Tables with Linear Probing
Date:

AIM: To write C Program to Implement Hash Tables with Linear Probing.

ALGORITHM:

1. Create a structure, item having a key and value representing data to be inserted in hash table.
2. Create another structure, hash table_item with variable data (key and value) and flag as a status variable which
informs about the status of array index.
flag = 1 : presence of some data at the array index.
flag = 0 : data not present in array index even once
flag = 2 : data had been removed from array index at least once
3. Now create an array of structure (hashtable_item) of some certain size (10, in this case). This array will be our
hash table.
4. A menu is displayed on the screen.
5. User must choose one option from four choices given in the menu.
6. 1st choice: Inserting item into hash table
(a) Take a key and a value as input.
(b) Calculate index as per the given key (using hashcode() function).
(c) Access the element at this calculated index in array.
(d) If there is no element at that particular array index, add straight way.
(e) If an element is present, check whether the given key matches the element’s key. If yes, then update it’s value
and return. Otherwise probe through subsequent elements (looping back if necessary), to find free space. While
probing
* if given key matches the element’s key, update its value and return.
* if a free space is found, add the data at that position.
Probing will stop until we reach the same element from where we began probing. Until then, if no free space is
found, then add will fail.
7. 2nd choice: Removing a key from hash table
(a) Take a key as input which needs to be removed.
(b) Calculate index as per the given key (using hashcode() function).
(c) Access the element at the calculated array index.
(d) If an element is present, check whether the given key matches the element’s key. If yes, then delete the key and
return decrementing the size. Otherwise probe through subsequent elements (looping back if necessary), to find free
space with flag = 0. While probing
* if given key matches the element’s key, delete and return.
* if a free space is found (with flag = 2), continue to probe.
(e) If no free space (flag = 0) is found even after probing through all element it means, key does not exist in the hash
table.
8. 3rd choice: Size of hash table

(a) Each time we add a new data item into the hash table, we increment it’s size by 1.
(b) Each time we remove a data item from the hash table, we decrement it’s size by 1.
(c) The size of the hash table can be determined either by size variable or size_of_hashtable() method.

9. 4th choice: Display hash table


(a) Function display() runs for displaying hash table contents.
(b) Here a for loop runs from 0 to array_size-1 with i as iterator.
(c) The code inside loop consists of taking i as index and accessing each element at that index of array.

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
struct item /* to store a data (consisting of key and value) in hash table array */
{
int key;
int value;
};
struct hashtable_item
{ /* each hash table item has a flag (status) and data (consisting of key and value) */
int flag;
/*
* flag = 0 : data does not exist
* flag = 1 : data exists
* flag = 2 : data existed at least once
*/
struct item *data;
};
struct hashtable_item *array;
int size = 0;
int max = 10;
void init_array() /* initializing hash table array */
{
int i;
for (i = 0; i < max; i++)
{
array[i].flag = 0;
array[i].data = NULL;
}
}
int hashcode(int key) /* to every key, it will generate a corresponding index */
{
return (key % max);
}
void insert(int key, int value) /* to insert an element in the hash table */
{

int index = hashcode(key);


int i = index; /* creating new item to insert in the hash table array */
struct item *new_item = (struct item*) malloc(sizeof(struct item));
new_item->key = key;
new_item->value = value;
while (array[i].flag == 1) /* probing through the array until we reach an empty space */
{
if (array[i].data->key == key)
{ /* case where already existing key matches the given key */
printf("\n Key already exists, hence updating its value \n");
array[i].data->value = value;
return;
}
i = (i + 1) % max;
if (i == index)
{
printf("\n Hash table is full, cannot insert any more item \n");
return;
}
}
array[i].flag = 1;
array[i].data = new_item;
size++;
printf("\n Key (%d) has been inserted \n", key);
} /* to remove an element from the hash table */
void remove_element(int key)
{
int index = hashcode(key);
int i = index;
/* probing through array until we reach an empty space where not even once an element
had been present */
while (array[i].flag != 0)
{
if (array[i].flag == 1 && array[i].data->key == key )
{ // case when data key matches the given key
array[i].flag = 2;
array[i].data = NULL;
size--;
printf("\n Key (%d) has been removed \n", key);
return;
}
i = (i + 1) % max;
if (i == index)
{
break;
}
}

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


}/* to display all the elements of hash table */
void display()
{
int i;
for (i = 0; i < max; i++)
{
struct item *current = (struct item*) array[i].data;
if (current == NULL)
{
printf("\n Array[%d] has no elements \n", i);
}
else
{
printf("\n Array[%d] has elements -: \n %d (key) and %d(value) ", i, current-
>key, current->value);
}
}
}
int size_of_hashtable()
{
return size;
}
void main()
{
int choice, key, value, n, c;
clrscr();
array = (struct hashtable_item*) malloc(max * sizeof(struct hashtable_item*));
init_array();
do {
printf("Implementation of Hash Table in C with Linear Probing \n\n");
printf("MENU-: \n1.Inserting item in the Hashtable"
"\n2.Removing item from the Hashtable"
"\n3.Check the size of Hashtable"
"\n4.Display Hashtable"
"\n\n Please enter your choice-:");
scanf("%d", &choice);
switch(choice)
{
case 1: printf("Inserting element in Hashtable\n");
printf("Enter key and value-:\t");
scanf("%d %d", &key, &value);
insert(key, value);
break;
case 2: printf("Deleting in Hashtable \n Enter the key to delete-:");
scanf("%d", &key);
remove_element(key);
break;

case 3: n = size_of_hashtable();
printf("Size of Hashtable is-:%d\n", n);
break;
case 4: display();
break;
default: printf("Wrong Input\n");
}
printf("\n Do you want to continue-:(press 1 for yes)\t");
scanf("%d", &c);
}while(c == 1);
getch();

OUTPUT:

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

Please enter your choice-: 3


Size of Hashtable is-: 0

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


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

Please enter your choice-: 1


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

Key (12) has been inserted

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


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

Please enter your choice-: 1


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

Key (122) has been inserted

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


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

Please enter your choice-: 3


Size of Hashtable is-: 2

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


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

Please enter your choice-: 4


Array[0] has no elements

Array[1] has no elements

Array[2] has elements-:


12 (key) and 10 (value)

Array[3] has elements-:


122(key) and 5(value)

Array[4] has no elements

Array[5] has no elements

Array[6] has no elements

Array[7] has no elements

Array[8] has no elements

Array[9] has no elements

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


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

Please enter your choice-: 2


Deleting in Hashtable
Enter the key to delete-: 122

Key (122) has been removed

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


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

Please enter your choice-: 2


Deleting in Hashtable
Enter the key to delete-: 56

This key does not exist

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

RESULT: Thus the C Program to Implement Hash Tables with Linear Probing has been completed successfully
Ex.No. 12c) Implement Hash Tables with Quadratic Probing.
Date:

AIM: To write C Program to Implement Hash Tables with Quadratic Probing.

ALGORITHM:

1.Create an array of structure (i.e a hash table).


2. Take a key and a value to be stored in hash table as input.
3. Corresponding to the key, an index will be generated i.e every key is stored in a particular array
index.
4. Using the generated index, access the data located in that array index.
5. In case of absence of data, create one and insert the data item (key and value) into it and increment
the size of hash table.
6. In case the data exists, probe through the subsequent elements (looping back if necessary) for free
space to insert new data item.
Note: This probing will continue until we reach the same element again (from where we began
probing)
Note: Here, unlike Linear Probing, probing will be done according to the following formula –
(currentPosition + h) % arraySize => Linear Probing
(currentPosition + (h * h)) % arraySize => Quadratic Probing

where h = 1, 2, 3, 4 and so on.


7. To display all the elements of hash table, element at each index is accessed (via for loop).
8. To remove a key from hash table, we will first calculate its index and delete it if key matches, else
probe through elements until we find key or an empty space where not a single data has been entered
(means data does not exist in the hash table).
9. Exit

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
/* to store a data (consisting of key and value) in hash table array */
struct item
{
int key;
int value;
};
/* each hash table item has a flag (status) and data (consisting of key and value) */
struct hashtable_item
{
int flag;
/*
* flag = 0 : data does not exist
* flag = 1 : data exists at given array location
* flag = 2 : data was present at least once
*/
struct item *data;
};
struct hashtable_item *array;
int size = 0;
int max = 10;
/* this function returns corresponding index of the given key */
int hashcode(int key)
{
return (key % max);
}
/* this function initializes the hash table array */
void init_array()
{
int i;
for (i = 0; i < max; i++)
{
array[i].flag = 0;
array[i].data = NULL;
}
}
/* this function inserts an element in the hash table */
void insert(int key, int value)
{
int index = hashcode(key);

int i = index;
int h = 1;
struct item *new_item = (struct item*) malloc(sizeof(struct item));
new_item->key = key;
new_item->value = value;
/* probing through the array until an empty space is found */
while (array[i].flag == 1)
{
if (array[i].data->key == key)
{
/* case when already present key matches the given key */
printf("\n This key is already present in hash table, hence updating it's
value \n");
array[i].data->value = value;
return;
}
i = (i + (h * h)) % max;
h++;
if (i == index)
{
printf("\n Hash table is full, cannot add more elements \n");
return;
}
}
array[i].flag = 1;
array[i].data = new_item;
printf("\n Key (%d) has been inserted\n", key);
size++;
}
/* to remove an element form the hash table array */
void remove_element(int key)
{
int index = hashcode(key);
int i = index;
int h = 1;
/* probing through the hash table until we reach at location where there had not been an
element even once */
while (array[i].flag != 0)
{
if (array[i].flag == 1 && array[i].data->key == key)
{
/* case where data exists at the location and its key matches to the given
key */
array[i].flag = 2;
array[i].data = NULL;
size--;
printf("\n Key (%d) has been removed \n", key);
return;
}
i = (i + (h * h)) % max;
h++;
if (i == index)
{
break;
}
}
printf("\n Key does not exist \n");
}
/* to display the contents of hash table */
void display()
{
int i;
for(i = 0; i < max; i++)
{
if (array[i].flag != 1)
{
printf("\n Array[%d] has no elements \n", i);
}
else
{
printf("\n Array[%d] has elements \n %d (key) and %d (value) \n", i,
array[i].data->key, array[i].data->value);
}
}
}
int size_of_hashtable()
{
return size;
}
void main()
{
int choice, key, value, n, c;
clrscr();
array = (struct hashtable_item*) malloc(max * sizeof(struct hashtable_item*));
init_array();
do {
printf("Implementation of Hash Table in C with Quadratic Probing.\n\n");
printf("MENU-: \n1.Inserting item in the Hash table"
"\n2.Removing item from the Hash table"
"\n3.Check the size of Hash table"
"\n4.Display Hash table"
"\n\n Please enter your choice-:");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Inserting element in Hash table \n");
printf("Enter key and value-:\t");
scanf("%d %d", &key, &value);
insert(key, value);
break;

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

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

Please enter your choice-: 3


Size of hash table is-: 0

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


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

Please enter your choice-: 1


Inserting element in Hash table
Enter key and value-: 12 10

Key (12) has been inserted

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


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

Please enter your choice-: 1


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

Key (122) has been inserted

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


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

Please enter your choice-: 1


Inserting element in hash table
Enter key and value-: 82 5

Key (82) has been inserted

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


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

Please enter your choice-: 3


Size of hash table is-: 3

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


Implementation of Hash Table in C with Quadratic Probing
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

Array[2] has elements-:


12 (key) and 10 (value)

Array[3] has elements-:


122(key) and 4(value)

Array[4] has no elements

Array[5] has no elements

Array[6] has no elements

Array[7] has no elements


82(key) and 5(value)
Array[8] has no elements

Array[9] has no elements

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


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

Please enter your choice-: 2


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

Key (122) has been removed

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


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

Please enter your choice-: 2


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

This key does not exist

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

RESULT: Thus the C Program to Implement Hash Tables with Quadratic Probing has been completed
successfully
Ex. No : 13
Depth First Search
Date :

Aim: To write a program to traverse the tree using Depth first search.

Algorithm:

1. Start
2. Read the value of n
3. Set for loop as i<n as i=0
4. Set for loop as j>n as j=0
5. Read adjacency of adj[i][j]
Read dfs(s)
6. Set for loop i<n and execute check whether (!vis[i]) then
Dfs(i)
7. Stop

Program Code
#include<stdio.h>
#include<conio.h>
#define max 50
int adj[max][max];
int vertex[max];
int visited[max];
void creategraph(int);
void dfs(int,int);
void depthfirst(int);
void main()
{
int ch,n,v;
clrscr();
do
{
printf("\n1.create graph"
"\n2.dfs"
"\n3.exit"
"\n Enter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1:{ printf("\n Enter no. of vertices to be created");
scanf("%d",&v);
creategraph(v);
break; }
case 2: depthfirst(v);
break;
case 3:printf("end of the program");
break;
}
}while(ch!=3);
getch();
}
void creategraph(int v)
{
int i,j,n,m,k;

for(i=0;i<v;i++)
{
printf("\n Enter the node value");
scanf("%d",&vertex[i]);
visited[i]=0;
}

for(j=0;j<v;j++)
adj[i][j]=0;
printf("Enter the adjacency vertices list");
printf("for each vertex of the graph");
for(i=0;i<v;i++)
{
printf("\n Enter the no.of adjancey vertices for the vertex %d",vertex[i]);
scanf("%d",&n);
for(j=0;j<n;j++)
{
printf("\n Enter adjacency vertex");
scanf("%d",&m);
for(k=0;k<v;k++)
{
if(vertex[k]==m)
adj[i]]k]=1;
}
}
}
printf("\n graph created with no. of vertices");
printf("the adjacency matrix of graph\n");
for(i=0;i<v;i++)
{
for(j=0;j<v;j++)
printf("%d\t",adj[i][j]);
printf("\n");
}
}
void depthfirst(int v)
{
int i;
for(i=0;i<v;i++)
visited[i]=0;
visited[0]=1;
printf("Depth first serach \n");
printf("%d",vertex[0]);
dfs(0,v);
}
void dfs(int ad,int v)
{
int j,k;
for(k=ad;k<v;k++)
for(j=0;j<v;j++)
if(adj[k][j]==1)
{
if(visited[j]==0)
{
visited[j]=1;
printf("%d",vertex[j]);
dfs(j,v);
}
}
}

Expected Output

1.create graph
2.dfs
3.exit
Enter your choice1

Enter no. of vertices to be created5

Enter the node value1


Enter the node value3
Enter the node value4
Enter the node value6
Enter the node value8

Enter the adjacency vertices list for each vertex of the graph
Enter the no.of
adjancey vertices
for the vertex 1

RESULT: Thus the C Program depth first search has been completed successfully

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy