0% found this document useful (0 votes)
2 views102 pages

Manual

The document is a manual for a C Programming and Data Structures laboratory course at Anna University, detailing various programming tasks and algorithms. It includes examples of C programs using statements, expressions, decision making, iterative statements, functions, arrays, pointers, file handling, and a banking system. Each section outlines the aim, algorithm, program code, output, and result of executing the program.

Uploaded by

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

Manual

The document is a manual for a C Programming and Data Structures laboratory course at Anna University, detailing various programming tasks and algorithms. It includes examples of C programs using statements, expressions, decision making, iterative statements, functions, arrays, pointers, file handling, and a banking system. Each section outlines the aim, algorithm, program code, output, and result of executing the program.

Uploaded by

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

lOMoARcPSD|11267200

Manual

Data Structures (Anna University)

Studocu is not sponsored or endorsed by any college or university


Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

ANNA UNIVERSITY
THANTHAI PERIYAR GOVERNMENT INSTITUTE OF
TECHNOLOGY
VELLORE – 632002.

DEPARTMENT OF ELECTRICAL AND ELECTRONICS


ENGINEERING

CS3362 – C PROGRAMMING & DATA STRUCTURES


LABORATORY

Downloaded by Omprakash D ([email protected])


lOMoARcPSD|11267200

Contents
C PROGRAM USING STATEMENTS .................................................................... 3
C PROGRAM USING EXPRESSIONS ................................................................... 4
C PROGRAM USING DECISION MAKING ......................................................... 5
C PROGRAM USING ITERATIVE STATEMENTS .............................................. 6
C PROGRAM USING FUNCTIONS ....................................................................... 7
C PROGRAM USING ARRAY ................................................................................ 8
C PROGRAM USING POINTERS ........................................................................... 9
C PROGRAM USING FILES ................................................................................. 11
C PROGRAM USING INTERNAL MARKS ........................................................ 13
C PROGRAM USING BANKING SYSTEM ........................................................ 16
ARRAY IMPLEMENTATION OF STACK ADT ................................................. 24
ARRAY IMPLEMENTATION OF QUEUE ADT ................................................. 28
ARRAY IMPLEMENTATION OF CIRCULAR QUEUE ADT ........................... 32
IMPLEMENTATION OF SINGLY LINKED LIST ............................................... 36
LINKED LIST IMPLEMENTATION OF STACK ADT ....................................... 42
LINKED LIST IMPLEMENTATION OF LINEAR QUEUE ADT ...................... 45
IMPLEMENTATION OF EVALUATING POSTFIX EXPRESSIONS................ 54
IMPLEMENTATION OF INFIX TO POSTFIX CONVERSION ......................... 56
IMPLEMENTATION OF BINARY SEARCH TREES ......................................... 58
IMPLEMENTATION OF HEAPS USING PRIORITY QUEUES ........................ 65
IMPLEMENTATION OF LINEAR SEARCH ....................................................... 71
IMPLEMENTATION OF BINARY SEARCH ...................................................... 73
IMPLEMENTATION OF INSERTION SORT ...................................................... 75
IMPLEMENTATION OF SELECTION SORT ..................................................... 77
IMPLEMENTATION OF MERGE SORT ............................................................. 79
IMPLEMENTATION OF OPEN ADDRESSING (LINEAR PROBING)............. 82
IMPLEMENTATION OF DEQUEUE .................................................................... 88
IMPLEMENTATION OF THREADED BINARY TREE ..................................... 93

Downloaded by Omprakash D ([email protected])


lOMoARcPSD|11267200

C PROGRAM USING STATEMENTS

AIM:

To write the C program using statements.

ALGORITHM:
Step 1: Open the Turbo C.
Step 2: Add the header file.
Step 3: Input the main
Step 4: Input the value as you needed.
Step 5: Use if condition.
Step 6: Print the condition using 'printf'
Step 7: Scan the condition using 'scanf'.
Step 8: Close the program.

PROGRAM:

// C program to illustrate If statement

#include <stdio.h>

int main()
{
int i = 10;

if (i < 15) {
printf("10 is less than 15 \n");
}

printf("I am Not in if");


}

OUTPUT:

Before swap : 10 20
After swap : 20 10

RESULT:
Thus, the C program using the statements is executed successfully.

3
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

C PROGRAM USING EXPRESSIONS

AIM:
To write the C program using expressions.

ALGORITHM:
Step 1: Open the Turbo C.
Step 2: Add the header file.
Step 3: Input the main
Step 4: Input the value as you needed.
Step 5: Use if condition. And write the expressions for the input values.
Step 6: Print the condition using 'printf'
Step 7: Scan the condition using 'scanf'.
Step 8: Close the program.

PROGRAM:
#include <stdio.h>
int main(){
int x=4;
if(x%2==0)
{
printf("The number x is even");
}
else
printf("The number x is not even");
return 0;
}

OUTPUT:

Line 1 – Value of c is 34
Line 2 – Value of c is 11
Line 3 – Value of c is 210
Line 4 – Value of c is 2

RESULT:

Thus, the C program using the expressions is executed successfully.

4
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

C PROGRAM USING DECISION MAKING

AIM:
To write the C program using decision making.

ALGORITHM:
Step 1: Open the Turbo C.
Step 2: Add the header file.
Step 3: Input the main
Step 4: Input the value as you needed.
Step 5: Use if condition. And write the expressions for the input values.
Step 6: Print the condition using 'printf'
Step 7: Scan the condition using 'scanf'.
Step 8: Close the program.

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

int a = 100;
int b = 200;
if( a == 100 ) {

if( b == 200 ) {
printf("Value of a is 100 and b is 200\n" );
}
}

printf("Exact value of a is : %d\n", a );


printf("Exact value of b is : %d\n", b );

return 0;
}

OUTPUT:
Enter any number : 10
Number is not divisible by 5 and 11

RESULT:
Thus, the C program using the decision making is executed successfully.
5
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

C PROGRAM USING ITERATIVE STATEMENTS


AIM:
To write the C program using iterative statements.

ALGORITHM:
Step 1: Open the Turbo C.
Step 2: Add the header file.
Step 3: Input the main
Step 4: Input the value as you needed.
Step 5: Use for loop condition. And write the expressions for the input values.
Step 6: Print the condition using 'printf'
Step 7: Scan the condition using 'scanf'.
Step 8: Close the program.

PROGRAM:
// Print numbers from 1 to 10
#include <stdio.h>

int main() {
int i;

for (i = 1; i < 11; ++i)


{
printf("%d ", i);
}
return 0;
}

OUTPUT:
Value of a : 10
Value of a : 11
Value of a : 12
Value of a : 13
Value of a : 14

RESULT:
Thus, the C program using the iterative statement is executed successfully.

6
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

C PROGRAM USING FUNCTIONS

AIM:
To write the C program using functions.

ALGORITHM:
Step 1: Open the Turbo C.
Step 2: Add the header file.
Step 3: Input the main
Step 4: Input the value as you needed.
Step 5: Use for loop condition. And write the expressions for the input values.
Step 6: Print the condition using 'printf'.
Step 7: Scan the condition using 'scanf'.
Step 8: Close the program.

PROGRAM:
#include <stdio.h>
int hcf(int n1, int n2);
int main() {
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1, n2));
return 0;}

int hcf(int n1, int n2) {


if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1;
}
OUTPUT:
Enter the side of square : 10
AOS : 100.000000

RESULT:

Thus, the C program using the functions is executed successfully.

7
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

C PROGRAM USING ARRAY


AIM:
To write the C program using array.
ALGORITHM:
Step 1: Open the Turbo C.
Step 2: Add the header file.
Step 3: Input the main
Step 4: Input the value as you needed.
Step 5: Use for loop condition. And write the expressions for the input values.
Step 6: Print the condition using 'printf'.
Step 7: Scan the condition using 'scanf'.
Step 8: Close the program.

PROGRAM:
#include <stdio.h>
int main() {
int values[5];
printf("Enter 5 integers: ");
// taking input and storing it in an array
for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}

printf("Displaying integers: ");

// printing elements of an array


for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}
OUTPUT:
Please enter 3 numbers : 35
54
97
Average is 62

RESULT:
Thus, the C program using the array is executed successfully.
8
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

C PROGRAM USING POINTERS

AIM:
To write the C program using pointers.

ALGORITHM:
Step 1: Open the Turbo C.
Step 2: Add the header file.
Step 3: Input the main
Step 4: Input the value as you needed.
Step 5: Use for loop condition. And write the expressions for the input values.
Step 6: Print the condition using 'printf'.
Step 7: Scan the condition using 'scanf'.
Step 8: Close the program.

PROGRAM:

#include <stdio.h>
int main()
{
int* pc, c;

c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22

pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22

c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11

*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}

9
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

OUTPUT:
Enter the no of employees
2
Enter employee info as id, name, age, salary
2063
Sundar
20
1000000
2028
Murali
20
2000000

EMP _ ID EMP _NAME EMP _AGE EMP_SAL


2063 SUNDAR 20 1000000
2028 MURAL 20 2000000

RESULT:
Thus, the C program using the pointers is executed successfully.

10
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

C PROGRAM USING FILES

AIM:
To write the C program using files.

ALGORITHM:
Step 1: Open the Turbo C.
Step 2: Add the header file.
Step 3: Input the main
Step 4: Input the value as you needed.
Step 5: Create a file at a location.
Step 6: Use the file operations for the opening and reading, writing files.
Step 7: Print & Scan the condition using “printf” 'scanf'.
Step 8: Close the program.

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

int main() {
char sentence[1000];

// creating file pointer to work


with files FILE *fptr;

// opening file in writing


mode fptr =
fopen("program.txt",
"w");

// exiting
program if (fptr
== NULL) {
printf("Error!
11
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

"); exit(1);
}
printf("Enter a sentence:\n");
fgets(sentence,
sizeof(sentence), stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
return 0;
}

OUTPUT:

Hello! I am Raju! I am studying in Thanthai Periyar Govt. Institute of Technology, Vellore.

RESULT:
Thus, the C program using the files is executed successfully.

12
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

C PROGRAM USING INTERNAL MARKS

AIM:
To write the C program using internal marks.

ALGORITHM:
Step 1: Open the Turbo C.
Step 2: Add the header file.
Step 3: Input the main
Step 4: Calculate total, percentage & average of the student.
Step 5: Use if & if else condition. And write the expressions for the input values.
Step 6: Print the condition using 'printf'.
Step 7: Scan the condition using 'scanf'.
Step 8: Close the program.

PROGRAM

// C Program to Find Grade of a Student Using


If else Ladder #include <stdio.h>

int main() {
float subject_1, subject_2, subject_3, subject_4,
subject_5; float total, average, percentage;
char grade;

printf("Enter the marks of five subjects::\n");


scanf("%f%f%f%f%f", &subject_1, &subject_2, &subject_3, &subject_4,
&subject_5);

// It will calculate the Total, Average and Percentage


total = subject_1 + subject_2 + subject_3 +
subject_4 + subject_5; average = total / 5.0;
13
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

percentage = (total / 500.0) * 100;

// It will calculate the


Grade if (average >=
90)
grade = 'A';
else if (average >= 80 &&
average < 90) grade = 'B';
else if (average >= 70 &&
average < 80) grade = 'C';
else if (average >= 60 &&
average < 70) grade = 'D';
else
grade = 'E';

// It will produce the final OUTPUT


printf("\nThe Total marks is: \t%.2f /
500.00\n", total); printf("\nThe Average
marks is:\t%.2f\n", average); printf("\nThe
Percentage is: \t%.2f%%\n", percentage);
printf("\nThe Grade is: \t'%c'\n", grade);
return 0;
}

14
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

OUTPUT:

Enter the marks of five subjects:

88
90
92
70
89
The total marks is : 429.00 / 500.00
The average mark is : 85.80
The percentage is : 85.80%
The grade is : B

RESULT:
Thus, the C program using the internal marks is executed successfully.

15
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

C PROGRAM USING BANKING SYSTEM


AIM:
To write the C program using banking system.

ALGORITHM:
Step 1: Open the Turbo C.
Step 2: Add the header file.
Step 3: Input the main
Step 4: Enter account number, balance, name, deposit amount, withdraw of the customers.
Step 5: Use cases for the different condition of operation.
Step 6: Print the condition using 'printf'.
Step 7: Scan the condition using 'scanf'.
Step 8: Close the program.

PROGRAM
#include <stdio.h>

struct customer
{
int
account_no;
char
name[80]; int
balance;
};

void accept(struct customer[],


int); void display(struct
customer[], int); int 16
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

search(struct customer[], int,


int);
void deposit(struct customer[], int,
int, int); void withdraw(struct
customer[], int, int, int);

int main()
{
struct customer data[20];
int n, choice, account_no, amount, index;

printf("Banking System\n\n");
printf("Number of customer records you want to
enter? : "); scanf("%d", &n);
accept(data,
n); do
{
printf("\nBanking System Menu
:\n"); printf("Press 1 to display
all records.\n"); printf("Press 2
to search a record.\n");
printf("Press 3 to deposit
amount.\n"); printf("Press 4 to
withdraw amount.\n");
printf("Press 0 to exit\n");
printf("\nEnter choice(0-4) : ");
17
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

scanf("%d", &choice);
switch (choice)
{
case 1:
display(data, n);
break;
case 2:
printf("Enter account number to search
: "); scanf("%d", &account_no);
index = search(data, n,
account_no); if (index == - 1)
{
printf("Record not found : ");
}
else
{
printf("A/c Number: %d\nName:
%s\nBalance: %d\n",
data[index].account_no,
data[index].name, data[index].balance);
}
break;
case 3:

printf("Enter account number


: "); scanf("%d",
&account_no); printf("Enter
18
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

amount to deposit : ");


scanf("%d", &amount);
deposit(data, n, account_no,
amount); break;
case 4:
printf("Enter account number :
"); scanf("%d", &account_no);
printf("Enter amount to
withdraw : "); scanf("%d",
&amount);
withdraw(data, n, account_no, amount);
}
}
while (choice != 0);

return 0;
}

void accept(struct customer list[80], int s)


{
int i;
for (i = 0; i < s; i++)
{
printf("\nEnter data for Record #%d", i + 1);

printf("\nEnter account_no
19
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

: "); scanf("%d",
&list[i].account_no);
fflush(stdin);
printf("Enter name : ");
gets(list[i].name
); list[i].balance
= 0;
}
}

void display(struct customer list[80], int s)


{
int i;

printf("\n\nA/c
No\tName\tBalance\n"); for (i =
0; i < s; i++)
{
printf("%d\t%s\t%d\n", list[i].account_no,
list[i].name, list[i].balance);
}
}

int search(struct customer list[80], int s, int number)


{
int i;

20
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

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


{
if (list[i].account_no == number)
{
return i;
}
}
return - 1;
}
void deposit(struct customer list[], int s, int number, int amt)
{
int i = search(list, s,
number); if (i == - 1)
{
printf("Record not found");
}
else
{
list[i].balance += amt;
}
}

void withdraw(struct customer list[], int s, int number, int amt)


{
int i = search(list, s,
number); if (i == - 1)
{
printf("Record not found\n"); 21
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

}
else if (list[i].balance < amt)
{
printf("Insufficient balance\n");
}
else
{
list[i].balance -= amt;
}
}

OUTPUT:

Banking System
Number of customer records you want to enter? : 2
Enter data for Record #1
Enter account_no : 12345678901
Enter name : Sundar
Enter data for Record #2
Enter account_no : 09876543210
Enter name : Ramesh

Banking System
Menu :
Press 1 to display all records.
Press 2 to search a record.
Press 3 to deposit amount.
Press 4 to withdraw amount.
Press 0 To exit
22
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

Enter choice(0-4) : 3
Enter account number : 09876543210
Enter amount to deposit : 5000
Banking System Menu :
Press 1 to display all records.
Press 2 to search a record.
Press 3 to deposit amount.
Press 4 to withdraw amount.
Press 0 To exit
Enter choice(0-4) : 4
- Enter account number : 09876543210

RESULT:
Thus, the C program using the banking system is executed successfully.

23
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

ARRAY IMPLEMENTATION OF STACK ADT

AIM
To write a C program to implement stack ADT using array.

ALGORITHM
Step 1: Start the program.
Step 2: For Push operation, check for stack overflow.
Step 3: If Top>=N then print stack overflow else increment Top and insert the
element. Step 4: For Pop operation, check for underflow of the stack.
Step 5: If Top=0 then print stack underflow else decrement Top and delete the
element. Step 6: Stop the program.

PROGRAM

#include <stdio.h>
#define MAXSIZE 5

struct stack{
int stk[MAXSIZE]; int top;
};
typedef struct stack STACK; STACK s;

void push(void); int


pop(void); void
display(void);

void main (){


int choice;
int option = 1; s.top = -
1;

printf ("STACK OPERATION\n");

while (option){
printf (" \n");
printf ("1-->PUSH\n");
printf ("2-->POP\n");
printf ("3-->DISPLAY\n");
24
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

printf ("4 -->EXIT\n");


printf (" \n");
printf ("Enter your choice\n");
scanf("%d", &choice);{
fflush (stdin);
printf ("Do you want to continue(Type 0 or 1)?\n");
scanf("%d", &option);
}
}
void push (){
int num;
if (s.top == (MAXSIZE - 1))
{
printf ("Stack is Full\n"); return;
}
else
{
printf ("Enter the element to be pushed\n");
scanf ("%d", &num);
s.top = s.top + 1;
s.stk[s.top] = num;
}
return;
}
int pop (){
int num;
if (s.top == - 1)
{
printf ("Stack is Empty\n"); return
(s.top);
}
else
{
num = s.stk[s.top];
printf ("Popped element is = %dn", s.stk[s.top]);
s.top = s.top - 1;
}
return(num);
}
void display (){
int i;
25
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

if (s.top == -1)
{
printf ("Stack is empty\n"); return;
}
else
{
printf ("\n The status of the stack is \n"); for
(i = s.top; i >= 0; i--)
{
printf ("%d\n", s.stk[i]);
}
}
printf ("\n");
}

OUTPUT

STACK OPERATION
1--> PUSH
2--> POP
3--> DISPLAY
4--> EXIT
Enter your choice 1
Enter the element to be pushed 34
Do you want to continue(Type 0 or 1)? 0

1--> PUSH
2--> POP
3--> DISPLAY
4--> EXIT

Enter your choice 1


Enter the element to be pushed 34
Do you want to continue(Type 0 or 1)? 1

1--> PUSH
2--> POP
3--> DISPLAY
4--> EXIT
Enter your choice 2 Popped element is = 34
Do you want to continue(Type 0 or 1)? 1
26
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

1--> PUSH
2--> POP
3--> DISPLAY
4--> EXIT
Enter your choice 3 Stack is empty
Do you want to continue(Type 0 or 1)? 1

1--> PUSH
2--> POP
3--> DISPLAY
4--> EXIT
Enter your choice 1
Enter the element to be pushed 50
Do you want to continue(Type 0 or 1)? 1
1--> PUSH
2--> POP
3--> DISPLAY
4--> EXIT
Enter your choice 1
Enter the element to be pushed 60
Do you want to continue(Type 0 or 1)? 1
1--> PUSH
2--> POP
3--> DISPLAY
4--> EXIT
Enter your choice 3
The status of the stack is 60
50

Do you want to continue(Type 0 or 1)? 1


1--> PUSH
2--> POP
3--> DISPLAY
4--> EXIT
Enter your choice 4

RESULT
Thus the C program for stack ADT using array was implemented and
executed successfully.

27
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

ARRAY IMPLEMENTATION OF QUEUE ADT

AIM
To write a C program to implement Queue ADT using array.

ALGORITHM
Step 1: Start the program.
Step 2: For queue insertion operation, check for queue overflow.
Step 3: If Rear>=N then print queue overflow
else increment rear pointer and insert the element.
Step 4: For queue deletion operation, check for underflow of the queue.
Step 5: If Front=0 then print queue underflow
else delete the element and increment the front pointer.
Step 6: Stop the program.
PROGRAM
#include <stdio.h> #define
MAX 50
int queue_array[MAX]; int rear
= - 1;
int front = - 1;
main()
{
int choice; while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice); switch
(choice)
{
case 1: insert();
break; case 2:
delet();
break; case 3:
display();
break; case 4:
exit(1); 28
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

default: printf("Wrong choice \n");


}
}
}
insert()
{
int add_item;

if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
front = 0;

printf("Inset the element in queue : ");


scanf("%d", &add_item);
rear = rear + 1; queue_array[rear] =
add_item;
}
}

delet()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n"); return
;
}
else
{
printf("Element deleted from queue is : %d\n",
queue_array[front]); front = front + 1;
}
}

display()
{
int i;

if (front == - 1)
29
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

printf("Queue is empty \n"); else


{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
}

OUTPUT
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 10

1.Insert element to queue


2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 15

1.Insert element to queue


2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 20

1.Insert element to queue


2.Delete element from queue
3.Display all elements of queue
4.Quit
30
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

Enter your choice : 2


Element deleted from queue is : 10

1.Insert element to queue


2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 3
Queue is :
15 20
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 4

RESULT
Thus the C program for Queue ADT using array was implemented and executed
successfully.

31
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

ARRAY IMPLEMENTATION OF CIRCULAR QUEUE ADT

AIM
To write a C program to implement Circular Queue ADT.

ALGORITHM
Step 1: Start the program.
Step 2: Define max as 6.
Step 3: Initialize both front and rear as -1.
Step 4: Get your choice.
Step 5: If choice is 1, Perform Enqueue operation as follows:
Step 5.1: If queue is empty, then increment both rear and front by 1
and assign element to queue[rear].
Step 5.2: If queue is full, then display queue if overflow.
Step 5.3: Otherwise, do the following:
• rear = (rear + 1) % max.
• queue[rear] = element.
Step 6: If choice is 2, Perform Dequeue operation as follows:
Step 6.1: If queue is empty, then display queue is underflow.
Step 6.2: If front == rear, then initialize both front and rear as -1.
Step 6.3: Otherwise assign front = (front + 1) % max and display deleted element.
Step 7: If choice is 3, display the elements of queue.
Step 8: Stop the program.

PROGRAM
#include <stdio.h> # define
max 6
int queue[max];
int front = -1; int rear =
-1;

int main()
{
int choice = 1, x;

while(choice < 4 && choice != 0)


{
printf(“\n Press 1: Insert an element - Enqueue”);
printf(“\n Press 2: Delete an element - Dequeue”);
32
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

printf(“\n Press 3: Display”);


printf(“\n Enter your choice: ”); scanf(“%d”,
&choice);
printf(“Enter the element which is to be inserted\n”); scanf(“%d”,
&x);
enqueue(x); break;

dequeue(); break;

display();
return 0;
}

void enqueue(int element)


{
if(front == -1 && rear == -1)
{
front = 0;
rear = 0;
queue[rear] = element;
}

else if((rear + 1) % max == front)


{
printf(“Queue is overflow\n”);
}

else
{
rear = (rear + 1) % max;
queue[rear] = element;
}
}

int dequeue()
{
if((front == -1) && (rear == -1))
{
printf(“\n Queue is underflow\n”);
33
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

}
else if(front == rear)
{
printf(“\nThe dequeued element is %d”, queue[front]);
front = -1;
rear = -1;
}
else
{
printf(“\nThe dequeued element is %d”, queue[front]);
front = (front + 1) % max;
}
}

void display()
{
int i = front;

if(front == -1 && rear == -1)


{
printf(“\n Queue is empty”);
}

else
{
printf(“\n Elements in a Queue are \n”);

while(i <= rear)


{
printf(“%d\n”, queue[i]); i = (i +
1) % max;
}
}
}

OUTPUT
Press 1: Insert an element - Enqueue
Press 2: Delete an element -Dequeue
Press 3: Display
Enter your choice: 1 34
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

Enter the element which is to be inserted 10


Press 1: Insert an element - Enqueue
Press 2: Delete an element -Dequeue
Press 3: Display
Enter your choice: 1
Enter the element which is to be inserted 20
Press 1: Insert an element - Enqueue
Press 2: Delete an element -Dequeue
Press 3: Display
Enter your choice: 1
Enter the element which is to be inserted 30
Press 1: Insert an element - Enqueue
Press 2: Delete an element -Dequeue
Press 3: Display
Enter your choice: 2
The dequeued element is 10

Press 1: Insert an element - Enqueue


Press 2: Delete an element -Dequeue
Press 3: Display
Enter your choice: 3 Elements
in a Queue are 20
30

Press 1: Insert an element - Enqueue


Press 2: Delete an element -Dequeue
Press 3: Display
Enter your choice: 4

RESULT
Thus the C program for Circular Queue ADT using array was implemented and
executed successfully.

35
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

IMPLEMENTATION OF SINGLY LINKED LIST

AIM
To write a C program for singly linked list using list.

ALGORITHM
Step1: Start the program
Step2: Get the values for insertion into the list
Step3: Get the position of the value to be deleted
Step4: Display the values entered into the list
Step5: Display the number of items in the list
Step6: Stop the program

PROGRAM
#include <stdio.h> #include
<malloc.h> #include <stdlib.h>
struct node
{
int value;
struct node *next;
};
void insert(); void
display(); void delet();
int count();
typedef struct node DATA_NODE;
DATA_NODE *head_node, *first_node, *temp_node = 0, *prev_node,
next_node; int data;
int main()
{
int option = 0;
printf("Singly Linked List Example - All Operations\n");

while (option < 5)


{
printf("\nOptions\n");
36
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

printf("1 : Insert into Linked List \n"); printf("2 :


Delete from Linked List \n"); printf("3 : Display
Linked List\n");
printf("4 : Count Linked List\n");
printf("Others : Exit()\n"); printf("Enter
your option:"); scanf("%d", &option);

temp_node -> next = 0; head_node =


temp_node; fflush(stdin);
}
void delet()
{
int countvalue, pos, i = 0; countvalue
= count(); temp_node = first_node;

printf("\nEnter Position to Delete element : \n");


scanf("%d", &pos);

if (pos > 0 && pos <= countvalue)


{

if (pos == 1)
{
temp_node = temp_node -> next;
first_node = temp_node; printf("\nDeleted
Successfully \n\n");
}
else
{
while (temp_node != 0)
{
if (i == (pos - 1))
{
prev_node->next = temp_node->next;

if(i == (countvalue - 1))


{
head_node = prev_node;
}
printf("\nDeleted Successfully \n\n");
break;
37
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

}
else
{
i++;
prev_node = temp_node; temp_node =
temp_node -> next;
}
}
}
}

else
printf("\nInvalid Position \n\n");
}
void display()
{
int count = 0; temp_node =
first_node;
printf("\nDisplay Linked List : \n");
while (temp_node != 0)
{
printf("# %d # ", temp_node->value);
count++;
temp_node = temp_node -> next;
}
printf("\nNo. of Items in Linked List : %d\n", count);
}

int count()
{
int count = 0; temp_node =
first_node; while (temp_node !=
0)
{
count++;
temp_node = temp_node -> next;
}
printf("\nNo. of Items in Linked List : %d\n", count);
return count;
}

38
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

OUTPUT
Options
1: Insert into linked list
2: Delete from Linked List
3 : Display Linked List
4 : Count Linked List Others
5 : Exit()
Enter your option:1

Enter Element to Insert in Linked List : 100

Options

1: Insert into linked list


2: Delete from Linked List
3 : Display Linked List
4 : Count Linked List Others
5 : Exit()
Enter your option:1
Enter Element to Insert in Linked List : 200
Options
1: Insert into linked list
2: Delete from Linked List
3 : Display Linked List
4 : Count Linked List Others
5 : Exit()
Enter your option:1
Enter Element to Insert in Linked List : 300
Options
1: Insert into linked list
2: Delete from Linked List
3 : Display Linked List
4 : Count Linked List Others
5 : Exit()
Enter your option:1

Enter Element to Insert in Linked List : 400


39
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

Options
Options
1: Insert into linked list
2: Delete from Linked List
3 : Display Linked List
4 : Count Linked List Others
5 : Exit()
Enter your option:1
Enter Element to Insert in Linked List : 500
Options
1: Insert into linked list
2: Delete from Linked List
3 : Display Linked List
4 : Count Linked List Others
5 : Exit()
Enter your option:3

Display Linked List :


# 100 # # 200 # # 300 # # 400 # # 500 #
No. of Items in Linked List : 5

Options
Options
1: Insert into linked list
2: Delete from Linked List
3 : Display Linked List
4 : Count Linked List Others
5 : Exit()
Enter your option:4
No. of Items in Linked List : 5
Options
1: Insert into linked list
2: Delete from Linked List
3 : Display Linked List
4 : Count Linked List Others
5 : Exit()
Enter your option:2
40
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

No. of Items in Linked List : 5

Enter Position to Delete element : 3 Deleted Successfully

Options

1: Insert into linked list


2: Delete from Linked List
3 : Display Linked List
4 : Count Linked List Others
5 : Exit()
Enter your option:3

Display Linked List :


# 100 # # 200 # # 400 # # 500 #
No. of Items in Linked List : 4
Options
1: Insert into linked list
2: Delete from Linked List
3 : Display Linked List
4 : Count Linked List Others
5 : Exit()
Enter your option:2
No. of Items in Linked List : 4

Enter Position to Delete element : 6 Invalid Position

Options

1: Insert into linked list


2: Delete from Linked List
3 : Display Linked List
4 : Count Linked List Others
5 : Exit()
Enter your option: 5

RESULT
Thus the C program for singly linked list using list was implemented and executed
successfully.

41
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

LINKED LIST IMPLEMENTATION OF STACK ADT

AIM
To write a c program to implement stack using linked list.

ALGORITHM
Step 1: Start the program.
Step 2: For Push operation, check for stack overflow
Step 3: If Top>=N then print stack overflow else increment Top and insert the
element. Step 4: For Pop operation, check for underflow of the stack.
Step 5: If Top=0 then print stack underflow else decrement Top and delete the
element. Step 6: Stop the program.

PROGRAM
#include <stdio.h> #include
<stdlib.h>
struct Node
{
int Data;
struct Node *next;
}*top;
int main()
{
int i = 0;
top = NULL; clrscr();
printf(" \n1. Push to stack"); printf("
\n2. Pop from Stack");
printf(" \n3. Display data of Stack");
printf(" \n4. Exit\n");

while(1)
{
printf(" \nChoose Option: ");
scanf("%d",&i);

popStack();
printf("\n The element is popped"); break;

display(); break; 42
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

struct Node *temp; while(top!=NULL)


{
temp = top->next; free(top);
top = temp;
}
exit(0); default:
printf("\nwrong choice for operation");
}
}
}
void push(int value){
struct Node *temp;
temp = (struct Node *)malloc(sizeof(struct Node));
temp->Data = value;
if (top == NULL)
{
top = temp;
top->next = NULL;
}
else
{
temp->next = top; top =
temp;
}
}
void popStack(){
struct Node *temp, *var = top; if(var ==
top)
{
top = top->next; free(var);
}else

}
printf("\nStack Empty");
void display(){
struct Node *var = top; if(var !=
NULL){
printf("\nElements are as:\n");
while(var != NULL)
{
43
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

printf("\t%d\n",var->Data); var =
var->next;
}
printf("\n");
}
else
printf("\nStack is Empty");
}

OUTPUT

1. Push to stack
2. Pop from Stack
3. Display data of Stack
4. Exit
Choose Option:1
Enter a value to push into Stack 5
Choose Option:1
Enter a value to push into Stack 3
Choose Option:1
Enter a value to push into Stack 2
Choose Option:1
Enter a value to push into Stack 9
Choose Option:3
Elements are as : 5
3
2
9
Choose Option:2
The element is popped Choose Option:3 Elements are as :
5
3
2

RESULT
Thus the C program for implementation of stack using linked list was done and
executed successfully.

44
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

LINKED LIST IMPLEMENTATION OF LINEAR QUEUE ADT

AIM
To write a C program to implement queue using linked list.

ALGORITHM
Step 1: Start the program.
Step 2: For queue insertion operation, check for queue overflow
Step 3: If R>=N then print queue overflow else increment rear pointer and insert the
element. Step 4: For queue deletion operation, check for underflow of the queue.
Step 5: If F=0 then print queue underflow else delete the element and increment the front
pointer Step 6: Stop the program.

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

struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;

int frontelement(); void


enq(int data); void deq();
void empty(); void
display(); void create();
void queuesize(); int
count = 0;

void main()
{
int no, ch, e;

printf("\n 1 - Enqueue");
printf("\n 2 - Dequeue");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
45
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

printf("\n 6 - Display");
printf("\n 7 - Queue size");
create();

while(1)
{
printf("\n Enter choice : "); scanf("%d",
&ch);
else break;
printf("\n No front element in Queue as queue is empty");
void queuesize(){
printf("\n Queue size : %d", count);
}
void enq(int data){
if (rear == NULL)
{
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
rear->info = data; front =
rear;
}
else
{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data; temp-
>ptr = NULL; rear = temp;
}
count++;
}
void display(){
front1 = front;

if ((front1 == NULL) && (rear == NULL))


{
printf("Queue is empty"); return;
}
while (front1 != rear)
{
printf("%d ", front1->info); front1 =
front1->ptr;
46
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

}
if (front1 == rear) printf("%d",
front1->info);
}
void deq(){
front1 = front;
if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else if (front1->ptr != NULL)
{
front1 = front1->ptr;
printf("\n Dequeued value : %d", front->info); free(front);
front = front1;
}
else
{
printf("\n Dequed value : %d", front->info);
free(front);
front = NULL; rear =
NULL;
}
count--;
}
int frontelement()
{
if ((front != NULL) && (rear != NULL))
return(front->info);
else
}return 0;
void empty(){
if ((front == NULL) && (rear == NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}

47
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

OUTPUT

1- Enqueue
2- Dequeue
3- Front element
4- Empty
5- Exit
6- Display
7- Queue size

Enter choice : 1
Enter data : 14
Enter choice : 1
Enter data : 85
Enter choice : 1
Enter data : 38
Enter choice : 3
Front element : 14
Enter choice : 6
14 85 38
Enter choice : 7
Queue size : 3
Enter choice : 2
Dequeued value : 14
Enter choice : 6
85 38
Enter choice : 7
Queue size : 2
Enter choice : 4
Queue not empty
Enter choice : 5

RESULT
Thus the C program for queue using linked list was implemented and executed
successfully.

48
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

IMPLEMENTATION OF POLYNOMIAL MANIPULATION USING LINKED


LIST

AIM
To write a C program to perform polynomial manipulation using linked list.

ALGORITHM
Step 1: Start the program.
Step 2: Define structure with three fields coef, expo, and link.
Step 3: Create two polynomials.
Step 4: Add two polynomials. Step 5:
Multiply two polynomials. Step 6:
Display polynomials.
Step 7: Stop the program.

PROGRAM

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

struct node
{
float coef; int expo;
struct node *link;
};

struct node *create(struct node *);


struct node *insert_s(struct node *,float,int); struct node *insert(struct node *,float,int);
void display(struct node *ptr);
void poly_add(struct node *,struct node *);
void poly_mult(struct node *,struct node *);

void main( )
{
struct node *start1 = NULL,*start2 = NULL;

printf("Enter polynomial 1 :\n"); start1 = create(start1);

printf("Enter polynomial 2 :\n"); start2 = create(start2);


printf("Polynomial 1 is : "); display(start1);
printf("Polynomial 2 is : "); display(start2);
49
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

poly_add(start1, start2); poly_mult(start1, start2);


}

struct node *create(struct node *start)


{
int i,n,ex; float co;
printf("Enter the number of terms : ");
scanf("%d",&n);
for(i = 1; I <= n; i++)
{
printf("Enter coeficient for term %d : ",i);
scanf("%f",&co);
printf("Enter exponent for term %d : ",i);
scanf("%d",&ex);
start = insert_s(start,co,ex);
}
return start;
}

struct node *insert_s(struct node *start, float co,int ex)


{
struct node *ptr,*tmp;
tmp = (struct node *)malloc(sizeof(struct node)); tmp->coef = co;
tmp->expo = ex;

if(start == NULL || ex > start->expo)


{
struct node *insert(struct node *start, float co,int ex)
{
struct node *ptr,*tmp;
tmp = (struct node *) malloc(sizeof(struct node));
tmp->coef = co;
tmp->expo = ex;
if(start == NULL)
{
}
else
{
tmp->link = start; start = tmp;
ptr = start;

while(ptr->link != NULL) ptr = ptr->link;


50
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

tmp->link = ptr->link; ptr->link = tmp;

return start;
}
void display(struct node *ptr)
{
if(ptr == NULL)
{
printf("Zero polynomial\n"); return;
}

while(ptr != NULL)
{
printf("(%.1fx^%d)", ptr->coef, ptr->expo); ptr = ptr->link;

if(ptr != NULL)
printf(" + ");
else
printf("\n");
}
}

void poly_add(struct node *p1, struct node *p2)


{
struct node *start3; start3 = NULL;

while(p1 != NULL && p2 != NULL)


{
if(p1->expo > p2->expo)
{
start3 = insert(start3, p1->coef, p1->expo); p1 = p1->link;
}

else if(p2->expo > p1->expo)


{
start3 = insert(start3, p2->coef, p2->expo); p2 = p2->link;
}

else if(p1->expo == p2->expo)


{
start3 = insert(start3, p1->coef+p2->coef, p1->expo); p1 = p1->link;
51
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

p2 = p2->link;
}
}

while(p1 != NULL)
{
start3 = insert(start3, p1->coef, p1->expo); p1 = p1->link;
}

while(p2 != NULL)
{
start3 = insert(start3, p2->coef, p2->expo); p2 = p2->link;
}

printf("Added polynomial is : "); display(start3);


}
void poly_mult(struct node *p1, struct node *p2)
{
struct node *start3;
struct node *p2_beg = p2; start3=NULL;

if(p1==NULL || p2==NULL)
{
printf("Multiplied polynomial is zero polynomial\n"); return;
}

while(p1!=NULL)
{
p2 = p2_beg;

while(p2 != NULL)
{
start3 = insert_s(start3, p1->coef*p2->coef, p1->expo+p2->expo); p2 = p2->link;
}
p1 = p1->link;
}
printf("Multiplied polynomial is : "); display(start3);
}

52
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

OUTPUT

Enter polynomial 1 :
Enter the number of terms : 2
Enter coefficient for term 1 : 2
Enter exponent for term 1 : 2
Enter coefficient for term 2 : 3
Enter exponent for term 2 : 4

Enter polynomial 2 :
Enter the number of terms : 5
Enter coefficient for term 1 : 4
Enter exponent for term 1 : 3
Enter coefficient for term 2 : 2
Enter exponent for term 2 : 1
Enter coefficient for term 3 : 2
Enter exponent for term 3 : 3
Enter coefficient for term 4 : 4
Enter exponent for term 4 : 5
Enter coefficient for term 5 : 6
Enter exponent for term 5 : 3

Polynomial 1 is : (3.0x^4) + (2.0x^2)


Polynomial 2 is : (4.0x^5) + (4.0x^3) + (2.0x^3) + (6.0x^3) + (2.0x^1)

Added polynomial is : (4.0x^5) + (3.0x^4) + (4.0x^3) + (2.0x^3) + (6.0x^3) + (2.0x^2) +


(2.0x^1)

Multiplied polynomial is : (12.0x^9) + (12.0x^7) + (6.0x^7) + (18.0x^7) + (8.0x^7) +


(6.0x^5) + (8.0x^5) + (4.0x^5) + (12.0x^5) + (4.0x^3)

RESULT
Thus the C program for the implementation of Polynomial Manipulation using Linked
List was done and executed successfully.

53
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

IMPLEMENTATION OF EVALUATING POSTFIX EXPRESSIONS

AIM
To write a C program to perform evaluation of postfix expressions.

ALGORITHM
Step 1: Start the program.
Step 2: Read postfix expression.
Step 3: If input is a digit, push into stack.
Step 4: If input is an operator, then do the following:
Step 4.1: Pop top two elements from the stack.
Step 4.2: Perform respective operation between two popped elements and Push the
result into the stack.
Step 5: Repeat step 3 and 4 until the end of expression.
Step 6: Print value of evaluated expression.
Step 7: Stop the program.

PROGRAM
#include<stdio.h>

int stack[20];

int top = -1;


void push(int x){
stack[++top] = x;
}
int pop(){
return stack[top--];
}
int main(){
char exp[20]; char *e;
int n1,n2,n3,num;

printf("Enter the expression :: ");


scanf("%s",exp);
e = exp;
while(*e != '\0'){ 54
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

if(isdigit(*e)){
num = *e - 48;
push(num);
}
else
{
n1 = pop();
n2 = pop();
switch(*e){
case '+':
n3 = n1 + n2;
break;
case '-':
n3 = n2 - n1;
break;
case '*':
n3 = n1 * n2;
break;
case '/':
n3 = n2 / n1;
break;
}

push(n3);
}
e++;
}
printf("\nThe result of expression %s = %d\n\n",exp,pop());
return 0;
}

OUTPUT

Enter the expression : 245+*

The result of expression 245+* = 18

RESULT
Thus the C program for evaluating postfix expressions was implemented and
executed successfully.

55
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

IMPLEMENTATION OF INFIX TO POSTFIX CONVERSION

AIM

To write a C program to convert the infix expression into postfix expression using
stack.

ALGORITHM

Step 1: Start the program.


Step 2: Get the infix expression as input.
Step 3: Read the input from left to right.
Step 4: If the input is operand then place it in the postfix expression.
Step 5: Else if the input symbol is an operator then check for the operator type and
also the precedence, pop entries from the stack and place them in the postfix
expression until the lowest priority operator is encountered.
Step 6: “(” symbol will be popped from stack only when we get a “)” symbol.
Step 7: When the input is completely read then pop the elements in stack until it becomes
empty. Step 8: Display the postfix expression.
Step 9: Stop the program.

PROGRAM

#include<stdio.h> char
stack[20]; int top = -1;

void push(char x)
{
stack[++top] = x;
}

char pop()
{
if(top == -1)
return -1; else
return stack[top--];
}

int priority(char x)
{
56
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

if(x == '(') return 0;


if(x == '+' || x == '-') return 1;
if(x == '*' || x == '/') return
2;
}
main(){
char exp[20]; char *e, x; printf("Enter
the expression :: "); scanf("%s",exp);
e = exp; while(*e != '\0'){
if(isalnum(*e))
printf("%c",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(') printf("%c", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c",pop());
push(*e);
} e++;
}

while(top != -1)
{
printf("%c",pop());
}
}

OUTPUT

Enter the expression :: a+b*c abc*+


Enter the expression :: (a+b)*c+(d-a) ab+c*da-+

RESULT
Thus the C program to convert the infix expression into postfix expression using
stack has been implemented successfully.

57
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

IMPLEMENTATION OF BINARY SEARCH TREES

AIM

To write a C program to construct a binary search tree and perform various operations.

ALGORITHM

ALGORITHM for INSERT(X,P)


1. if(P==NULL)
t=(struct treenode *)malloc(sizeof(struct treenode));
2. else
t->element=x;
t- >left=t->right=NULL;
3. else if(x<t->element)
t->left=insert(x,t->left);
4. else if(x>t->element)
t->right=insert(x,t->right); return t;

ALGORITHM For INORDER(P)


1. If(P!=Null)
2. CALL INORDER (P→lchild)
3. WRITE (P→data)
4. CALL INORDER (P→rchild)
5. [End the function]

ALGORITHM for PREORDER(P)


1. If (P! =NULL)
2. WRITE (P->Data)
3. CALL PREORDER (P→lchild)
4. CALL PREORDER (P→ rchild)
5. [END OF FUNTION]

ALGORITHM for POSTORDER(P)


1. If (P!=NULL)
2. Call POSTORDER (P→lchild)
3. Call POSTORDER (P→rchild)
4. Write (P→data)
5. [End of function]
58
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

ALGORITHM for COUNT


1. If (P==NULL)
2. Return 0
3. Else
4. Return (1+count(P→lchild)+call count(P→rchild))

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

#define NULL 0 struct


treenode
{
int element;
struct treenode *left; struct
treenode *right;
};
typedef struct treenode *position, *searchtree;
searchtree insert(int x, searchtree t)
{
if(t == NULL)
{
t = (struct treenode *)malloc(sizeof(struct treenode)); if(t
== NULL)
exit(0); else
{
t->element = x;
t->left = t->right = NULL;
}
}
else if(x < t->element)
t->left = insert(x, t->left); else
if(x > t->element)
t->right = insert(x, t->right);
return t;
}
position findmin(searchtree t)
{
if(t == NULL)
return NULL; else
59
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

return findmin(t->left);
}
position findmax(searchtree t)
{
if(t == NULL)
return NULL;
else if(t->right == NULL) return
t;
else
return findmax(t->right);
}

searchtree rem(int x, searchtree t)


{
position temp; if(t ==
NULL)
printf("\n Element not found\t"); else
if(x < t->element)
t->left = rem(x, t->left); else if(x
> t->element)
t->right = rem(x, t->right); else
if(t->left && t->right)
{
temp = findmin(t->right);
t->element = temp->element;
t->right = rem(t->element, t->right);
}
else
{
temp = t;
if(t->left == NULL) t = t-
>right;
else if(t->right == NULL)
t = t->left;
free(temp);
}
return t;
}
void intrav(searchtree head)
{
if(head == NULL) return;
60
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

if(head->left != NULL)
intrav(head->left);
printf("%d\t", head->element);
if(head->right != NULL)
intrav(head->right);
}
void main()
{
int n,i,dat,ch; searchtree t =
NULL; position node;
printf("\nElement no. of elements:\t");
scanf("%d",&n);
printf("\nEnter the elements:\t");
for(i=1; i<=n; i++)
{
scanf("%d",&dat); t =
insert(dat,t);
}
intrav(t); do
{
printf("\n****MENU****\n");
printf("1->Insert a node \n");
printf("2->Delete a node \n");
printf("3->Find Minimum\n");
printf("4->Find Maximum\n");
printf("5->Display (Inorder Traversal)\n");
printf("6->Exit\n");
printf("Enter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\n Enter the element to be inserted:\t");
scanf("%d",&dat);
t=insert(dat,t); break;
case 2: printf("\n Enter the node to be deleted:\t");
scanf("%d",&dat);
t=rem(dat,t); break;
case 3: node=findmin(t);
printf("\nThe minimum element is %d",node->element);
break;
case 4: node=findmax(t);
printf("\n The maximum element is %d",node->element); break;
61
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

case 5: intrav(t); break;


case 6: exit(0);
}
}
while(ch!=6);
}

OUTPUT
Enter no. of elements: 3 Enter
the elements:
5
2
9
259
****MENU****
1->Insert a node
2->Delete a node
3->Find Minimum
4->Find Maximum
5->Display (Inorder Traversal)
6->Exit
Enter your choice:1
Enter the element to be inserted: 4
****MENU****
1->Insert a node
2->Delete a node
3->Find Minimum
4->Find Maximum
5->Display (Inorder Traversal)
6->Exit
Enter your choice:1
Enter the element to be inserted:6
62
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

****MENU****
1->Insert a node
2->Delete a node
3->Find Minimum
4->Find Maximum
5->Display (Inorder Traversal)
6->Exit
Enter your choice:2
Enter the element to be deleted:5
****MENU****
1->Insert a node
2->Delete a node
3->Find Minimum
4->Find Maximum
5->Display (Inorder Traversal)
6->Exit
Enter your choice: 5
2 4 6 9
****MENU****
1->Insert a node
2->Delete a node
3->Find Minimum
4->Find Maximum
5->Display (Inorder Traversal)
6->Exit
Enter your choice:3
The minimum element is: 2

63
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

****MENU****
1->Insert a node
2->Delete a node
3->Find Minimum
4->Find Maximum
5->Display (Inorder Traversal)
6->Exit

Enter your choice:4


The maximum element is:9

****MENU****
1->Insert a node
2->Delete a node
3->Find Minimum
4->Find Maximum
5->Display (Inorder Traversal)
6->Exit

Enter your choice:6

RESULT
Thus the C program to construct a binary search tree and perform various
operations has been executed successfully.

64
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

IMPLEMENTATION OF HEAPS USING PRIORITY QUEUES

AIM

To write a C program for the implementation of heaps using priority queues.

ALGORITHM

Step 1: Start the program


Step 2: Declare the necessary variables
Step 3: Write the functions for Insert, Delete, Display and Exit
Step 4: Do the deletion for the higher order element and display it.
Step5: End the program

PROGRAM

#include<stdio.h>
#include<math.h>
#define MAX 100 void
swap(int*,int*); void main()
{
int choice, num, n, a[MAX], data, s; void
display(int[], int);
void insert(int[], int, int, int); int
del_hi_priori(int[], int, int);

int lb = 0; n = 0;

while(1)
{
printf(".....MAIN MENU \n");
printf("\n1.Insert\n");
printf("2.Delete\n");
printf("3.Display\n");
printf("4.Quit\n");

printf("\nEnter your choice : ");


scanf("%d",&choice);

65
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

switch(choice)
{
case 1:
printf("Enter data to be inserted : ");
scanf("%d",&data); insert(a,n,data,lb);
n++;
break;
case 2:
s=del_hi_priori(a,n+1,lb);
if(s!=0)
printf("\nThe deleted value is : %d \n",s);
case 3:
if(n>0)
n--;
break;
case 4:
printf("\n");
display(a,n); break;
return;
default:
}
printf("Invalid choice \n");
printf("\n\n");
}
}

void insert(int a[], int heapsize, int data, int lb)


{
int i,p;
int parent(int); if(heapsize ==
MAX)
{
printf("Queue Is Full!!\n"); return;
}
i = lb + heapsize; a[i] =
data;

while(i > lb && a[p = parent(i)] < a[i])


{
swap(&a[p], &a[i]); i = p;
66
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

}
}

int del_hi_priori(int a[], int heapsize, int lb)


{
int data,i,l,r,max_child,t; int
left(int);
int right(int);

if(heapsize == 1)
{
printf("Queue is Empty!!\n"); return
0;
}

t = a[lb];
swap(&a[lb], &a[heapsize-1]); i = lb;
heapsize--;

while(1)
{
if((l = left(i)) >= heapsize) break;
if((r = right(i)) >= heapsize)
max_child = l;
else
max_child = (a[l] > a[r]) ? l : r;

if(a[i] >= a[max_child]) break;

swap(&a[i], &a[max_child]); i =
max_child;
}
return t;
}

int parent(int i)
{
float p;
p = ((float) i / 2.0) - 1.0; return
ceil(p);
}
67
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

int left(int i)
{
return 2 * i + 1;
}
int right(int i)
{
return 2 * i + 2;
}

void display(int a[], int n)


{
int i;
if(n == 0){
printf("Queue Is Empty!!\n");
return;
}
for(i = 0; i < n; i++)
printf("%d ",a[i]);
printf("\n");
}

void swap(int*p, int*q)


{
int temp; temp=*p;
*p=*q;
*q=temp;
}

OUTPUT

.....MAIN MENU.....
1. Insert.
2. Delete.
3. Display.
4.Quit.

Enter your choice : 1


Enter data to be inserted : 52
68
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

.....MAIN MENU.....
1. Insert.
2. Delete.
3. Display.
4.Quit.
Enter your choice : 1
Enter data to be inserted : 63

.....MAIN MENU.....
1. Insert.
2. Delete.
3. Display.
4.Quit.

Enter your choice : 1


Enter data to be inserted : 45

.....MAIN MENU.....
1. Insert.
2. Delete.
3. Display.
4.Quit.

Enter your choice : 1


Enter data to be inserted : 2

.....MAIN MENU.....
1. Insert.
2. Delete.
3. Display.
4. Quit.

Enter your choice : 1


Enter data to be inserted : 99
.....MAIN MENU.....
1. Insert.
2. Delete.
3. Display.
4. Quit.
69
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

Enter your choice : 3 99 63


45 2 52

.....MAIN MENU.....
1. Insert.
2. Delete.
3. Display.
4. Quit.

Enter your choice : 2 The


deleted value is : 99

.....MAIN MENU.....
1. Insert.
2. Delete.
3. Display.
4. Quit.

Enter your choice : 3 63 52


45 2

.....MAIN MENU.....
1. Insert.
2. Delete.
3. Display.
4.Quit.
Enter your choice : 4

RESULT
Thus the C program for the implementation of heaps using priority queues has
been executed successfully.

70
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

IMPLEMENTATION OF LINEAR SEARCH

AIM
To write a C program to implement Linear Search.

ALGORITHM
Step 1. Start the program
Step 2. Initialize i,j,,n,a[20],size
Step 3. Read the size of sorting numbers size Step
4. Read the elements of the array
Step 5. Read the element to be searched n
Step 6. Using for(i=0;i<size;i++), If it is true then
Step 6.1. Check the condition, if(n==array[i]) if it is true go to next
step, else go to step 6.
Step 6.2. Display the element is found & terminate the for loop
Step 7. if i==size, then display element is not found
Step 8. Stop the program

PROGRAM
#include <stdio.h> int
main()
{
int a[20], i, j, n, size;

printf("Linear Search\n");

printf("Enter the size of the list:");


scanf("%d", &size);
printf("Enter %d Integers \n", size); for (i
= 0; i < size; i++)
scanf("%d", &a[i]);

printf("Enter value to find\n");


scanf("%d", &n);

linear_search(a, size, n);

return 0; 71
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

}
void linear_search(int array[], int size, int n)
{
int i;

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


{
if (array[i] == n)
{
printf("%d found at location %d.\n", n, i+1);
break;
}
}

if (i == size)
printf("Not found! %d is not present in the list.\n", n);
}

OUTPUT

Linear Search

Enter the size of the list:10

Enter 10 Integers 12 5 8 22 16 25 11 45 78 55

Enter value to find 16

16 found at location 5.

RESULT
Thus the C program to perform linear search has been implemented and executed
successfully.

72
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

IMPLEMENTATION OF BINARY SEARCH

AIM
To write a C program to implement Binary Search.

ALGORITHM
Step 1. Start the program
Step 2. Initialize i,j,,n,a[20],size
Step 3. Read the size of sorting numbers size
Step 4. Read the elements of the array in ascending order
Step 5. Read the element to be searched n
Step 6. Initialize first =0, last = size-1
Step 7. Calculate middle as (first+last) / 2
Step 8. If first <= last, then do the following:
Step 8.1 If array[middle] == n then display element is found & terminate while loop
Step 8.2 If array[middle] > n then last = middle – 1 and repeat step 8
Step 8.3 If array[middle] < n then first = middle + 1 and repeat step 8
Step 8.4 Update middle as (first + last) / 2
Step 9: If first > last, then display element is not found
Step 10. Stop the program
PROGRAM
#include <stdio.h> int
main(){
int a[20], i, j, n, size;

printf("Binary Search\n");

printf("Enter the size of the list:");


scanf("%d", &size);
printf("Enter %d Integers in ascending order\n", size);
for (i = 0; i < size; i++)
scanf("%d", &a[i]);
printf("Enter value to find\n");
scanf("%d", &n);
binary_search(a, size, n); return
0;
}
73
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

void binary_search(int array[], int size, int n)


{
int i, first, last, middle;

first = 0;
last = size - 1;
middle = (first+last) / 2;
while (first <= last)
{
if (array[middle] < n) first =
middle + 1;
else if (array[middle] == n)
{
printf("%d found at location %d.\n", n, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last) / 2;
}
if ( first > last )
printf("Not found! %d is not present in the list.\n", n);
}

OUTPUT

Binary Search

Enter the size of the list:10

Enter 10 Integers 2 5 8 12 16 25 31 45 48 55

Enter value to find 16

16 found at location 5.

RESULT
Thus the C program to perform binary search has been implemented and executed
successfully.
74
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

IMPLEMENTATION OF INSERTION SORT

AIM

To write a C program for sorting an array of N numbers using Insertion Sort.

ALGORITHM

Step 1. Start the program


Step 2. Initialize arr[max],i,j,tmp,n,p
Step 3. Read the number of elements from the user
Step 4. Read the elements
Step 5. Display the unsorted elements to the user
Step 6. Invoke function call insertionsort(arr,n)
Step 6.1 In function block, using for loop, for(p=1;p<n;p++)
Step 6.2 Initialize tmp=a[p]
Step 6.3 for(j=p; j>0 && a[j-1] > tmp; j--), if it is true go to next step, else go to step
6.5 Step 6.4 Assign a[j]=a[j-1]
Step 6.5 Assign a[j]=tmp
Step 7. Display sorted list to the user
Step 8. Stop the program

PROGRAM
#include<stdio.h>
void insertionsort(int[], int);

#define max 20

void main(){
int arr[max],i,j,tmp,n,p;

printf(“\n enter the size of the sorting”);


scanf(“%d”,&n);

for(i=0;i<n;i++)
{
printf(“\n Enter element %d”, i+1);
scanf(“%d”,&arr[i]);
}
75
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

printf(“unsorted list are:”);


for(i = 0;i < n; i++)
printf(“%d \t”, arr[i]); insertionsort(arr, n);

printf(“sorted list:”);
for( i = 0; i < n; i++)
printf(“%d\t”, arr[i]);
}
void insertionsort(int a[], int n){
int p,j,tmp;

for( p = 1; p < n; p++)


{
tmp = a[p];

for( j = p; j > 0 && a[ j -1 ] > tmp; j--) a[j]


= a[j-1];
a[j] = tmp;
}
}

OUTPUT
Enter the number of elements: 5 Enter
element 1: 8
Enter element 2: 5
Enter element 3: 1
Enter element 4: 3
Enter element 5: 4

Unsorted list are: 8 5 1 3 4

Sorted list are: 1 3 4 5 8

RESULT
Thus the C program for sorting an array of N numbers using insertion sort has
been executed successfully.

76
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

IMPLEMENTATION OF SELECTION SORT

AIM
To write a C program for sorting an array of N numbers using Selection Sort.

ALGORITHM
Step 1. Start the program
Step 2. Initialize a[max],i,j,n
Step 3. Read the number of elements from the user
Step 4. Read the elements
Step 5. Display the unsorted elements to the user
Step 6. Invoke function call selectionsort(a,n)
Step 6.1 In function block, using for loop for(i=0;i<n-1;i++)
Step 6.2 index=i;
Step 6.3 using for loop, for(j=i+1;j<n;j++)
Step 6.4 if(a[j]<a[index]), if it is true go to next step else go to step 6.6.
Step 6.5 index=j;
Step 6.6 Swap smallno=a[index]; a[index]=a[i]; a[i]=smallno;
Step 7. Display sorted list to the user
Step 8. Stop the program
PROGRAM
#include<stdio.h>
void selectionsort(int[], int);

#define max 20

void main(){
int a[max],i,j,n;
printf(“\n enter the size of the sorting”);
scanf(“%d”, &n);
for( i = 0; i < n; i++)
{
printf(“\n Enter element %d”, i+1);
scanf(“%d”, &a[i]);
}
printf(“unsorted list are:”);
77
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

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


printf(“%d \t”, a[i]);

selectionsort(a,n);

printf(“sorted list: ”);

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


printf(“%d\t”, a[i]);
}
void selectionsort(int a[], int n){
int i,j,index,smallno;

for(i = 0; i < n-1; i++)


{
index=i;

for( j = i + 1; j < n; j++) if(a[j]


< a[index])
index = j;
smallno = a[index]; a[index]
= a[i];
a[i] = smallno;
}
}

OUTPUT

Enter the number of elements: 5 Enter


element 1: 8
Enter element 2: 5
Enter element 3: 1
Enter element 4: 3
Enter element 5: 4
Unsorted list are: 8 5 1 3 4
Sorted list are: 1 3 4 5 8

RESULT
Thus the C program for sorting an array of N numbers using selection sort has
been executed successfully.
78
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

IMPLEMENTATION OF MERGE SORT

AIM
To write a C program for sorting an array of N numbers using Merge Sort.

ALGORITHM

Step 1. Read number of elements n to sort


Step 2. Read n number of elements
Step 3. Calculate mid = (i + j) / 2
Step 4. merge_sort(i, mid, a, aux)
Step 5. merge_sort(mid + 1, j, a, aux)
Step 6. pointer_left = i, pointer_right = mid + 1
Step 7. for k in [i ... j]
if pointer_left points to smaller element,
aux[k] = a[pointer_left] and increment
pointer_left by 1
if pointer_right points to smaller element,
aux[k] = a[pointer_right] and increment
pointer_right by 1
copy the contents of aux[i .. j] to a[i .. j]
Step 8. Print sorted numbers

PROGRAM

#include <stdio.h>

int merge_sort(int i, int j, int a[], int aux[])


{
if (j <= i)
{
return 0;
}

int mid = (i + j) / 2;

merge_sort(i, mid, a, aux);


merge_sort(mid + 1, j, a, aux);

int pointer_left = i;
79
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

int pointer_right = mid + 1; int k;


for (k = i; k <= j; k++)
{
if (pointer_left == mid + 1)
{
aux[k] = a[pointer_right];
pointer_right++;
}
else if (pointer_right == j + 1)
{
aux[k] = a[pointer_left];
pointer_left++;
}
else if (a[pointer_left] < a[pointer_right])
{
aux[k] = a[pointer_left];
pointer_left++;
}
else
{
aux[k] = a[pointer_right];
pointer_right++;
}
}
for (k = i; k <= j; k++)
{
a[k] = aux[k];
}
}

int main()
{
int a[100], aux[100], n, i, d, swap;
printf("Enter number of elements in the array:\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);

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


scanf("%d", &a[i]);

merge_sort(0, n - 1, a, aux);
80
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

printf("Printing the sorted array:\n"); for


(i = 0; i < n; i++)
printf("%d\n", a[i]); return
0;
}
OUTPUT

Enter number of elements in the array: 5

Enter 5 integers

12

456

67

Printing the sorted array: 4

12

67

456

RESULT
Thus the C program for sorting an array of N numbers using Merge Sort has been
executed successfully.

81
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

IMPLEMENTATION OF OPEN ADDRESSING (LINEAR PROBING)

AIM

To write a C program to implement Open Addressing (Linear Probing).

ALGORITHM

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


Step 2. Take a key and a value to be stored in hash table as input.
Step 3. Corresponding to the key, an index will be generated.
Step 4. Using the generated index, access the data located in that array index.
Step 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.
Step 6. In case the data exists, probe through the subsequent elements (looping back if
necessary) for free space to insert new data item.
Step 7. Display all the elements of hash table, element at each index is accessed.
Step 8. Remove a key from hash table is done as follows, 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).

PROGRAM

#include <stdio.h>

int tsize;

int hasht(int key)


{
int i ;
i = key%tsize ; return i;
}

//-------LINEAR PROBING-------
int rehashl(int key)
{
int i ;
82
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

i = (key+1)%tsize ; return i
;
}
void main()
{
int key,arr[20],hash[20],i,n,s,op,j,k ;

printf ("Enter the size of the hash table: ");


scanf ("%d",&tsize);
printf ("\nEnter the number of elements: "); scanf
("%d",&n);
for (i=0;i<tsize;i++) hash[i]
= -1 ;
printf ("Enter Elements: "); for
(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}

for (i=0;i<tsize;i++) hash[i]


= -1 ;

for(k=0;k<n;k++)
{
key=arr[k] ;
i = hasht(key); while
(hash[i] != -1)
{
i = rehashl(i);
}
hash[i]=key ;
}

printf("\nThe elements in the array are: "); for


(i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i]);

}
}
83
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

OUTPUT
Enter the size of the hash table: 10
Enter the number of elements: 8
Enter Elements: 72 27 36 24 63 81 92 101

The elements in the array are: Element at


position 0: -1
Element at position 1: 81
Element at position 2: 72
Element at position 3: 63
Element at position 4: 24
Element at position 5: 92
Element at position 6: 36
Element at position 7: 27
Element at position 8: 101
Element at position 9: -1

RESULT
Thus the C program to implement open addressing (Linear Probing) has been
done and executed successfully.

84
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

IMPLEMENTATION OF OPEN ADDRESSING (QUADRATIC PROBING)

AIM

To write a C program to implement Open Addressing (Quadratic Probing).

ALGORITHM

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


Step 2. Take a key and a value to be stored in hash table as input.
Step 3. Corresponding to the key, an index will be generated.
Step 4. Using the generated index, access the data located in that array index.
Step 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.
Step 6. In case the data exists, probe through the subsequent elements using this calculation
(key+(j*j))%tsize to find free space to insert new data item.
Step 7. Display all the elements of hash table, element at each index is accessed.
Step 8. Remove a key from hash table is done as follows, 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).

PROGRAM

#include <stdio.h> int

tsize;

int hasht(int key)


{
int i ;
i = key%tsize ; return i;
}

//-------QUADRATIC PROBING-------
int rehashq(int key, int j)
{
int i ;
i = (key+(j*j))%tsize ; return i
; 85
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

}
void main()
{
int key,arr[20],hash[20],i,n,s,op,j,k ;

printf ("Enter the size of the hash table: ");


scanf ("%d",&tsize);

printf ("\nEnter the number of elements: "); scanf


("%d",&n);

for (i=0;i<tsize;i++) hash[i]


= -1 ;
printf ("Enter Elements: "); for
(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}

for (i=0;i<tsize;i++)
hash[i]=-1 ;

for(k=0;k<n;k++)
{
j=1;
key=arr[k] ;
i = hasht(key); while
(hash[i] != -1)
{
i = rehashq(i,j); j++;
}
hash[i]=key ;
}

printf("\nThe elements in the array are: "); for


(i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i]);
}
86
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

}
OUTPUT
Enter the size of the hash table: 10
Enter the number of elements: 8
Enter Elements: 72 27 36 24 63 81 92 101

The elements in the array are: Element at


position 0: -1
Element at position 1: 81
Element at position 2: 72
Element at position 3: 63
Element at position 4: 24
Element at position 5: 101
Element at position 6: 36
Element at position 7: 27
Element at position 8: 92
Element at position 9: -1

RESULT
Thus the C program to implement open addressing (Quadratic Probing) has been
done and executed successfully.

87
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

IMPLEMENTATION OF DEQUEUE

AIM

To write a C program to implement DeQueue.

ALGORITHM

Insertion at the front end


• If the queue is empty, both rear and front are initialized with 0. Now, both will point
to the first element.
• Otherwise, check the position of the front if the front is less than 1 (front < 1), then
reinitialize it by front = n - 1, i.e., the last index of the array.

Insertion at the rear end


• If the queue is empty, both rear and front are initialized with 0. Now, both will point
to the first element.
• Otherwise, increment the rear by 1. If the rear is at last index (or size - 1), then
instead of increasing it by 1, we have to make it equal to 0.

Deletion at the front end


• If the queue is empty, i.e., front = -1, it is the underflow condition, and we cannot
perform the deletion. If the queue is not full, then the element can be inserted from
the front end by using the below conditions -
• If the deque has only one element, set rear = -1 and front = -1.
• Else if front is at end (that means front = size - 1), set front = 0.
• Else increment the front by 1, (i.e., front = front + 1).

Deletion at the rear end


• If the queue is empty, i.e., front = -1, it is the underflow condition, and we cannot
perform the deletion.
• If the deque has only one element, set rear = -1 and front = -1.
• If rear = 0 (rear is at front), then set rear = n - 1.
• Else, decrement the rear by 1 (or, rear = rear -1).

Check empty
• If front = -1, it means that the deque is empty.

Check full
• If front = rear + 1, or front = 0 and rear = n - 1 it means that the deque is full.
88
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

PROGRAM

#include <stdio.h> #define

size 5

int deque[size]; int f = -1,

r = -1;

void insert_front(int x){


if((f==0 && r==size-1) || (f==r+1))
{
printf("Overflow");
}
else if((f==-1) && (r==-1))
{
f=r=0; deque[f]=x;
}
else if(f==0)
{
f=size-1; deque[f]=x;
}
else
{
f=f-1; deque[f]=x;
}
}
void insert_rear(int x){
if((f==0 && r==size-1) || (f==r+1))
{
printf("Overflow");
}
else if((f==-1) && (r==-1))
{
r=0;
deque[r]=x;
}

89
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

else if(r==size-1)
{
r=0;
deque[r]=x;
}
else
{
r++;
deque[r]=x;
}
}
void display(){
int i=f;
printf("\nElements in a deque are: ");

while(i!=r)
{
printf("%d ",deque[i]);
i=(i+1)%size;
}
printf("%d",deque[r]);
}

void getfront()
{
if((f==-1) && (r==-1))
{
printf("Deque is empty");
}
else
{
printf("\nThe value of the element at front is: %d", deque[f]);
}

void getrear()
{
if((f==-1) && (r==-1))
{
printf("Deque is empty");
90
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

}else{
}
}

printf("\nThe value of the element at rear is %d", deque[r]);

void delete_front()
{
if((f==-1) && (r==-1))
{
printf("Deque is empty");
}
else if(f==r)
{
printf("\nThe deleted element is %d", deque[f]); f=-1;
r=-1;

}
else if(f==(size-1))
{
printf("\nThe deleted element is %d", deque[f]); f=0;
}
else
{
printf("\nThe deleted element is %d", deque[f]); f=f+1;
}
}

void delete_rear()
{
if((f==-1) && (r==-1))
{
printf("Deque is empty");
}
else if(f==r)
{
printf("\nThe deleted element is %d", deque[r]); f=-1;
r=-1;}
else if(r==0)
{
printf("\nThe deleted element is %d", deque[r]);
91
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

r=size-1;
}
else
{
printf("\nThe deleted element is %d", deque[r]);
r=r-1;
}
}

int main()
{
insert_front(20);
insert_front(10);
insert_rear(30);
insert_rear(50);
insert_rear(80); display();
getfront(); getrear();
delete_front();
delete_rear(); display();
return 0;
}

OUTPUT

Elements in a deque are: 10 20 30 50 80 The

value of the element at front is: 10 The value

of the element at rear is 80 The deleted

element is 10

The deleted element is 80 Elements in a

deque are: 20 30 50

RESULT
Thus the C program for implementation of DeQueue was done and executed
successfully.

92
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

IMPLEMENTATION OF THREADED BINARY TREE


AIM

To write a C program to implement Threaded Binary Tree.

ALGORITHM

ALGORITHM Inorder(I)

ThreadedTreeNode *Header;
Header=I;
while(1)

I=fnFindInorder_Successor(H);
if(I==Header)
return; else
print(I->info);

PROGRAM

#include <stdio.h>
#include <stdlib.h>
typedef enum {false,true} boolean;
struct node *in_succ(struct node *p);
struct node *in_pred(struct node *p);
struct node *insert(struct node *root, int ikey);
struct node *del(struct node *root, int dkey);
struct node *case_a(struct node *root, struct node *par,struct node *ptr);
struct node *case_b(struct node *root,struct node *par,struct node *ptr);
struct node *case_c(struct node *root, struct node *par,struct node *ptr);
void inorder( struct node *root);
void preorder( struct node *root);
struct node{
struct node *left; boolean
lthread; int info;
boolean rthread; struct
node *right;
};

93
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

int main( ){
int choice,num;
struct node *root=NULL; while(1)
{
printf("\nProgram of Threaded Tree in C\n");
printf("1.Insert\n");
printf("2.Delete\n"); printf("3.Inorder
Traversal\n"); printf("4.Preorder
Traversal\n"); printf("5.Quit\n");
printf("\nEnter your choice : ");
scanf("%d",&choice); switch(choice)
{
case 1:
printf("\nEnter the number to be inserted : ");
scanf("%d",&num);
root = insert(root,num); break;
case 2:
printf("\nEnter the number to be deleted : ");
scanf("%d",&num);
root = del(root,num); break;
case 3:
inorder(root); break;
case 4:
preorder(root); break;
case 5:
exit(1);

default:
printf("\nWrong choice\n");
}
}
return 0;
}

struct node *insert(struct node *root, int ikey){


struct node *tmp,*par,*ptr; int
found=0;

94
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

ptr = root; par =


NULL;
while( ptr!=NULL ){
if( ikey == ptr->info)
{
found =1; break;
}
par = ptr;
if(ikey < ptr->info){
if(ptr->lthread == false) ptr =
ptr->left;
else
break;
}
else
{
if(ptr->rthread == false) ptr =
ptr->right;
else
break;
}
}
if(found) printf("\nDuplicate key");
else{
tmp=(struct node *)malloc(sizeof(struct node));
tmp->info=ikey;
tmp->lthread = true; tmp-
>rthread = true;
if(par==NULL){
root=tmp;
tmp->left=NULL; tmp-
>right=NULL;
}
else if( ikey < par->info ){
tmp->left=par->left; tmp-
>right=par;
par->lthread=false; par-
>left=tmp;
}else{
tmp->left=par;
tmp->right=par->right; par-
95
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

>rthread=false; par-
>right=tmp;
}
}
return root;
}

struct node *del(struct node *root, int dkey){


struct node *par,*ptr; int
found=0;
ptr = root; par =
NULL;
while( ptr!=NULL)
{
if( dkey == ptr->info){
found =1; break;
}
par = ptr;
if(dkey < ptr->info){
if(ptr->lthread == false) ptr =
ptr->left;
else
break;
}
else{
if(ptr->rthread == false) ptr =
ptr->right;
else
break;
}
}
if(found==0)
printf("\ndkey not present in tree");
else if(ptr->lthread==false && ptr->rthread==false)/*2 children*/
root = case_c(root,par,ptr);
else if(ptr->lthread==false ) root =
case_b(root, par,ptr);
else if(ptr->rthread==false) root =
case_b(root, par,ptr); else
root = case_a(root,par,ptr); return
root;
} 96
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

struct node *case_a(struct node *root, struct node *par,struct node *ptr )
{
if(par==NULL) root=NULL;
else if(ptr==par->left)
{
par->lthread=true; par-
>left=ptr->left;
}
else
{
par->rthread=true; par-
>right=ptr->right;
}
free(ptr); return root;
}

struct node *case_b(struct node *root,struct node *par,struct node *ptr)


{
struct node *child,*s,*p; if(ptr-
>lthread==false)
child=ptr->left; else
child=ptr->right;
if(par==NULL )
root=child;
else if( ptr==par->left) par-
>left=child;
else
par->right=child;
s=in_succ(ptr);
p=in_pred(ptr);
if(ptr->lthread==false)
p->right=s;
else
{
if(ptr->rthread==false)
s->left=p;
}
free(ptr); return root;
}
struct node *case_c(struct node *root, struct node *par,struct node *ptr){
97
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

struct node *succ,*parsucc; parsucc =


ptr;
succ = ptr->right; while(succ-
>left!=NULL)
{
parsucc = succ; succ =
succ->left;
}
ptr->info = succ->info;
if(succ->lthread==true && succ->rthread==true)
root = case_a(root, parsucc,succ);
else
root = case_b(root, parsucc,succ);
return root;
}
struct node *in_succ(struct node *ptr)
{
if(ptr->rthread==true) return
ptr->right;
else
{
}
}

ptr=ptr->right;
while(ptr->lthread==false) ptr=ptr->left;
return ptr;
struct node *in_pred(struct node *ptr)
{
if(ptr->lthread==true) return
ptr->left;
else
{

void inorder( struct node *root){


struct node *ptr; if(root == NULL )
{
printf("Tree is empty"); return;
}
ptr=root;
while(ptr->lthread==false) ptr=ptr->left; 98
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

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

ptr=ptr->left;
while(ptr->rthread==false) ptr=ptr->right;
return ptr;

void preorder(struct node *root ){


struct node *ptr;
if(root==NULL)
{
printf("Tree is empty"); return;
}
ptr=root;
while(ptr!=NULL)
{
printf("%d ",ptr->info); if(ptr-
>lthread==false) ptr=ptr->left;
else if(ptr->rthread==false)
ptr=ptr->right;
else
{ while(ptr!=NULL && ptr->rthread==true) ptr=ptr-right;
if(ptr!=NULL)ptr=ptr->right;
}
}
}

OUTPUT

Program of Threaded Tree in C


1.Insert
2.Delete
3.Inorder Traversal
4.Preorder Traversal
5.Quit
Enter your choice : 1
Enter the number to be inserted : 100

99
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

Program of Threaded Tree in C


1.Insert
2.Delete
3.Inorder Traversal
4.Preorder Traversal
5.Quit
Enter your choice : 1
Enter the number to be inserted : 200

Program of Threaded Tree in C


1.Insert
2.Delete
3.Inorder Traversal
4.Preorder Traversal
5.Quit
Enter your choice : 1
Enter the number to be inserted : 300

Program of Threaded Tree in C


1.Insert
2.Delete
3.Inorder Traversal
4.Preorder Traversal
5.Quit
Enter your choice : 3 100
200 300

Program of Threaded Tree in C


1.Insert
2.Delete
3.Inorder Traversal
4.Preorder Traversal
5.Quit
Enter your choice : 4 100
200 300

Program of Threaded Tree in C


1.Insert
2.Delete
3.Inorder Traversal
4.Preorder Traversal
5.Quit
100
Downloaded by Omprakash D ([email protected])
lOMoARcPSD|11267200

Enter your choice : 2


Enter the number to be deleted : 200

Program of Threaded Tree in C


1.Insert
2.Delete
3.Inorder Traversal
4.Preorder Traversal
5.Quit
5.Quit

Enter your choice : 3 100 300

Program of Threaded Tree in C


1.Insert
2.Delete
3.Inorder Traversal
4.Preorder Traversal
5.Quit
Enter your choice : 5

RESULT
Thus the C program for implementation of Threaded Binary Tree was done and
executed successfully.

101
Downloaded by Omprakash D ([email protected])

You might also like