0% found this document useful (0 votes)
41 views105 pages

CS3362 C&DS Manual Record-2

Cprog and DS lab manual

Uploaded by

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

CS3362 C&DS Manual Record-2

Cprog and DS lab manual

Uploaded by

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

SYLLABUS

CS3362 C PROGRAMMING AND DATA STRUCTURES

COURSE OBJECTIVES:
• To develop applications in C
• To implement linear and non-linear data structures
• To understand the different operations of search trees
• To get familiarized to sorting and searching algorithms
LIST OF EXPERIMENTS
1. Practice of C programming using statements, expressions, decision making and iterative
statements
2. Practice of C programming using Functions and Arrays
3. Implement C programs using Pointers and Structures
4. Implement C programs using Files
5. Development of real time C applications
6. Array implementation of List ADT
7. Array implementation of Stack and Queue ADTs
8. Linked list implementation of List, Stack and Queue ADTs
9. Applications of List, Stack and Queue ADTs
10. Implementation of Binary Trees and operations of Binary Trees
11. Implementation of Binary Search Trees
12. Implementation of searching techniques
13. Implementation of Sorting algorithms : Insertion Sort, Quick Sort, Merge Sort
14. Implementation of Hashing – any two collision techniques
15. Implementation of Open Addressing(Quadratic probing).
TOTAL: 45 PERIODS

COURSE OUTCOMES:
At the end of the course, the students will be able to:
CO1:Use different constructs of C and develop applications
CO2:Write functions to implement linear and non-linear data structure operations
CO3:Suggest and use the appropriate linear / non-linear data structure operations for a given
problem
CO4:Apply appropriate hash functions that result in a collision free scenario for data storage
and Retrieval
CO5:Implement Sorting and searching algorithms for a given application

1
INDEX

Ex no Date Name of the Experiments Pg.No Marks Sign

C Program to get the user details and


1a display it.
C Program to check biggest of three
1b numbers

C Program to check whether the entered


1c character is vowel or not
C Program to find whether the given year
1d is leap year or not.
C Program to check whether the given
1e number is Armstrong number or not

Find factorial of a given number


1f

To find average of 4 integers using array.


2a

To perform swapping using functions


2b
C Program display all prime numbers
2c between two intervals using functions

To reverse a sentence using recursion.


2d

2e Largest element of an array using function

Find the length of the given string


2f

2g Display array elements using 2D arrays


Find the frequency of a character in a
2h string.

Program to generate salary slip of


3a employees

3b Store student information in structure

4 C program using files

2
Real time application to perform a spam
5 filter in C
Program to implement list in array using C
6

7a Implement stack operations using array


Implement queue operations using array.
7b

8a Implementation of singly linked list


Implement stack operations using linked
8b list.

9 Polynomial manipulation using linked lis t


C program for Binary Tree and its
10 operation.
Binary search tree
11

12 Perform linear search

13a Insertion sort

13b Merge sort

13c Quick sort

14 Hash table with linear probing

15 Hash table Open addressing

3
Ex.No : 1(a)
IMPLEMENT A C PROGRAM TO GET THE USER DETAILS AND DISPLAY
IT.
Date :

AIM
To implement a C Program to get the user details and display it.

ALGORITHM

Step 1: Start
Step 2: Declare the variables for name, address, date, month, year, mobile number, age.
Step 3: Read values of name, address, date, month, year, mobile number, age from the user.
Step 4: Display name, address, date, month, year, mobile number, age.
Step 5: End

PROGRAM

#include<stdio.h>
#include<string.h>
int main() {
char name[20];
char address[80];
int date;
int month;
int year;
int mobile;
char gender[20];
int age;
printf("\n ENTER YOUR NAME:=");
fgets(name,20,stdin);
printf("\nENTER YOUR ADDRESS=");
fgets(address,80,stdin);
printf("\nENTER YOUR date/month/year=");
scanf("%d/%d/%d",&date,&month,&year);
printf("\n ENTER YOUR AGE=");
scanf("%d",&age);
printf("\n ENTER YOUR GENDER(MALE/FEMALE)=");
4
scanf("%s",gender);
printf("\nENTER YOUR MOBILE NUMBER=");
scanf("%d" ,&mobile);
printf("\n=====================");
printf("\n NAME: %s",name);
printf("\n ADDRESS:%s", address);
printf("\n DOB:%d:%d:%d", date , month, year); printf("\n AGE:%d", age);
printf("\n GENDER:%s", gender);
printf("\n MOBILE NUMBER:%d", mobile);
printf("\n=====================");
return 0;
}

OUTPUT

ENTER YOUR NAME:=karthikeyan

ENTER YOUR ADDRESS=west tambharam,chennai. ENTER YOUR


date/month/year=03/12/1992
ENTER YOUR AGE=28

ENTER YOUR GENDER(MALE/FEMALE)=MALE ENTER YOUR MOBILE


NUMBER=987654321
===================== NAME: karthikeyan ADDRESS:west
tambharam,chennai.
DOB:3:12:1992
AGE:28
GENDER:MALE
MOBILE NUMBER:987654321
========================

RESULT
Thus, the C Program to read and display the user details has been executed and the output

5
was verified.

Ex.No : 1(b)
BIGGEST OF THREE NUMBERS
Date :

AIM
To implement a C Program to check biggest of three numbers

ALGORITHM

Step 1:Start

Step 2:Read three numbers A,B & C Step 3:If A>B,then go to step 6

Step 4:If B>C,then print B & go to step 8

Step 5:print C is greatest & go to step 8

Step 6:If A>C,then print A is greatest & go to step 8

Step 7:Print C is greatest

Step 8:end

PROGRAM
#include<stdio.h>
void main()
{
int A,B,C;
printf("Enter 3 integer number \n");
scanf("%d",&A);
scanf("%d",&B);
scanf("%d",&C);
if(A>B)
{
if(A>C)
{
printf(" %d is the Greatest Number \n",A);
}
else
{
printf("%d is the greatest Number \n",C);
}
6
}
else
{
if(B>C)
{
printf("%d is the greatest Number \n",B );
}
else
{
printf("%d is the greatest Number \n", C);
}
}
}

OUTPUT

Enter three numbers: -4.5


3.9
5.6
5.60 is the largest number.

RESULT
7
Thus, the C Program to display the personal details has been executed and the output
was verified.

Ex.No: 1(c) PROGRAM TO CHECK WHETHER THE ENTERED


Date : CHARACTER IS VOWEL OR NOT (USE SWITCH CASE)

AIM
To implement a C Program to check whether the entered character is vowel or not.
ALGORITHM

Step 1: Start
Step 2: Declare and initialize the variables
Step 3: Get the input from the user and compare with each cases
Step 4: if match found, print vowel otherwise print consonant
Step 5: End

PROGRAM
#include<stdio.h>
int main()
{
char ch;
printf("Enter a character: ");
scanf("%c",&ch);
//condition to check character is alphabet or not if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z'))
{
switch(ch)
{
case 'A': case 'E': case 'I': case 'O': case 'U': case 'a': case 'e': case 'i': case 'o': case
'u':
printf("%c is a VOWEL.\n",ch);
break;
default:
printf("%c is a CONSONANT.\n",ch);
}
}
else
{
printf("%c is not an alphabet.\

8
n",ch);
}
return
0;
}
OUTPUT:

Enter a character
E
E is a vowel Enter a character X
X is a consonant
Enter a character
+
+ is not an alphabet

RESULT:
Thus, the C Program check whether the entered character is vowel or not (Use switch

9
case) has been executed and the output was verified.

Ex.No: 1(d)
PROGRAM TO FIND WHETHER THE GIVEN YEAR IS LEAP YEAR OR
NOT
Date :

AIM:
To write a C Program to find whether the given year is leap year or not.
ALGORITHM:
Step 1: Start
Step 2: Take integer variable year
Step 3: Check if year is divisible by 400 then DISPLAY "is a leap year"
Step 4: Check if year is not divisible by 100 AND divisible by 4 then DISPLAY "is a leap year"
Step 5: Otherwise, DISPLAY "is not a leap year"
Step 6: Stop

PROGRAM:

#include<stdio.h>
#include<conio.h>
void main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
if(((year%4==0) && ((year%400==0) || (year%100!==0))
{
printf("%d is a leap year", &year);
}
else
{
printf("%d is not a leap year", &year);
}
getch();
}
}

10
OUTPUT

Enter a year:
2000
2000 is a leap year

Enter a year:
1900
1900 is not a leap year

11
RESULT:
Thus, the C Program to find whether the given year is leap year or not has been
executed successfully and the output was verified.

Ex.No: 1(e)
PROGRAM TO CHECK WHETHER A GIVEN NUMBER IS ARMSTRONG
NUMBER OR NOT
Date :
AIM
To implement a C Program to check whether the given number is Armstrong number or
not

ALGORITHM:
Step 1: Start
Step 2: Declare Variable sum, temp, num
Step 3: Read num from User
Step 4: Initialize Variable sum=0 and temp=num
Step 5: Repeat Until num&gt;=0 5.1 sum=sum + cube of last digit i.e
[(num%10)*(num%10)*(num%10)] 5.2 num=num/10
Step 6: IF sum==temp Print "Armstrong Number" ELSE Print "Not Armstrong Number" Step
7: Stop

PROGRAM:
#include<stdio.h>
int main()
{
int num,copy_of_num,sum=0,rem;
printf("\nEnter a number:");
scanf("%d",&num);
while (num != 0)
{
rem = num % 10;

12
sum = sum +(rem*rem*rem);
num = num / 10;
}
if(copy_of_num == sum)
{
printf("\n%d is an Armstrong Number",copy_of_num);
}
else
{
printf("\n%d is not an Armstrong Number",copy_of_num);
}
return 0;
}

OUTPUT:

Enter a number: 370


370 is an Armstrong Number

13
RESULT:
Thus, the C Program to check whether a given number is Armstrong or not has been
executed and the output was verified.

Ex.No: 1(f)
PROGRAM TO FIND FACTORIAL OF A GIVEN NUMBER
Date :

AIM:
To find factorial of a given number

ALGORITHM:

Step 1. Start the program


Step 2. Get the number
Step 3. If the number < 0 print “Error for finding a factorial”
Step 4. Else Initialize variables factorial←1 i←1 Step
5. Read value of n
Step 6. Repeat the steps until i=n 6.1: factorial←factorial, i←i+1
Step 7. Display factorial
Step 8: Stop the program

PROGRAM:
#include<stdio.h>
int main()
{
int n, i;
long factorial = 1;
printf("Enter an integer: ");
scanf("%d",&n);
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else
14
{
for(i=1; i<=n; ++i)
{
factorial *= i; // factorial = factorial*i;
}
printf("Factorial of %d = %lu", n, factorial);
}
return 0;
}

OUTPUT:

Enter an integer: 10
Factorial of 10 = 3628800

15
RESULT

Thus, the C Program to find the factorial of a given number has been successfully
executed and verified.

Ex.No: 2(a)
PROGRAM TO FIND OUT THE AVERAGE OF 4 INTEGERS
Date :

AIM
To find average of 4 integers using array.

ALGORITHM
Step 1. Start
Step 2. Declare variables
Step 3. Read the 4 numbers
Step 4. Calculate avg=sum/n
Step 5. Display the output
Step 6. Stop

PROGRAM:

#include <stdio.h>
int main()
{
int avg = 0;
int sum =0;
int x=0;

/* Array- declaration – length 4*/


int num[4];

/* We are using a for loop to traverse through the array


16
* while storing the entered values in the array
*/
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}
for (x=0; x<4;x++)
{
sum = sum+num[x];
}

avg = sum/4;
printf(“Average of entered number is : %d \n”,avg);
return 0;
}

OUTPUT:

Enter the numbers

32

45

54

22

Average is 38.25

17
RESULT

Thus, the C Program to find the average of 4 numbers has been executed and verified

Ex.No: 2(b)
PROGRAM TO PERFORM SWAPPING USING FUNCTIONS
Date :

AIM:
To perform swapping using functions
ALGORITHM:
Step 1. Start the program
Step 2. Declare and get the two integer variables a and b.
Step 3. call the swap () function
In swap definition use the temporary variable and assign temp =a b=temp
Step 4. Print the a and b values
Step 5. Stop the program

PROGRAM:

#include<stdio.h>
void swap(int *,int *);
int main()
{
int n1,n2;
printf("\n\n Function : swap two numbers using function :\n");
printf("------------------------------------------------\n");
printf("Enter 1st number : ");
18
scanf("%d",&n1);
printf("Enter 2nd number : ");
scanf("%d",&n2);
printf("Before swapping: n1 = %d, n2 = %d ",n1,n2);
//pass the address of both variables to the function.
swap(&n1,&n2);
printf("\nAfter swapping: n1 = %d, n2 = %d \n\n",n1,n2);
return 0;
}

void swap(int *p,int *q)


{

int tmp;
tmp = *p; // tmp store the value of n1
*p=*q; // *p store the value of *q that is value of n2
*q=tmp; // *q store the value of tmp that is the value of n1
}

OUTPUT:

Function : swap two numbers using function :


------------------------------------------------
Enter 1st number : 23
Enter 2nd number : 45
Before swapping: n1 = 23, n2 = 45
After swapping: n1 = 45, n2 = 23

19
RESULT:
Thus, the C Program to swap two numbers using functions has been executed and
verified

Ex.No: 2(c)
PROGRAM TO DISPLAY ALL PRIME NUMBERS BETWEEN TWO
INTERVALS USING FUNCTIONS
Date :

AIM:
To display all prime numbers between two intervals using functions

ALGORITHM:
Step1: Start the Program
Step 2: Get the intervals
Step 3: Find and Display the prime numbers ie., the numbers that are divisible by 1 and itself
between the intervals
Step 4: Stop the Program

PROGRAM:
#include <stdio.h>
/* Function declarations */
int isPrime(int num);
void printPrimes(int lowerLimit, int upperLimit);
int main()
{
int lowerLimit, upperLimit;
20
printf("Enter the lower and upper limit to list primes: ");
scanf("%d%d", &lowerLimit, &upperLimit);
/* Call function to print all primes between the given range*/
printPrimes(lowerLimit, upperLimit);
return 0;
}
/* Print all prime numbers between lower limit and upper limit*/ void
printPrimes(int lowerLimit, int upperLimit)
{
printf("All prime number between %d to %d are: ", lowerLimit, upperLimit); while(lowerLimit
<= upperLimit)
{
/* Print if current number is prime*/
if(isPrime(lowerLimit))

{
printf(“%d”,lowerLimit);
} lowerLimit++;
}
}
/*Check whether a number is prime or not*/
/*Returns 1 if the number is prime otherwise 0*/ int
isPrime(int num)
{
int i;
for(i=2; i<=num/2; i++)
{
/*If the number is divisible by any number*/
/*other than 1 and self then it is not prime*/ if(num
% i == 0)
{ return
0;
}
}
return 1;
}

21
OUTPUT:
Enter the lower and upper limit to list primes:
1 100
All prime number between 1 100 are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
53, 59, 61, 67, 71, 73, 79, 83, 89, 97

RESULT:
Thus, the C Program to find the prime numbers between two intervals has been
executed and verified.

Ex.No: 2(d)
PROGRAM TO REVERSE A SENTENCE USING RECURSION
Date :
AIM:
To reverse a sentence using recursion.
ALGORITHM:
Step 1: Start
Step 2: Declare the function reverse
Step 3: Call the reverse function
Step 4: Get the sentence from the user and reverse it recursively Step
5: stop the execution.

PROGRAM:
#include <stdio.h>
void reverseSentence();
int main()
{
printf("Enter a sentence: ");
reverseSentence();
return 0;
}
void reverseSentence()
{
char c;

22
scanf("%c", &c);
if (c != '\n')
{
reverseSentence();
printf("%c", c);
}
}

OUTPUT:
Enter a sentence: margorp emosewa awesome

23
RESULT
Thus, the C Program to reverse a sentence has been executed and verified.

Ex.No: 2(e)
PROGRAM TO GET THE LARGEST ELEMENT OF AN ARRAY USING
FUNCTION
Date :

AIM:
To get the largest element of an array using function
ALGORITHM:
Step 1: Start the program
Step 2: Initialize the array elements
Step 3: Find the largest number of the array
Step 4: Display the largest number
Step 5: Stop the program

PROGRAM:
#include<stdio.h>
#define MAX 100

int findMaxElem(int []);


int n;

int main()
{
int arr1[MAX],mxelem,i;
printf("\n\n Function : get largest element of an array :\n");
24
printf("-------------------------------------------------\n");

printf(" Input the number of elements to be stored in the array :");


scanf("%d",&n);

printf(" Input %d elements in the array :\n",n);


for(i=0;i<n;i++)
{
printf(" element - %d : ",i);
scanf("%d",&arr1[i]);
}
mxelem=findMaxElem(arr1);

printf(" The largest element in the array is : %d\n\n",mxelem);


return 0;
}
int findMaxElem(int arr1[])
{
int i=1,mxelem;
mxelem=arr1[0];
while(i < n)
{
if(mxelem<arr1[i])
mxelem=arr1[i];
i++;
}
return mxelem;
}

OUTPUT:

Input the number of elements to be stored in the array :5


Input 5 elements in the array :
element - 0 : 2
element - 1 : 4
element - 2 : 6
element - 3 : 2
element - 4 : 1
The largest element in the array is : 6

25
RESULT:
Thus, the C Program to display the largest number in an array using function has been
executed and verified.

Ex.No: 2(f)
PROGRAM TO FIND THE LENGTH OF STRING
Date :

AIM:
To find the length of the given string
ALGORITHM:
Step 1 : Start the program
Step 2: Get the string
Step 3: Find the length of the string
Step 4 : Display the length of the string
Step 5 : Stop the program

PROGRAM:
i) Using Library Function

#include <stdio.h>

#include <string.h>

int main()

26
char a[100];

int length;

printf("\n Enter a string to calculate its length=");

gets(a);

length = strlen(a);

printf("\nLength of the string = %d\n", length);

return 0;

ii) Without Using Library Function


#include <stdio.h>
int main()
{
char str[100];
int i,length=0;

printf("Enter a string: \n");


scanf("%s",str);
for(i=0; str[i]!='\0'; i++)
{
length++;
}

printf("\nLength of input string: %d",length);


return 0;
}

27
OUTPUT:
Enter a string to calculate its length=Introduction
Length of the string: 12

RESULT:
Thus, the C Program to find the length of the string has been executed and verified.

Ex.No: 2(g)
PROGRAM TO DISPLAY ARRAY ELEMENTS USING 2D ARRAYS
Date :

AIM:
To display array elements using 2D arrays
ALGORITHM:
Step1 : Start the program
Step2 : Get the elements of the array
Step 3 : Display the array elements
Step 4 : Stop the program

PROGRAM:
#include<stdio.h>
int main()
{
/* 2D array declaration*/
int disp[2][3];
/*Counter variables for the loop*/
28
int i, j;
for(i=0; i<2; i++)
{
for(j=0;j<3;j++)
{
printf("Enter value for disp[%d][%d]:", i, j);
scanf("%d", &disp[i][j]);
}
}
printf("Two Dimensional array elements:\n");
for(i=0; i<2; i++)
{
for(j=0;j<3;j++)
{
printf("%d ", disp[i][j]);
if(j==2)
{
printf("\n");
}
}
}
return 0;
}

OUTPUT:
Enter value for disp[0][0]:1
Enter value for disp[0][1]:2
Enter value for disp[0][2]:3
Enter value for disp[1][0]:4
Enter value for disp[1][1]:5
Enter value for disp[1][2]:6
Two Dimensional array elements:
123
29
456

RESULT:
Thus, the C Program to display the array elements of the 2D array has been executed
and the result was verified

Ex.No: 2(h)
PROGRAM TO FIND THE FREQUENCY OF A CHARACTER IN A STRING
Date :

AIM:
To find the frequency of a character in a string.

ALGORITHM:
Step 1 : Start the program
Step 2 : Get the string
Step 3 : Get the character for which frequency needs to be found
Step 4 : Display the frequency
Step 5 : Stop the program

PROGRAM:
#include <stdio.h>
int main()
{
30
char str[1000], ch;
int count = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("\nEnter a character to find its frequency: "); scanf("%c",
&ch);
for (int i = 0; str[i] != '\0'; ++i)
{
if (ch == str[i])
++count;
}
printf("\nFrequency of %c = %d", ch, count);
return 0;
}

OUTPUT:

Enter a string: This website is awesome.


Enter a character to find its frequency: e
Frequency of e = 4

31
RESULT:
Thus, the C Program to find the frequency of a character in a string has been executed
and verified.

Ex.No: 3(a)
IMPLEMENT C PROGRAMS USING POINTERS AND STRUCTURES
Date :

AIM:
To write a program to generate salary slip of employees using structures and pointers
ALGORITHM:
Step 1 : Start the Program
Step 2: Create a Structure to Store Employee Details
Step 3: Define the necessary function to calculate the salary of 12 employee.
Step 4: Generate Payslip and Display it.
Step 5: Stop the Program
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* structure to store employee salary details */
struct employee
{

32
int empId;
char name[32];
int basic, hra, da, ma; int pf, insurance;
float gross, net;
};
void printSalary(struct employee e1)
{
printf("Salary Slip of %s \n", e1.name);
printf("Employee ID: %d\n", e1.empId);
printf("Basic Salary: %d\n", e1.basic);
printf("House Rent Allowance: %d\n", e1.hra);
printf("Dearness Allowance: %d\n", e1.da);
printf("Medical Allowance: %d\n", e1.ma);
printf("Gross Salary: %.2f Rupees\n", e1.gross);

printf("Provident fund: %d\n", e1.pf);


printf("Insurance: %d\n", e1.insurance);
printf("\nNet Salary: %.2f Rupees\n\n", e1.net);
return; }

int main()
{
int i, ch, num, flag, empID;
struct employee *e1;
printf("Enter the number of employees:");
scanf("%d", &num);

e1 = (struct employee *)malloc(sizeof(struct employee) * num);

printf("Enter your input for every employee:\n");


for (i = 0; i <num; i++)
{
printf("Employee ID:");
scanf("%d", &(e1[i].empId));
getchar();
printf("Employee Name:");
fgets(e1[i].name, 32, stdin);
e1[i].name[strlen(e1[i].name) - 1] = '\0';
printf("Basic Salary, HRA:");
scanf("%d%d", &(e1[i].basic), &(e1[i].hra));
printf("DA, Medical Allowance:");
scanf("%d%d", &(e1[i].da), &(e1[i].ma));
printf("PF and Insurance:");
scanf("%d%d", &(e1[i].pf), &(e1[i].insurance));
printf("\n");
}

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


{

33
e1[i].gross = e1[i].basic + (e1[i].hra * e1[i].basic) / 100 + (e1[i].da * e1[i].basic) / 100 +
(e1[i].ma * e1[i].basic) / 100;
e1[i].net = e1[i].gross - (e1[i].pf + e1[i].insurance);

while (1)
{
printf("Enter employee ID to get payslip:");
scanf("%d", &empID);
flag = 0;
for (i = 0; i <num; i++)
{
if (empID == e1[i].empId)
{
printSalary(e1[i]); flag = 1;
}}
if (!flag)
{
printf("No Record Found!!\n");
}
printf("Do You Want To Continue(1/0):");
scanf("%d", &ch);
if (!ch)
{
break;

}
}
return 0;
}

OUTPUT

Enter the number of employees:1


Enter your input for every employee:
Employee ID:123
Employee Name:John
Basic Salary, HRA:10000 2340
DA, Medical Allowance:125 89
PF and Insurance:1000 120
Enter employee ID to get payslip:123
Salary Slip of John
Employee ID: 123
Basic Salary: 10000
House Rent Allowance: 2340
Dearness Allowance: 125
Medical Allowance: 89
34
Gross Salary: 265400.00 Rupees
Provident fund: 1000
Insurance: 120

Net Salary: 264280.00 Rupees

Do You Want To Continue(1/0):

RESULT
Thus, a program to generate salary slip of employees using structures and pointers was
executed successfully.

Ex.No: 3(b)
PROGRAM TO STORE STUDENT INFORMATION IN STRUCTURE AND
DISPLAY IT
Date :
AIM:
To store student information in structure and display it
ALGORITHM:
Step 1: START
Step 2: Read student details like name, mark1,2,3
Step 3: Calculate total, and average
Step 4: Display the grade
Step 5: STOP

PROGRAM:
#include<stdio.h>
35
struct student {
int roll_no, mark1, mark2, mark3, total;
float average;
char name[10],grade;
};
void struct_funct_student(struct student stu);
int main() {
struct student stud;
printf("\nRoll No.=");
scanf("%d",&stud.roll_no);
printf("Name=");
scanf("%s",stud.name);
printf("Mark1=");
scanf("%d",&stud.mark1);
printf("Mark2=");
scanf("%d",&stud.mark2); printf("Mark3=");
scanf("%d",&stud.mark3);
struct_funct_student(stud);
return 0;
}
void struct_funct_student( struct student stu)
{
stu.total = stu.mark1 + stu.mark2 + stu.mark3;
stu.average = stu.total / 3; if(stu.average >= 90)
stu.grade='S'; else if(stu.average >= 80)
stu.grade='A'; else if(stu.average >= 70)
stu.grade='B'; else if(stu.average >= 60)
stu.grade='C'; else if(stu.average >= 50)
stu.grade='D'; else stu.grade='F';
printf("\n ROLL NO. \t NAME \t TOTAL \t AVG \tGRADE \n");
printf("%d \t %s \t %d \t %f \t %c",
stu.roll_no,stu.name,stu.total,stu.average,stu.grade); }

OUTPUT:

36
Roll No.= 1
Name= a
Mark1= 95
Mark2= 94
Mark3= 96
ROLL NO.
1
NAME a TOTAL 285 Avg 95 Grade S

RESULT:
Thus, the C Program to store and display student details using structures has been
executed and the result was verified.

Ex.No: 4
IMPLEMENT C PROGRAMS USING FILES
Date :

AIM:
To write a program to Insert, update, delete and append telephone details of an
individual or a company into a telephone directory using random access file.
ALGORITHM :
Step 1: Create a random access file
Step 2: call the respective procedure to insert, update, delete or append based on user choice
Step 3: Access the random access file to make the necessary changes and save.

PROGRAM
#include <stdio.h>
#include<stdlib.h>
#include<fcntl.h>
37
#include <string.h>
struct person{
char name[20];
long telno;};

void appendData()
{
FILE *fp;
struct person obj;

fp=fopen("data.txt","a");
printf("*****Add Record****\n");

printf("Enter Name : ");


scanf("%s",obj.name);
printf("Enter Telephone No. : ");
scanf("%ld",&obj.telno);
fprintf(fp,"%20s %7ld",obj.name,obj.telno);
fclose(fp);}
void showAllData()
{
FILE *fp;
struct person obj;

fp=fopen("data.txt","r");
printf("*****Display All Records*****\n");
printf("\n\n\t\tName\t\t\tTelephone No.");
printf("\n\t\t=====\t\t\t===============\n\n");
while(!feof(fp))
{
fscanf(fp,"%20s %7ld",obj.name,&obj.telno);
printf("%20s %30ld\n",obj.name,obj.telno);

38
fclose(fp);
}
void findData()
{
FILE *fp;
struct person obj;
char name[20];
int totrec=0;

fp=fopen("data.txt","r");
printf("*****Display Specific Records*****\n");
printf("\nEnter Name : ");
scanf("%s",&name);
while(!feof(fp))
{
fscanf(fp,"%20s %7ld",obj.name,&obj.telno);
if(strcmp(obj.name,name)==0)
{
printf("\n\nName : %s",obj.name);
printf("\nTelephone No : %ld",obj.telno);
totrec++;
}}
if(totrec==0)
printf("\n\n\nNo Data Found");
else
printf("\n\n===Total %d Record found===",totrec);
fclose(fp);

}
void main()
{
char choice;
while(1)

39
{

printf("*****TELEPHONE DIRECTORY*****\n\n");
printf("1) Append Record\n");
printf("2) Find Record\n");
printf("3) Read all record\n");
printf("4) exit\n");
printf("Enter your choice : ");
fflush(stdin);
choice = getchar();
switch(choice){ case'1' ://call append record
appendData();
break;
case'2' ://call find record
findData();
break;
case'3' ://Read all record
showAllData();
break;
case'4' :
case 27 :
exit(1);

} }}

OUTPUT
*****TELEPHONE DIRECTORY*****

1) Append Record
2) Find Record
3) Read all record
4) exit
Enter your choice : 1
*****Add Record****

40
Enter Name : john
Enter Telephone No. : 789403121

Enter your choice : *****TELEPHONE DIRECTORY*****

1) Append Record
2) Find Record
3) Read all record
4) exit
Enter your choice : 2
*****Display Specific Records*****

Enter Name : john


Name : john
Telephone No : 7894031

Enter your choice : *****TELEPHONE DIRECTORY*****

1) Append Record
2) Find Record
3) Read all record
4) exit
Enter your choice : 3
*****Display All Records*****

Name Telephone No.


===== ===============

john 7894031
21 7894031
*****TELEPHONE DIRECTORY*****

41
RESULT:
Thus, the C program to insert, update, delete and append telephone details of an
individual or a company into a telephone directory using random access file was
successfully written and executed.

Ex.No: 5
DEVELOPMENT OF REAL TIME C APPLICATIONS
Date :

AIM
To develop a real time application to perform a spam filter in C
ALGORITHM
Step 1: Start
Step 2: Perform statistics on the types of characters read
Step 3: Calculate Loop over characters from standard input
Word length turns out to be a useful measure.
I'm defining words to end at a space or unprintable character.
42
It's also useful to see how many unprintables are their.
Else
If it's not a space, then consider it as part of a word
STEP 4 : start calculating statistics.
Assuming we didn't end with a space,
We haven't added this word length
STEP 5: Compare alphanum chars to punct chars
STEP 6 : Check word lengths
STEP 7: Unscientific: just root out extreme cases
Step 4: Display the Result
Step 5: Stop

PROGRAM
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
/* Returns a score from 0 to 100 indicating confidence that it's English */
int GetScore()
{
/*
* I'll be doing statistics on the types of characters read.
* So I need a bunch of integer variables to store the * running totals:
*/ int total = 0; /* total number of letters we've seen */ int
punct = 0; /* number of punctuation characters */ int
unprint = 0; int alpha = 0; int num = 0; int words = 1; /*
number of words -- we have at least one*/ int
thiswordlength = 0; int avwordlength = 0; int totalNonSpace
= 0; int score; char c;
/* Loop over characters from standard input */ while
((c = getchar()) != EOF)
{
/*
* Word length turns out to be a useful measure.
* I'm defining words to end at a space or unprintable character.

43
* It's also useful to see how many unprintables there are.
*/ if (isspace(c) || !
isprint(c))
{

if (thiswordlength > 0)
{
++words; avwordlength +=
thiswordlength; thiswordlength =
0;
} if (!
isprint(c)) {
++unprint;
++totalNonSpace;
}}
else
{
/* If it's not a space, then consider it as part of a word */
++thiswordlength;
if (isdigit(c))
++num;
else if (isalpha(c))
++alpha; else +
+punct;

++totalNonSpace;
}
++total;
}
/* We're done with the loop over input characters.
* Now we can start calculating statistics.
*/
/* Assuming we didn't end with a space,

44
* we haven't added thiswordlength yet, so add it now:
*/

avwordlength += thiswordlength; /* Compare


alphanum chars to punct chars */ score =
(alpha + num) * 100 / totalNonSpace;
printf("percentage of alpha + num: %d\n", score);
/* Check word lengths */ avwordlength /=
words; printf("av word length: %d\n",
avwordlength); /* Unscientific: just root out
extreme cases */ if (avwordlength < 3 &&
words > 5) score /= 2; if (avwordlength > 10)
score /= 2; return score;
}
#define THRESHHOLD 55
int main() { int score =
GetScore(); if (score <
THRESHHOLD)
{ printf("Score is %d: Not english.\n",
score); exit(1); }
printf("Score is %d: Probably not english.\n", score);
exit(0); }

OUTPUT

45
RESULT
Thus, a C program to develop a real time application to perform a spam filter was
executed successfully.

Ex.No: 6
ARRAY IMPLEMENTATION OF LIST ADT
Date :

AIM
To write a Program to implement list in array using C
46
ALGORITHM
Step 1: Start the program
Step 2: Initialize and declare variables using structure and arrays. Define the required sizeof
header files
Step 3: Enter the operations to perform in list as
a)Create list
b)Insert
c)Delete
d)View
Step 4: Based on the operations choosing, the list elements are structured.
Step 5: Stop the program

PROGRAM
#include<stdio.h>
#define maxsize 10
int list[maxsize],n;
void Create();
void Insert();
void Delete();
void Display();
void Search();
void main()
{
int choice;

do
{
printf("\n Array Implementation of List\n");
printf("\t1.create\n");
printf("\t2.Insert\n");
printf("\t3.Delete\n");
printf("\t4.Display\n");
printf("\t5.Search\n");
printf("\t6.Exit\n");

47
printf("\nEnter your choice:\t");
scanf("%d",&choice);
switch(choice)
{
case 1: Create();
break;
case 2: Insert();
break;
case 3: Delete();
break;
case 4: Display();
break;
case 5: Search();
break;
case 6: exit(1);
default: printf("\nEnter option between 1 - 6\n");
break;
}
}while(choice<7);
}
void Create()
{
int i;
printf("\nEnter the number of elements to be added in the list:\t");
scanf("%d",&n);
printf*”\n Enter the array elements \t”);
for(i=0;i<n;i++)
scanf("%d",&list[i]);
Display();
}
void Insert()
{
int i,data,pos;
printf("\nEnter the data to be inserted:\t");
48
scanf("%d",&data);
printf("\nEnter the position at which element to be inserted:\t");
scanf("%d",&pos);
for(i = n-1 ; i >= pos-1 ; i--)
list[i+1] = list[i];
list[pos-1] = data;
n+=1;
Display();
}
void Delete( )
{
int i,pos;
printf("\nEnter the position of the data to be deleted:\t");
scanf("%d",&pos);
printf("\nThe data deleted is:\t %d", list[pos-1]);
for(i=pos-1;i<n-1;i++)
list[i]=list[i+1];
n=n-1;
Display();
}
void Display()
{
int i;
printf("\n**********Elements in the array**********\n");
for(i=0;i<n;i++)
printf("%d\t",list[i]);
}
void Search()
{
int search,i,count = 0;
printf("\nEnter the element to be
searched:\t");
scanf("%d",&search);
for(i=0;i<n;i++)
49
{
if(search == list[i])
{
count++;
}
}
if(count==0)
printf("\nElement not present in the list");
else
printf("\nElement present in the list");
}

OUTPUT
Array Implementation of List
1.create 2.Insert 3.Delete
4.Display 5.Search 6.Exit

Enter your choice: 1


Enter the number of elements to be added in the list: 5
Enter the array elements: 1 2 3 4 5
**********Elements in the array**********
12345

Array Implementation of List


1.create 2.Insert 3.Delete 4.Display 5.Search 6.Exit
Enter your choice: 2
Enter the data to be inserted: 3
Enter the position at which element to be inserted: 1
**********Elements in the array**********
312345

Array Implementation of List


1.create 2.Insert 3.Delete 4.Display 5.Search 6.Exit
Enter your choice: 3

50
Enter the position of the data to be deleted: 4
The data deleted is: 3
**********Elements in the array**********
31245

Array Implementation of List


1.create 2.Insert 3.Delete 4.Display 5.Search 6.Exit
Enter your choice: 5
Enter the element to be searched: 1
Element present in the list

Array Implementation of List


1.create 2.Insert 3.Delete 4.Display 5.Search 6.Exit
Enter your choice:6

RESULT
Thus, a C Program to implement list in array was executed successfully.

Ex.No : 7(a) ARRAY IMPLEMENTATION OF STACK ADTS

51
Date :

AIM
To implement stack operations using array.

ALGORITHM

1. Start
2. Define a array stack of size max = 5
3. Initialize top = -1 4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then If top < max -1 Increment top
Store element at current position of top
Else
Print Stack overflow
Else If choice = 2 then
If top < 0 then
Print Stack underflow
Else
Display current top element
Decrement top
Else If choice = 3 then
Display stack elements starting from top
7. Stop

PROGRAM

#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t--------------------------------");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{

52
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
printf("\n\t EXIT POINT ");
break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}

}
}
while(choice!=4);
return 0;
}
void push()
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");

}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}
void pop()
{
53
if(top<=-1)
{
printf("\n\t Stack is under flow");
}
else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}

OUTPUT

Enter the size of STACK[MAX=100]:10

STACK OPERATIONS USING ARRAY


--------------------------------
1.PUSH
2.POP
3.DISPLAY
4.EXIT
Enter the Choice:1
Enter a value to be pushed:12

Enter the Choice:1


Enter a value to be pushed:24

Enter the Choice:1


Enter a value to be pushed:98

Enter the Choice:3

The elements in STACK

98

54
24
12
Press Next Choice
Enter the Choice:2

The popped elements is 98


Enter the Choice:3

The elements in STACK

24
12
Press Next Choice
Enter the Choice:4

EXIT POINT

RESULT
Thus, push and pop operations of a stack was demonstrated using arrays.

55
Ex.No : 7(b)
ARRAY IMPLEMENTATION OF QUEUE ADTS
Date :

AIM
To implement queue operations using array.

ALGORITHM

1. Start
2. Define a array queue of size max = 5
3. Initialize front = rear = –1
4. Display a menu listing queue operations
5. Accept choice
6. If choice = 1 then If rear < max -1 Increment rear
Store element at current position of rear Else
Print Queue Full
Else If choice = 2 then If
front = –1 then
Print Queue empty
Else
Display current front element
Increment front
Else If choice = 3 then

Display queue elements starting from front to rear.

7. Stop

PROGRAM

#include<stdio.h>
#define n 5
int main()
{
int queue[n],ch=1,front=0,rear=0,i,j=1,x=n;
printf("Queue using Array");
printf("\n1.Insertion \n2.Deletion \n3.Display \n4.Exit");
while(ch)
{
printf("\nEnter the Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
if(rear==x)
56
printf("\n Queue is Full");
else
{
printf("\n Enter no %d:",j++);
scanf("%d",&queue[rear++]);
}
break;
case 2:
if(front==rear)
{
printf("\n Queue is empty");
}
else
{
printf("\n Deleted Element is %d",queue[front++]);
x++;
}
break;
case 3:
printf("\nQueue Elements are:\n ");
if(front==rear)
printf("\n Queue is Empty");
else
{
for(i=front; i<rear; i++)
{
printf("%d",queue[i]);
printf("\n");
}
break;
case 4:
exit(0);
default:
printf("Wrong Choice: please see the options");
}
}
}
return 0;
}

OUTPUT

Queue using Array


1.Insertion
2.Deletion
3.Display
4.Exit
Enter the Choice:1

57
Enter no 1:10

Enter the Choice:1

Enter no 2:54

Enter the Choice:1

Enter no 3:98

Enter the Choice:1

Enter no 4:234

Enter the Choice:3

Queue Elements are:


10
54
98
234

Enter the Choice:2

Deleted Element is 10
Enter the Choice:3

Queue Elements are:


54
98
234

Enter the Choice:4

RESULT
Thus, insert and delete operation of a queue was demonstrated using arrays.

58
Ex.No: 8(a)
IMPLEMENTATION OF SINGLY LINKED LIST
Date :

AIM
To define a singly linked list node and perform operations such as insertions and
deletions dynamically.

ALGORITHM

1. Start
2. Define single linked list node as self referential structure
3. Create Head node with label = -1 and next = NULL using
4. Display menu on list operation
5. Accept user choice
6. If choice = 1 then
Locate node after which insertion is to be done
Create a new node and get data part
Insert new node at appropriate position by manipulating address
Else if choice = 2
Get node's data to be deleted.
Locate the node and delink the node
Rearrange the links
Else
Traverse the list from Head node to node which points to null
7. Stop
PROGRAM
#include<stdio.h>
#include<stdlib.h>

struct Node
{
int data;
struct Node *next;
};
59
void deleteStart (struct Node **head)
{
struct Node *temp = *head;

// if there are no nodes in Linked List can't delete


if (*head == NULL)
{
printf ("Linked List Empty, nothing to delete");
return;
}

// move head to next node


*head = (*head)->next;

printf ("\n%d deleted\n", temp->data);


free (temp);
}
void insertStart (struct Node **head, int data)
{
// dynamically create memory for this newNode
struct Node *newNode = (struct Node *) malloc (sizeof
(struct Node));

// assign data value


newNode->data = data;
// change the next node of this newNode
// to current head of Linked List
newNode->next = *head;

//re-assign head to this newNode


*head = newNode;
printf ("\n%d Inserted\n", newNode->data);

60
void display (struct Node *node)
{
printf ("\nLinked List: ");

// as linked list will end when Node is Null


while (node != NULL)
{
printf ("%d ", node->data);
node = node->next;
}
printf ("\n");
}

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

// Need '&' i.e. address as we need to change head


insertStart (&head, 100);
insertStart (&head, 80);
insertStart (&head, 60);
insertStart (&head, 40);
insertStart (&head, 20);

// No Need for '&' as not changing head in display operation


display (head);
deleteStart (&head);
deleteStart (&head);
display (head);
return 0;
}
OUTPUT

100 Inserted
61
80 Inserted
60 Inserted
40 Inserted
20 Inserted

Linked List: 20 40 60 80 100


20 deleted
40 deleted
Linked List: 60 80 100

Result
Thus, operation on single linked list is performed.

Ex.No: 8(b)
LINKED LIST IMPLEMENTATION OF STACK ADTS
Date :

62
AIM
To implement stack operations using linked list.

ALGORITHM
1. Start
2. Define a singly linked list node for stack
3. Create Head node
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
Create a new node with data
Make new node point to first node
Make head node point to new node
Else If choice = 2 then
Make temp node point to first node
Make head node point to next of temp node
Release memory
Else If choice = 3 then
Display stack elements starting from head node till null
7. Stop

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

// Structure to create a node with data and the next pointer


struct node {
int info;
struct node *ptr;
}*top,*top1,*temp;

int count = 0;
// Push() operation on a stack
void push(int data) {
if (top == NULL)
{
top =(struct node *)malloc(1*sizeof(struct node));
63
top->ptr = NULL;
top->info = data;
}
else
{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->ptr = top;
temp->info = data;
top = temp;
}
count++;
printf("Node is Inserted\n\n");
}

int pop() {
top1 = top;

if (top1 == NULL)
{
printf("\nStack Underflow\n");
return -1;
}
else
top1 = top1->ptr;
int popped = top->info;
free(top);
top = top1;
count--;
return popped;
}

void display() {
// Display the elements of the stack
top1 = top;

if (top1 == NULL)
{
printf("\nStack Underflow\n");
return;
}

printf("The stack is \n");


while (top1 != NULL)
{
printf("%d--->", top1->info);
top1 = top1->ptr;

64
}
printf("NULL\n\n");

int main() {
int choice, value;
printf("\nImplementation of Stack using Linked List\n");
while (1) {
printf("\n1. Push\n2. Pop\n3. Display\n4. Exit\n");
printf("\nEnter your choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("\nEnter the value to insert: ");
scanf("%d", &value);
push(value);
break;
case 2:
printf("Popped element is :%d\n", pop());
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\nWrong Choice\n");
}
}
}

OUTPUT

Implementation of Stack using Linked List


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

Enter your choice : 1

65
Enter the value to insert: 12
Node is Inserted

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

Enter your choice : 1

Enter the value to insert: 45


Node is Inserted

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

Enter your choice : 1

Enter the value to insert: 56


Node is Inserted

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

Enter your choice : 3


The stack is
56--->45--->12--->NULL

66
The stack is
56--->45--->12--->NULL

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

Enter your choice : 2


Popped element is :56
1. Push
2. Pop
3. Display
4. Exit

Enter your choice : 2


Popped element is :45
1. Push
2. Pop
3. Display
4. Exit

67
Enter your choice : 3
The stack is
12--->NULL

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

Enter your choice : 2


Popped element is :12
1. Push
2. Pop
3. Display
4. Exit

RESULT
Thus, push and pop operations of a stack was demonstrated using linked list.

68
Ex.No: 9(a)
IMPLEMENTATION OF POLYNOMIAL MANIPULATION
USING LINKED LIST
Date :

AIM
To implement a polynomial manipulation using linked lis

ALGORITHM

1. Input the multiplicand and multiplier and multiplier


2. Set both the polynomial in descending order of the coefficient
3. Multiply each node of multiplicand with each node of the multiplier (multiplication of the
coefficient part and addition of the exponent part) and add them into a newly formed linked
list in descending order
4. Coefficient having the same exponent value are added up with each other in the list and no
two nodes have the same exponent value.
5. Then the product is to be displayed in a proper way in the form of ax^n+bx^n-1+…
6. Certain points to be noted before displaying a polynomial: Any coefficient with value 0 must
not be displayed, 1x^n+2x^n-1 must not be displayed … node having coefficient value 1
must be displayed as x^n, node with exponent value 0 must be displayed as x not x^0, 1x^n-
2x^n-1 format should be maintained not standard like errors 1x^n+-2x^n-1 should come up.

PROGRAM

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct Node {
int coeff;
int exp;
struct Node * next;
}* poly = NULL;

void create() {
struct Node * t, * last = NULL;
int num, i;

printf("Enter number of terms: ");


scanf("%d", & num);
printf("Enter each term with coeff and exp:\n");

69
for (i = 0; i < num; i++) {
t = (struct Node * ) malloc(sizeof(struct Node));
scanf("%d%d", & t -> coeff, & t -> exp);
t -> next = NULL;
if (poly == NULL) {
poly = last = t;
} else {
last -> next = t;
last = t;
}
}
}

void Display(struct Node * p) {


printf("%dx%d ", p -> coeff, p -> exp);
p = p -> next;

while (p) {
printf("+ %dx%d ", p -> coeff, p -> exp);
p = p -> next;
}
printf("\n");
}

long Eval(struct Node * p, int x) {


long val = 0;

while (p) {
val += p -> coeff * pow(x, p -> exp);
p = p -> next;
}

return val;
}

int main() {
int x;
create();
Display(poly);

printf("Enter value of x: ");


scanf("%d", &x);

printf("%ld\n", Eval(poly, x));


return 0;
}

OUTPUT:
70
Enter number of terms:4
Enter each term with coeff and exp:
43
92
61
70
4*3 + 9*2 + 6*1 + 7*0
Enter the value of x: 2
87

RESULT
Thus, a program to implement polynomial manipulation using linked list was executed
successfully.

71
Ex.No: 10
IMPLEMENTATION OF BINARY TREES AND OPERATIONS OF
BINARY TREES
Date :

AIM
To implement a C program for Binary Tree and its operation.
ALGORITHM
1. Create a structure with key and 2 pointer variable left and right.
2. Creation of Binary Tree
• Check first if tree is empty, then insert node as root.
• Check if node value to be inserted is lesser than root node value, then • Call insert()
function recursively while there is non-NULL left node
• When reached to leftmost node as NULL, insert new node.
• Check if node value to be inserted is greater than root node value, then • Call insert()
function recursively while there is non-NULL right node
• When reached to rightmost node as NULL, insert new node.
3. Searching into binary tree
• Check first if tree is empty, then return NULL.
• Check if node value to be searched is equal to root node value, then return node
• Check if node value to be searched is lesser than root node value, then call search()
function recursively with left node
• Check if node value to be searched is greater than root node value, then call search()
function recursively with right node
• Repeat step 2, 3, 4 for each recursion call of this search function until node to be
searched is found.
4. Deletion of node
• Check first if root node is non-NULL, then
• Call deltree() function recursively while there is non-NULL left node • Call deltree()
function recursively while there is non-NULL right node
• Delete the node.
5. Displaying binary tree
Binary tree can be displayed in three forms – pre-order, in-order and post-order.
• Pre-order displays root node, left node and then right node.
• In-order displays left node, root node and then right node.
• Post-order displays left node, right node and then root node.
6.Stop

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

struct bin_tree {
int data;
struct bin_tree * right, * left;
};
typedef struct bin_tree node;

void insert(node ** tree, int val)


{
node *temp = NULL;
if(!(*tree))
{
temp = (node *)malloc(sizeof(node));
temp->left = temp->right = NULL;
temp->data = val;
*tree = temp;
return;
}

if(val < (*tree)->data)


{
insert(&(*tree)->left, val);
}
else if(val > (*tree)->data)
{
insert(&(*tree)->right, val);
}
}

void print_preorder(node * tree)


{
if (tree)
{
printf("%d\n",tree->data);
print_preorder(tree->left);
print_preorder(tree->right);
}
}

void print_inorder(node * tree)


{
if (tree)
{
print_inorder(tree->left);
printf("%d\n",tree->data);
print_inorder(tree->right);
}
}

void print_postorder(node * tree)

73
{
if (tree)
{
print_postorder(tree->left);
print_postorder(tree->right);
printf("%d\n",tree->data);
}
}

void deltree(node * tree)


{
if (tree)
{
deltree(tree->left);
deltree(tree->right);
free(tree);
}
}

node* search(node ** tree, int val)


{
if(!(*tree))
{
return NULL;
}

if(val < (*tree)->data)


{
search(&((*tree)->left), val);
}
else if(val > (*tree)->data)
{
search(&((*tree)->right), val);
}
else if(val == (*tree)->data)
{
return *tree;
}
}
void main()
{
node *root;
node *tmp;
//int i;
root = NULL;
/* Inserting nodes into tree */
insert(&root, 9);
insert(&root, 4);
insert(&root, 15);
insert(&root, 6);
insert(&root, 12);
insert(&root, 17);
insert(&root, 2);

74
/* Printing nodes of tree */
printf("Pre Order Display\n");
print_preorder(root);
printf("In Order Display\n");
print_inorder(root);
printf("Post Order Display\n");
print_postorder(root);

/* Search node into tree */


tmp = search(&root, 4);
if (tmp)
{
printf("Searched node=%d\n", tmp->data);
}
else
{
printf("Data Not found in tree.\n");
}
/* Deleting all nodes of tree */
deltree(root);
}

OUTPUT
Pre Order Display
9
4
2
6
15
12
17
In Order Display
2
4
6
9
12
15

75
17
Post Order Display
2
6
4
12
17
15
9
Searched node=4

RESULT
Thus, a C program to implement Binary Tree and its operation was executed successfully.

76
Ex.No: 11
IMPLEMENTATION OF BINARY SEARCH TREES
Date :

AIM
To insert and delete nodes in a binary search tree.

ALGORITHM
1. Create a structure with key and 2 pointer variable left and right.
2. Read the node to be inserted.
If (root==NULL) root=node
else if (root->key<node->key) root->right=NULL
else
Root->left=node
3. For Deletion if it is a leaf node
Remove immediately
Remove pointer between del node & child if it is
having one child
Remove link between del node&child
Link delnode is child with delnodes parent
If it is a node with a children
Find min value in right subtree
Copy min value to delnode place
Delete the duplicate
4. Stop

PROGRAM

/* Binary Search Tree */


// Tree traversal in C

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

struct node {
77
int item;
struct node* left;
struct node* right;
};

// Inorder traversal
void inorderTraversal(struct node* root) {
if (root == NULL) return;
inorderTraversal(root->left);
printf("%d ->", root->item);
inorderTraversal(root->right);
}

// Preorder traversal
void preorderTraversal(struct node* root) {
if (root == NULL) return;
printf("%d ->", root->item);
preorderTraversal(root->left);
preorderTraversal(root->right);
}

// Postorder traversal
void postorderTraversal(struct node* root) {
if (root == NULL) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ->", root->item);
}

// Create a new Node


struct node* createNode(value) {
struct node* newNode = malloc(sizeof(struct node));
newNode->item = value;
newNode->left = NULL;
newNode->right = NULL;

return newNode;
}

// Insert on the left of the node


struct node* insertLeft(struct node* root, int value) {
root->left = createNode(value);
return root->left;
}

// Insert on the right of the node


struct node* insertRight(struct node* root, int value) {

78
root->right = createNode(value);
return root->right;
}

int main() {
struct node* root = createNode(1);
insertLeft(root, 2);
insertRight(root, 3);
insertLeft(root->left, 4);
printf("Inorder traversal \n");
inorderTraversal(root);
printf("\nPreorder traversal \n");
preorderTraversal(root);
printf("\nPostorder traversal \n");
postorderTraversal(root);
}

OUTPUT
Inorder traversal of the given tree
20 30 40 50 60 70 80
Delete 20
Inorder traversal of the modified tree
30 40 50 60 70 80
Delete 30
Inorder traversal of the modified tree
40 50 60 70 80
Delete 50
Inorder traversal of the modified tree
40 60 70 80

RESULT

Thus, a program to implement insertion and deletion in a node from a binary search tree was
executed successfully.

Ex.No: 12(a) IMPLEMENTATION OF LINEAR SEARCH

79
Date :

AIM
To perform linear search of an element on the given array.

ALGORITHM
1. Start
2. Read number of array elements n

3. Read array elements Ai, i = 0,1,2,…n–1


4. Read search value
5. Assign 0 to found
6. Check each array element against search If Ai = search then found = 1
Print "Element found" Print position i
Stop
7. If found = 0 then print "Element not found"
8. Stop
PROGRAM
/* Linear search on a sorted array */

#include <stdio.h>

#include <conio.h> main()

int a[50],i, n, val, found;


clrscr();
printf("Enter number of elements : ");
scanf("%d", &n);
printf("Enter Array Elements : \n");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
printf("Enter element to locate : ");
scanf("%d", &val);
found = 0;

80
for(i=0; i<n; i++)
{
if (a[i] == val)
{
printf("Element found at position %d", i);
found = 1;
break;
}
}
if (found == 0)
printf("\n Element not found");
getch();
}
OUTPUT

Enter number of elements : 7 Enter


Array Elements :
23 6 12 5 0 32 10
Enter element to locate : 5
Element found at position 3

RESULT
Thus, an array was linearly searched for an element's existence.

Ex.No: 13(a)
IMPLEMENTATION OF INSERTION SORT
Date :

81
AIM
To sort an array of N numbers using Insertion sort.

ALGORITHM
1. Start

2. Read number of array elements n

3. Read array elements Ai

4. Sort the elements using insertion sort

• In pass p, move the element in position p left until its correct place is found among the first p
+ 1 elements.
• Element at position p is saved in temp, and all larger elements (prior to position p) are
moved one spot to the right. Then temp is placed in the correct spot. 5. Stop

PROGRAM
/* Insertion Sort */
#include<stdio.h>
Void main()
{
int i, j, k, n, temp, a[20], p=0;
printf("Enter total elements: ");
scanf("%d",&n);
printf("Enter array elements: ");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(i=1; i<n; i++)
{
temp = a[i];
j = i - 1;
while((temp<a[j]) && (j>=0))
{
a[j+1] = a[j]; j = j - 1;
}
a[j+1] = temp; p++;
82
printf("\n After Pass %d: ", p);
for(k=0; k<n; k++)
printf(" %d", a[k]);
}
printf("\n Sorted List : "); for(i=0;
i<n; i++)
printf(" %d", a[i]);
}

OUTPUT

Enter total elements: 6


Enter array elements: 34 8 64 51 32 21
After Pass 1: 8 34 64 51 32 21
After Pass 2: 8 34 64 51 32 21
After Pass 3: 8 34 51 64 32 21
After Pass 4: 8 32 34 51 64 21
After Pass 5: 8 21 32 34 51 64
Sorted List : 8 21 32 34 51 64

RESULT
Thus, array elements were sorted using insertion sort.

Ex.No: 13(b)
IMPLEMENTATION OF MERGE SORT
Date :

AIM
To sort an array of N numbers using Merge sort.

83
ALGORITHM
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Divide the array into sub-arrays with a set of elements
5. Recursively sort the sub-arrays
6. Merge the sorted sub-arrays onto a single sorted array.
7. Stop

PROGRAM
/* Merge sort */
#include <stdio.h>
#include <conio.h>
void merge(int [],int ,int ,int );
void part(int [],int ,int );
int size;
void main()
{
int i, arr[30];
printf("Enter total no. of elements : ");
scanf("%d", &size);
printf("Enter array elements : ");
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
part(arr, 0, size-1);

printf("\n Merge sorted list : ");


for(i=0; i<size; i++)
printf("%d ",arr[i]);
getch();
}
void part(int arr[], int min, int max)
{

84
int i, mid; if(min <
max)
{
mid = (min + max) / 2;
part(arr, min, mid);
part(arr, mid+1, max);
merge(arr, min, mid, max);
}
if (max-min == (size/2)-1)
{
printf("\n Half sorted list : ");
for(i=min; i<=max; i++)
printf("%d ", arr[i]);
}}
void merge(int arr[],int min,int mid,int max)
{
int tmp[30];
int i, j, k, m;
j = min;
m = mid + 1;
for(i=min; j<=mid && m<=max; i++)
{
if(arr[j] <= arr[m]) {
tmp[i] = arr[j]; j++;
}
else {
tmp[i] = arr[m]; m++;
}}
if(j > mid)
{
for(k=m; k<=max; k++)
{
tmp[i] = arr[k];
i++;

85
}
}
else {
for(k=j; k<=mid; k++)
{
tmp[i] = arr[k]; i++;
}
}
for(k=min; k<=max; k++)
arr[k] = tmp[k];
}

OUTPUT

Enter total no. of elements : 8


Enter array elements : 24 13 26 1 2 27 38 15

Half sorted list : 1 13 24 26


Half sorted list : 2 15 27 38
Merge sorted list : 1 2 13 15 24 26 27 38

86
RESULT
Thus, array elements were sorted using merge sort's divide and conquer method.

Ex.No: 13(c)
IMPLEMENTATION OF QUICK SORT
Date :

AIM
To sort an array of N numbers using Quick sort.

ALGORITHM
1. START.
2. use two pointers up and down initialized to the first and last elements respectively, down=lb
and up=ub.
87
3. pivot=A[lb].
4. Repeatedly increase down as long as the element is < pivot i.e A[down]<pivot.
5. Repeatedly increase down as long as the element is < pivot i.e repeatedly decrease up as
long as the element is >pivot i.e A[up]>pivot.
6. If up and down cross each other i.e up <=down, the correct position of the pivot is up and
A[up] and pivot are interchanged.
7. If up and down do not cross, A[up] and A[down] are interchanged and the process is
repeated till they do not cross or coincide.
8. Return up.
9. STOP.

PROGRAM
#include<stdio.h>
int n;
int main()
{
int arr[30],i,r,i;
void quick_sort(int arr[],int,int); printf("\nInput
number of elements: "); scanf(" %d",&n);
printf("\nInput array values one by one: ");
for(i=0;i<n;i++)
scanf(" %d",&arr[i]);
i=0;
r=n-1;
quick_sort(arr,l,r);
printf("\nThe quick sorted array is: ");
for(i=0;i<n;i++)
printf(" %d",arr[i]);
printf("\n");
}
void quick_sort(int arr[],int low,int high)
{
int temp,left,right,x,k;
if(low>=high)

88
return;
else
{
x=arr[low];
right=low+1;
left = high;
while(right<=left)
{
while(arr[right]<x && right <= high)
{
right ++;
}
while(arr[left]>x && left > low)
{
left--;
} if(right<left)
{ temp=arr[right];
arr[right]=arr[left];
arr[left]=temp; right++;
left--;
}
}
arr[low]=arr[left]; arr[left]=x;
quick_sort(arr,low,left-1);
quick_sort(arr,left+1,high);
}
}

OUTPUT

Input number of elements: 5


Input array values one by one: 3
5

89
1
9
2

The quick sorted array is: 1 2 3 5 9

RESULT
Thus, array elements were sorted using Quick sort's method.

Ex.No: 14(a)
IMPLEMENTATION OF OPEN ADDRESSING (LINEAR PROBING)
Date :
AIM
To implement a Hash Table 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
90
* 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.

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
* flag = 2 : data existed at least once
*/
struct item *data;
};
struct hashtable_item *array;
int size = 0; int max
= 10;
/* initializing hash table array */ void
int_array()
{
91
int i;
for (i = 0; i < max; i++)
{
array[i].flag = 0; array[i].data
= NULL;
}
}
/* to every key, it will generate a corresponding index */ int
hashcode(int key)
{
return (key % max);
}

/* to insert an element in the hash table */


void insert(int key, int value)
{
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;

/* probing through the array until we reach an empty space */ while


(array[i].flag == 1)
{
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);
}

92
/* 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()
{

93
return size;
}
void main()
{
int choice, key, value, n, c; clrscr();
array = (struct hashtable_item*) malloc(max * sizeof(struct hashtable_item*));
init_array();

do {
printf("Implementation of Hash Table in C with Linear Probing \n\n");
printf("MENU-: \n1.Inserting item in the Hashtable"
"\n2.Removing item from the Hashtable"
"\n3.Check the size of Hashtable"
"\n4.Display Hashtable"
"\n\n Please enter your choice-:");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Inserting element in Hashtable\n");
printf("Enter key and value-:\t");
scanf("%d %d", &key, &value); insert(key,
value);
break;
case 2:
printf("Deleting in Hashtable \n Enter the key to delete-:");
scanf("%d", &key);
remove_element(key);
break;
case 3:
n = size_of_hashtable();
printf("Size of Hashtable is-:%d\n", n); break;

case 4:
display();
break; default:
printf("Wrong Input\n");
}
printf("\n Do you want to continue-:(press 1 for yes)\t");
scanf("%d", &c);
}
while(c == 1);
getch();
}
OUTPUT
Implementation of Hash Table in C with Linear Probing MENU-:
1. Inserting item in the Hashtable

94
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

95
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

96
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, a program to implement a Hash Table with Linear Probing was executed successfully.

Ex.No: 15
IMPLEMENTATION OF OPEN ADDRESSING (QUADRATIC PROBING)
Date :

AIM
To implement a Hash Table 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
97
(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>
/* 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;

98
/* 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;
}

99
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

100
{
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:

101
printf("Wrong Input\n");

}
printf("\n Do you want to continue-:(press 1 for yes)\t");
scanf("%d", &c);
}while(c == 1);
getch();
}

OUTPUT

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

102
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

103
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

104
RESULT
Thus, a program to implement a Hash Table with Quadratic Probing was executed
successfully.

105

You might also like