You are on page 1of 49

L T P C

B19CSP305 FUNDAMENTALS OF DATA STRUCTURES IN


B.E-ECE
C LABORATORY 0 0 4 2

OBJECTIVES:
1. To understand and implement basic data structures using C
2. Understand the principles of linear and nonlinear data structures.
3. To understand and implement basic data structures using C
4. Build an applications using sorting
5. Build an application using searching.
LIST OF EXERCISES:

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


2. Programs using strings – string function implementation.
3. Programs using structures and pointers.
4. Programs involving dynamic memory allocations.
5. Write a C program to implement a Stack ADT using array.
6. Write a C program to implement the Queue ADT using array and write the routine to enqueuer and
dequeuer operations.
7. Linked list implementation of stacks and queues.
8. Write a C program that uses functions to perform the following:
a. Create a binary search tree of integers.
b. Traverse the above Binary search tree non recursively in inorder.
9. Implementation of Linear search and binary search.
10. Write C programs for implementing the following sorting methods to arrange a
11. list of integers in ascending order:
a) Insertion sort b) Merge sort
12. Write C programs for implementing the following sorting methods to arrange alist of integers in
ascending order:
a)Quick sort b) Bubble sort

TOTAL:60 PERIODS

OUTCOMES: Upon completion of the course, the students will be able to:
 Write basic and advanced programs in C
 Implement functions and recursive functions in C
 Implement data structures using C
 Choose appropriate sorting algorithm for an application and implement it in a modularized way
 Implement C programs to illustrate linear data structures
 Develop C programs to implement nonlinear data structures. 2
INDEX

SIGNATURE
PAGE
Sl.No. DATE NAME OF THE EXPERIMENT MARKS OF THE
No.
FACULTY
Basic C Programs – looping, data
1.
manipulations, arrays
Programs using strings – string function
2. implementation

3. Programs using structures and pointers

Programs involving dynamic memory


4. allocations

5. Array implementation of stack

6. Array implementation of Queue

7(a). Linked list implementation of stack

7(b). Linked list implementation of Queue

8(a). Implementation of Trees, Tree Traversals

8(b). Implementation of Binary Search trees

Implementation of Linear Search


9(a).
9(b). Implementation of Binary Search

10(a). Implementation of Insertion Sort

10(b). Implementation of Bubble Sort

11(a). Implementation of Quick Sort

11(b). Implementation of Merge Sort

12. Implementation of hash functions,


collision resolution technique
ADDITIONAL EXPERIMENT (CONTENT BEYOND SYLLABUS)

13. Implementation of File concepts

3
Ex.No :1(a) Basic C Program – Looping, array - Finding the sum of elements in an
Date: array

Aim:
To write a c program to illustrate the usage of loop to find the sum of elements in an
array.

Algorithm:
Step 1 : Start
Step 2 : Take an array ‘a’ and define its values
Step 3 : Loop for each value of an array ‘a’
Step 4 : Add each element to 'sum' variable
Step 5: After the loop finishes, display 'sum'
Step 6 : Stop

Program:
#include<stdio.h>
#include <conio.h>
void main()
{
int array[10]={1,2,3,4,5,6,7,8,9,0};
int sum, loop;
sum =0;
for(loop =9; loop >=0; loop--)
{
sum = sum + array[loop];
}
printf("Sum of array is %d.", sum);
getch();
}

Output:
Sum of array is 45.

Result:

Thus the c program to illustrate the usage of loop to find the sum of elements in an array has
been executed successfully.
4
Ex.No :1(b)
Basic C Program – Array implementation
Date:
Aim:
To write a C program to illustrate the usage of an array to pass an array containing age of
person to a function and to find average age and display the average age in main function.

Algorithm:
Step 1 : Start
Step 2 : Take an array ‘age’ and define its values
Step 3 : Call function average() by passing an array ‘age’ as an argument
Step 4 : Loop for each value of an array ‘age’ to find the sum of it inside average()
Step 5: After the loop finishes, calculate ‘avg’
Step 6 : Return ‘avg’ and print it in main function
Step 7: Stop

Program:
#include<stdio.h>
#include<conio.h>
float average(float age[]);
void main()
{
Float avg,age[]={23.4,55,22.6,3,40.5,18};
avg= average(age);/* Only name of array is passed as argument. */
printf("Average age=%.2f",avg);
getch();
}
float average(float age[])
{
Int i;float avg, sum =0.0;
for(i=0;i<6;++i)
sum += age[i];
avg=(sum /6);
return avg;
}
Output:
Average age=27.08

Result:
Thus the C program to illustrate the usage of an array to pass an array containing
age of person to a function and to find average age and display the average age in main function
has been executed successfully.

5
Ex.No :1(c)
Basic C Program - Data manipulations
Date:
Aim:
To write a C program to illustrate data manipulation using file handling
Algorithm:
Step 1: Start
Step 2: Open file “input.txt” in read mode.
Step 3: Read the contents of file
Step 4: Reverse the contents of the file and print it on the standard output.
Step 5: Stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
int i,pos;
fp=fopen("input.txt","r");
if(fp==NULL)
{
printf("File does not exist..");
}
fseek(fp,0,SEEK_END);
pos=ftell(fp);
//printf("Current postion is %d\n",pos);
i=0;
while(i<pos) {
i++;
fseek(fp,-i,SEEK_END);
//printf("%c",fgetc(fp));
ch=fgetc(fp);
printf("%c",ch); }
getch();}
Input.txt
hai
Output:
iah
Result:
Thus the C Program to illustrate data manipulation using file handling has been
successfully executed.

6
Ex.No : 2(a)
Program using strings
Date:

Aim:
To write a C program to read a string and check if it's a palindrome, without using library
functions.

Algorithm:
Step 1: Start
Step 2 : Take a string as input and store it in the array string[].
Step 3 : Store the same string into the another array reverse_string[] in the reverse
fashion.
Step 4 : Using for loop compare the elements of both the arrays.
Step 5 : If all the elements of the array are same, then it is a palindrome. Otherwise it is
not a palindrome.
Step 6: Stop

Program:
#include <stdio.h>
#include <string.h>
void main()
{
char string[25], reverse_string[25] = {'\0'};
int i, length = 0, flag = 0;
fflush(stdin);
printf("Enter a string \n");
gets(string);
/* keepgoing through each character of the string till its end */
for (i = 0; string[i] != '\0'; i++)
{
length++;
}
for (i = length - 1; i>= 0; i--)
{
reverse_string[length - i - 1] = string[i];
}
for (i = 0; i< length; i++)
{
if (reverse_string[i] == string[i])
flag = 1;

7
else
flag = 0;
}
if (flag == 1)
printf("%s is a palindrome \n", string);
else
printf("%s is not a palindrome \n", string);
}

Output:
Enter a string
sanfoundry
sanfoundry is not a palindrome

Enter a string
malayalam
malayalam is a palindrome

Result:
Thus a C program to read a string and check if it's a palindrome, without using library
functions has been executed successfully.
8
Ex.No : 2(b)
Program using string functions
Date:
Aim:
To write a C program to illustrate the usage of string functions.

Algorithm:
Step 1 : Start
Step 2 : Declare a string as input and store it in the array string[].
Step 3 : Find the length of the string using strlen() function and print the length of the
string
Step 4 :Use Strstr() which returns the pointer to the first occurrence of the string in a
given string
Step 5: Stop

Program:
#include <stdio.h>
#include <string.h>
#include<conio.h>
#include<stdio.h>
void main( )
{
Int len;
char string[20]="fresh refresh com" ; char *p;
len = strlen(string) ;
printf ( "string length = %d \n" , len ) ;
p = strstr (string,"refresh");
if(p)
{
printf("string found\n" );
printf ("First occurrence of string \"refresh\" in \"%s\" is \"%s\"",string, p);
}
else printf("string not found\n" );
getch();}
Output:
string length = 17
string found
First occurrence of string "refresh" in "fresh refresh com" is "refresh com"
Result:
Thus the C program to illustrate the usage of string functions has been executed
successfully.

9
Ex.No : 3
Programs using structures and pointers
Date:

Aim:
To write a C program to illustrate the usage of structures and pointers

Algorithm:
Step 1:Start
Step 2: Create Structure using 'struct Structure_name{}'
Step 3: Create pointer variable for structure
Step 4: Use Arrow operator for accessing members of structure using pointer variable
Step 5: Stop

Program:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct person {
int age;
float weight;
char name[30];
};

void main()
{
struct person *ptr;
inti,num;

printf("Enter number of persons: ");


scanf("%d",&num);

ptr=(struct person*) malloc(num*sizeof(struct person));


// Above statement allocates the memory for n structures with pointer personPtr pointing to base
address */

for(i=0;i<num;++i)
{
printf("Enter name, age and weight of the person respectively:\n");
scanf("%s%d%f",&(ptr+i)->name,&(ptr+i)->age,&(ptr+i)->weight);
}

10
printf("Displaying Infromation:\n");
for(i=0;i<num;++i)
printf("%s\t%d\t%.2f\n",(ptr+i)->name,(ptr+i)->age,(ptr+i)->weight);

getch();
}

Output:
Enter number of persons: 2
Enter name, age and weight of the person respectively:
Adam
2
3.2
Enter name, age and weight of the person respectively:
Eve
6
2.3
Displaying Information:
Adam23.20
Eve62.30

Result:
Thus the C program to illustrate the usage of structures and pointers has been
successfully executed.
11
Ex.No : 4(a)
Program involving dynamic memory allocation(calloc() and free())
Date:
Aim:
To write a C program to find the sum of n elements by allocating memory dynamically
using calloc() function.
Algorithm:
Step 1: Start
Step 2: Read the no. of elements
Step 3: Allocate memory dynamically using Calloc() function
Step 4: Add the elements into sum variable
Step 5: Print ‘sum’
Step 6: Deallocate memory using free()
Step 7: Stop
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);

ptr = (int*) calloc(num, sizeof(int));


if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0); }
printf("Enter elements of array: ");
for(i = 0; i < num; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i); }
printf("Sum = %d", sum);
free(ptr);
return 0;}
Output:
Enter number of elements: 5
Enter elements of array: 1
2
3
4
5
Sum = 15

Result:
Thus the C program to find sum of n elements by allocating memory dynamically using
calloc() function has been successfully executed.

12
Ex.No : 4(b) Program involving dynamic memory allocation (malloc() and
Date: realloc())
Aim:
To write a C program to illustrate the usage of dynamic memory allocation using
malloc () and realloc()
Algorithm:
Step 1: Start
Step 2: Read the size of an array
Step 3: Allocate memory using malloc() function
Step 4: Print the address of an array
Step 5: To reallocate the memory, read the new size of an array.
Step 6: Print the address of an array after reallocation
Step 7: Stop
Program:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
int*ptr,i, n1, n2;
printf("Enter size of array: ");scanf("%d",&n1);
ptr=(int*) malloc(n1 *sizeof(int));
printf("Address of previously allocated memory: ");
for(i=0;i< n1;++i)
printf("%u\t",ptr+i);
printf("\nEnter new size of array: ");scanf("%d",&n2);
ptr=realloc(ptr, n2);
for(i=0;i< n2;++i)
printf("%u\t",ptr+i);
getch();
}
Output:
Enter size of array: 3
Address of previously allocated memory: 10760208 10760212 10760216

Enter new size of array: 2


10760208 10760212

Result:
Thus the C program to illustrate the usage of dynamic memory allocation using malloc
() and realloc() has been executed successfully.

13
Ex.No:5a
Array implementation of stack
Date:
Aim:
To write a C program to implement a stack using array.

Algorithm:
Before implementing actual operations, first follow the below steps to create an empty stack.
Step 1: Include all the header files which are used in the program and define a
constant 'SIZE' with specific value.
Step 2: Declare all the functions used in stack implementation.
Step 3: Create a one dimensional array with fixed size (int stack[SIZE])
Step 4: Define a integer variable 'top' and initialize with '-1'. (int top = -1)
Step 5: In main method display menu with list of operations and make suitable function
calls to perform operation selected by the user on the stack.
push(value) - Inserting value into the stack
Step 1: Check whether stack is FULL. (top == SIZE-1)
Step 2: If it is FULL, then display "Stack is FULL!!! Insertion is not possible!!!" and
terminate the function.
Step 3: If it is NOT FULL, then increment top value by one (top++) and set stack[top] to
value (stack[top] = value).
pop() - Delete a value from the Stack
Step 1: Check whether stack is EMPTY. (top == -1)
Step 2: If it is EMPTY, then display "Stack is EMPTY!!! Deletion is not possible!!!" and
terminate the function.
Step 3: If it is NOT EMPTY, then delete stack[top] and decrement top value by one (top-
-).
display() - Displays the elements of a Stack
Step 1: Check whether stack is EMPTY. (top == -1)
Step 2: If it is EMPTY, then display "Stack is EMPTY!!!" and terminate the function.
Step 3: If it is NOT EMPTY, then define a variable 'i' and initialize with top.
Display stack[i] value and decrement i value by one (i--).
Step 4: Repeat above step until i value becomes '0'.
Program:
#include<stdio.h>
#include<conio.h>
#define SIZE 10
void push(int);
void pop();
void display();
int stack[SIZE], top = -1;
void main()

14
{
int value, choice;
clrscr();
while(1){
printf("\n\n***** MENU *****\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
push(value);
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Try again!!!");
} }}
void push(int value){
if(top == SIZE-1)
printf("\nStack is Full!!! Insertion is not possible!!!");
else{
top++;
stack[top] = value;
printf("\nInsertion success!!!");
}}
void pop(){
if(top == -1)
printf("\nStack is Empty!!! Deletion is not possible!!!");
else{
printf("\nDeleted : %d", stack[top]);
top--;
}}
void display(){
if(top == -1)
printf("\nStack is Empty!!!");
else{
inti;
printf("\nStack elements are:\n");
for(i=top; i>=0; i--)
15
printf("%d\n",stack[i]);
}}
Output:
***** MENU *****
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 4
Insertion success!!!
***** MENU *****
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 5
Insertion success!!!
***** MENU *****
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2
Deleted : 5
***** MENU *****
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
Stack elements are:
4
***** MENU *****
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 4

Result:
Thus the C program to implement a stack using array has been successfully implemented.

16
Ex.No:5b
Array implementation of Queue
Date:

Aim:
To write a C program to implement Queue data structure using array

Algorithm:

Before we implement actual operations, first follow the below steps to create an empty
queue.
Step 1: Include all the header files which are used in the program and define a
constant 'SIZE' with specific value.
Step 2: Declare all the user defined functions which are used in queue implementation.
Step 3: Create a one dimensional array with above defined SIZE (int queue[SIZE])
Step 4: Define two integer variables 'front' and 'rear' and initialize both with '-1'. (int front
= -1, rear = -1)
Step 5: Then implement main method by displaying menu of operations list and make
suitable function calls to perform operation selected by the user on queue.

enQueue(value) - Inserting value into the queue


Step 1: Check whether queue is FULL. (rear == SIZE-1)
Step 2: If it is FULL, then display "Queue is FULL!!! Insertion is not possible!!!" and
terminate the function.
Step 3: If it is NOT FULL, then increment rear value by one (rear++) and
set queue[rear] = value.

deQueue() - Deleting a value from the Queue


Step 1: Check whether queue is EMPTY. (front == rear)
Step 2: If it is EMPTY, then display "Queue is EMPTY!!! Deletion is not
possible!!!" and terminate the function.
Step 3: If it is NOT EMPTY, then increment the front value by one (front ++). Then
display queue[front] as deleted element. Then check whether both front and rear are equal
(front == rear), if it TRUE, then set both front and rear to '-1' (front = rear = -1).

display() - Displays the elements of a Queue


Step 1: Check whether queue is EMPTY. (front == rear)
Step 2: If it is EMPTY, then display "Queue is EMPTY!!!" and terminate the function.
Step 3: If it is NOT EMPTY, then define an integer variable 'i' and set 'i = front+1'.
Step 4: Display 'queue[i]' value and increment 'i' value by one (i++). Repeat the same
until 'i' value is equal to rear (i <= rear)

17
Program:
#include<stdio.h>
#include<conio.h>
#define SIZE 10
void enQueue(int);
void deQueue();
void display();

int queue[SIZE], front = -1, rear = -1;

void main()
{
int value, choice;
clrscr();
while(1){
printf("\n\n***** MENU *****\n");
printf("1. Insertion\n2. Deletion\n3. Display\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
enQueue(value);
break;
case 2: deQueue();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Try again!!!");
} }}
void enQueue(int value){
if(rear == SIZE-1)
printf("\nQueue is Full!!! Insertion is not possible!!!");
else{
if(front == -1)
front = 0;
rear++;
queue[rear] = value;
printf("\nInsertion success!!!"); }}
void deQueue(){
if(front == rear)

18
printf("\nQueue is Empty!!! Deletion is not possible!!!");
else{ printf("\nDeleted : %d", queue[front]);
front++;
if(front == rear)
front = rear = -1; }}
void display(){ if(rear == -1)
printf("\nQueue is Empty!!!");
else{
inti;
printf("\nQueue elements are:\n");
for(i=front; i<=rear; i++)
printf("%d\t",queue[i]);
}}
Output:
***** MENU *****
1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 1
Insertion success!!!
***** MENU *****
1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 2
Insertion success!!!
***** MENU *****
1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 3
Queue elements are:
1 2
***** MENU *****
1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 4
Result:
Thus the C program to implement Queue data structure using array has been successfully
executed.

19
Ex.No:7a
Linked list implementation of stack
Date:

Aim:
To write a C program to implement stack using linked list

Algorithm:

To implement stack using linked list, we need to set the following things before implementing
actual operations
Step 1: Include all the header files which are used in the program. And declare all
the user defined functions.
Step 2: Define a 'Node' structure with two members data and next.
Step 3: Define a Node pointer 'top' and set it to NULL.
Step 4: Implement the main method by displaying Menu with list of operations and make
suitable function calls in the main method.

push(value) - Inserting an element into the Stack


Step 1: Create a newNode with given value.
Step 2: Check whether stack is Empty (top == NULL)
Step 3: If it is Empty, then set newNode → next = NULL.
Step 4: If it is Not Empty, then set newNode → next = top.
Step 5: Finally, set top = newNode.

pop() - Deleting an Element from a Stack


Step 1: Check whether stack is Empty (top == NULL).
Step 2: If it is Empty, then display "Stack is Empty!!! Deletion is not possible!!!" and
terminate the function
Step 3: If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.
Step 4: Then set 'top = top → next'.
Step 5: Finally, delete 'temp' (free(temp)).

display() - Displaying stack of elements


Step 1: Check whether stack is Empty (top == NULL).
Step 2: If it is Empty, then display 'Stack is Empty!!!' and terminate the function.
Step 3: If it is Not Empty, then define a Node pointer 'temp' and initialize with top.
Step 4: Display 'temp → data --->' and move it to the next node. Repeat the same
until temp reaches to the first node in the stack (temp → next != NULL).
Step 5: Finally! Display 'temp → data ---> NULL'.

20
Program:
#include<stdio.h>
#include<conio.h>

struct Node
{
int data;
struct Node *next;
}*top = NULL;

void push(int);
void pop();
void display();

void main()
{
int choice, value;
clrscr();
printf("\n:: Stack using Linked List ::\n");
while(1){
printf("\n****** MENU ******\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d", &value);
push(value);
break;
case 2: pop(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
}
}
}
void push(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
if(top == NULL)
21
newNode->next = NULL;
else
newNode->next = top;
top = newNode;
printf("\nInsertion is Success!!!\n");
}
void pop()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else{
struct Node *temp = top;
printf("\nDeleted element: %d", temp->data);
top = temp->next;
free(temp);
}
}
void display()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else{
struct Node *temp = top;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL",temp->data);
}
}
Output:

:: Stack using Linked List ::

****** MENU ******


1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 3

22
Insertion is Success!!!
****** MENU ******
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 5

Insertion is Success!!!
****** MENU ******
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
5--->3--->NULL
****** MENU ******
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2

Deleted element: 5
****** MENU ******
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:
3
3--->NULL
****** MENU ******
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:4

Result:
Thus the C program to implement stack using linked list has been successfully executed.
23
Ex.No:7b
Linked list implementation of Queue
Date:

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

Algorithms:

To implement queue using linked list , we need to set the following things before implementing
actual operations.
Step 1: Include all the header files which are used in the program. And declare all
the user defined functions.
Step 2: Define a 'Node' structure with two members data and next.
Step 3: Define two Node pointers 'front' and 'rear' and set both to NULL.
Step 4: Implement the main method by displaying Menu of list of operations and make
suitable function calls in the main method to perform user selected operation.

enQueue(value) - Inserting an element into the Queue


Step 1: Create a newNode with given value and set 'newNode → next' to NULL.
Step 2: Check whether queue is Empty (rear == NULL)
Step 3: If it is Empty then, set front = newNode and rear = newNode.
Step 4: If it is Not Empty then, set rear → next = newNode and rear = newNode.

deQueue() - Deleting an Element from Queue


Step 1: Check whether queue is Empty (front == NULL).
Step 2: If it is Empty, then display "Queue is Empty!!! Deletion is not possible!!!" and
terminate from the function
Step 3: If it is Not Empty then, define a Node pointer 'temp' and set it to 'front'.
Step 4: Then set 'front = front → next' and delete 'temp' (free(temp)).

display() - Displaying the elements of Queue


Step 1: Check whether queue is Empty (front == NULL).
Step 2: If it is Empty then, display 'Queue is Empty!!!' and terminate the function.
Step 3: If it is Not Empty then, define a Node pointer 'temp' and initialize with front.
Step 4: Display 'temp → data --->' and move it to the next node. Repeat the same until
'temp' reaches to 'rear' (temp → next != NULL).
Step 4: Finally! Display 'temp → data ---> NULL'.

Program:
#include<stdio.h>
#include<conio.h>

24
struct Node
{
int data;
struct Node *next;
}*front = NULL,*rear = NULL;

void insert(int);
void delete();
void display();

void main()
{
int choice, value;
clrscr();
printf("\n:: Queue Implementation using Linked List ::\n");
while(1){
printf("\n****** MENU ******\n");
printf("1. Insert\n2. Delete\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d", &value);
insert(value);
break;
case 2: delete(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
}
}
}
void insert(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode -> next = NULL;
if(front == NULL)
front = rear = newNode;
else{
25
rear -> next = newNode;
rear = newNode;
}
printf("\nInsertion is Success!!!\n");
}
void delete()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
front = front -> next;
printf("\nDeleted element: %d\n", temp->data);
free(temp);
}
}
void display()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL\n",temp->data);
}
}

Output:
:: Queue Implementation using Linked List ::

****** MENU ******


1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 3

Insertion is Success!!!
26
****** MENU ******
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice:
1
Enter the value to be insert: 5

Insertion is Success!!!

****** MENU ******


1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 2

Deleted element: 3

****** MENU ******


1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 3
5--->NULL

****** MENU ******


1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 4

Result:
Thus the c program to implement queue using linked list has been successfully executed.

27
Ex.No:8a
Implementation of Trees, Tree Traversals
Date:

Aim:
To write a C program to implement a tree and its traversals

Algorithm:

Insertion into binary tree


Step 1:Check first if tree is empty, then insert node as root.
Step 2:Check if node value to be inserted is lesser than root node value, then
Step 2.1:Call insert() function recursively while there is non-NULL left node
Step2.2:When reached to leftmost node as NULL, insert new node.
Step3:Check if node value to be inserted is greater than root node value, then
Step3.1:Call insert() function recursively while there is non-NULL right node
Step3.2:When reached to rightmost node as NULL, insert new node.

Searching into binary tree


Step1:Check first if tree is empty, then return NULL.
Step2:Check if node value to be searched is equal to root node value, then return node
Step3:Check if node value to be searched is lesser than root node value, then call search()
function recursively with left node
Step4:Check if node value to be searched is greater than root node value, then call
search() function recursively with right node
Step 5:Repeat step 2, 3, 4 for each recursion call of this search function until node to be
searched is found.

Deletion of binary tree


Step1:Check first if root node is non-NULL, then
Step1.1:Call deltree() function recursively while there is non-NULL left node
Step 1.2:Call deltree() function recursively while there is non-NULL right node
Step 1.3:Delete the node.

Displaying binary tree

Pre-order display
Step1:Display value of root node.
Step2:Call print_preorder() function recursively while there is non-NULL left node
Step3:Call print_preorder() function recursively while there is non-NULL right node

In-order display

28
Step1:Call print_inorder() function recursively while there is non-NULL left node
Step2: Display value of root node.
Step3:Call print_inorder() function recursively while there is non-NULL right node

Post-order display
Step1:Call print_postorder() function recursively while there is non-NULL left node
Step2:Call print_postorder() function recursively while there is non-NULL right node
Step3:Display value of root node.

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, intval)


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

29
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)


{
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, intval)
{
if(!(*tree))
{
return NULL;
30
}

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;
//inti;

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);
/* 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);
31
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
17
Post Order Display
2
6
4
12
17
15
9
Searched node=4
Result:
Thus the C program to implement a tree and its traversals have been successfully
executed

32
Ex.No:8b
Implementation of Binary Search trees
Date:

Aim:
To write a C program to demonstrate insert operation in binary search tree

Algorithm:

Step 1: Start from root.


Step 2: Compare the inserting element with root, if less than root, then recurse for left,
else recurse for right.
Step 3: After reaching end, just insert that node at left(if less than current) else right.

Program:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int key;
struct node *left, *right;
};

// A utility function to create a new BST node


struct node *newNode(int item)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to do inorder traversal of BST
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d \n", root->key);
inorder(root->right);
}
}

33
/* A utility function to insert a new node with given key in BST */
struct node* insert(struct node* node, int key)
{
/* If the tree is empty, return a new node */
if (node == NULL) return newNode(key);
/* Otherwise, recur down the tree */
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);

/* return the (unchanged) node pointer */


return node;
}
// Driver Program to test above functions
int main()
{
/* Let us create following BST
50
/ \
30 70
/ \ /\
20 40 60 80 */
struct node *root = NULL;
root = insert(root, 50);
insert(root, 30);insert(root, 20);
insert(root, 40);insert(root, 70);
insert(root, 60);
insert(root, 80);
inorder(root);
return 0;}
Output:
20
30
40
50
60
70
80
Result:
Thus the C program to demonstrate insert operation in binary search tree has been
executed successfully.
34
Ex.No:9a
Implementation of Linear Search
Date:

Aim:
To write a C program to implement linear search in an array

Algorithm:
Step 1: Start from the leftmost element of arr[] and one by one compare x with each
element of arr[]
Step 2: If x matches with an element, return the index.
Step 3: If x doesn’t match with any of elements, return -1.

Program:
#include <stdio.h>
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
return i;
return -1;
}
int main(void)
{
int arr[] = {2, 3, 10,4, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = search(arr,n-1, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d",
result);
return 0;
}

Output:
Element is present at index 2

Result:
Thus the C program to implement linear search in an array has been successfully
executed

35
Ex.No:9b
Implementation of Binary Search
Date:

Aim:
To write a C program to implement binary search in an array

Algorithm:

Step 1: Compare x with the middle element.


Step 2: If x matches with middle element, we return the mid index.
Step 3:Else If x is greater than the mid element, then x can only lie in right half subarray
after the mid element. So we recur for right half.
Step 4: Else (x is smaller) recur for the left half.

Program:
// C program to implement recursive Binary Search
#include <stdio.h>

// A recursive binary search function. It returns


// location of x in given array arr[l..r] is present,
// otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l)/2;

// If the element is present at the middle


// itself
if (arr[mid] == x)
return mid;

// If element is smaller than mid, then


// it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid-1, x);

// Else the element can only be present


// in right subarray
return binarySearch(arr, mid+1, r, x);
}

36
// We reach here when element is not
// present in array
return -1;
}

int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n-1, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d",
result);
return 0;
}

Output:
Element is present at index 3

Result:
Thus the C program to implement binary search in an array has been successfully
executed.

37
Ex.No:10a
Implementation of Insertion Sort
Date:
Aim:
To write a C program to implement insertion sort
Algorithm:
Step 1: Assume that first element in the list is in sorted portion of the list and remaining
all elements are in unsorted portion.
Step 2: Consider first element from the unsorted list and insert that element into the
sorted list in order specified.
Step 3: Repeat the above process until all the elements from the unsorted list are moved
into the sorted list.
Program:
#include<stdio.h>
#include<conio.h>
void main(){
int size, i, j, temp, list[100];
printf("Enter the size of the list: ");
scanf("%d", &size);
printf("Enter %d integer values: ", size);
for (i = 0; i < size; i++)
scanf("%d", &list[i]);
for (i = 1; i < size; i++) {
temp = list[i];
j = i - 1;
while ((temp < list[j]) && (j >= 0)) {
list[j + 1] = list[j];
j = j - 1;
} list[j + 1] = temp; }
printf("List after Sorting is: ");
for (i = 0; i < size; i++)
printf(" %d", list[i]);
getch();}
Output:Enter the size of the list: 5
Enter 5 integer values: 6
3
9
1
2
List after Sorting is: 1 2 3 6 9
Result:
Thus the C program to implement insertion sort has been successfully executed

38
Ex.No:10b
Implementation of Bubble Sort
Date:
Aim:
To write a C program to implement Bubble sort

Algorithm:
Step 1: Starting with the first element(index = 0), compare the current element with the
next element of the array.
Step 2: If the current element is greater than the next element of the array, swap them.
Step 3: If the current element is less than the next element, move to the next
element. Repeat Step 1.

Program:
#include <stdio.h>
#include <conio.h>
void bubbleSort(int arr[], int n)
{ int i, j, temp;
for(i = 0; i < n; i++)
{ for(j = 0; j < n-i-1; j++)
{
if( arr[j] > arr[j+1])
{ // swap the elements
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
} } }
// print the sorted array
printf("Sorted Array: ");
for(i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}}
void main()
{
int arr[100], i, n, step, temp;
// ask user for number of elements to be sorted
printf("Enter the number of elements to be sorted: ");
scanf("%d", &n);
// input elements if the array
for(i = 0; i < n; i++)
{

39
printf("Enter element no. %d: ", i+1);
scanf("%d", &arr[i]);
}
// call the function bubbleSort
bubbleSort(arr, n);
getch();
// return 0;
}
Output:

Enter the number of elements to be sorted: 5


Enter element no. 1: 3
Enter element no. 2: 7
Enter element no. 3: 1
Enter element no. 4: 9
Enter element no. 5: 2
Sorted Array: 1 2 3 7 9

Result:
Thus, the C program to implement Bubble sort has been successfully executed.

40
Ex.No:11a
Implementation of Quick Sort
Date:

Aim:
To write a C program to implement Quick sort

Algorithm:
Step 1: After selecting an element as pivot, which is the last index of the array
Step 2: Do partitioning where the array elements are so positioned that all the elements
smaller than the pivot will be on the left side of the pivot and all the elements greater than
the pivot will be on the right side of it and the pivot element will be at its
final sorted position.
Step 3: Then we pick subarrays, elements on the left of pivot and elements on the right
of pivot, and we perform partitioning on them by choosing a pivot in the subarrays to get
them sorted.

Program:
#include<stdio.h>
#include<conio.h>
// A utility function to swap two elements
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
/* This function takes last element as pivot, places the pivot element at its correct position in
sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements
to right of pivot */
int partition (int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
int j;
for (j = low; j <= high- 1; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{ i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
41
} }
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
/* The main function that implements QuickSort
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quickSort(int arr[], int low, int high)
{ if (low < high) {
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);

// Separately sort elements before


// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
//printf("n");
}// Driver program to test above functions
void main()
{
clrscr();
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr)/sizeof(arr[0]);
quickSort(arr, 0, n-1);
printf("Sorted array: ");
printArray(arr, n);
getch();
}
Output:
Sorted array:1 5 7 8 9 10

Result:
Thus, the C program to implement Quick sort has been successfully executed.
42
Ex.No:11b
Implementation of Merge Sort
Date:

Aim:
To write a C program to implement Merge sort

Algorithm:
Step 1: Take a variable p and store the starting index of array in this.
Step 2:And take another variable r and store the last index of array in it.
Step 3:Thenfind the middle of the array using the formula (p + r)/2 and mark the middle
index as q, and break the array into two subarrays, from p to q and from q + 1 to r index.
Step 4: Then divide these 2 subarrays again, just like we divided main array and this
continues.
Step 5: Once we have divided the main array into subarrays with single elements, then we
start merging the subarrays.

Program:

/*
a[] is the array, p is starting index, that is 0,
and r is the last index of array.
*/

#include <stdio.h>

#include<conio.h>
// lets take a[5] = {32, 45, 67, 2, 7} as the array to be sorted.

// merge sort function


void mergeSort(int a[], int p, int r)
{
int q;
if(p < r)
{
q = (p + r) / 2;
mergeSort(a, p, q);
mergeSort(a, q+1, r);
merge(a, p, q, r);
}
}

43
// function to merge the subarrays
void merge(int a[], int p, int q, int r)
{
int b[5]; //same size of a[]
int i, j, k;
k = 0;
i = p;
j = q + 1;
while(i <= q && j <= r)
{
if(a[i] < a[j])
{
b[k++] = a[i++]; // same as b[k]=a[i]; k++; i++;
}
else
{
b[k++] = a[j++];
}
}

while(i <= q)
{
b[k++] = a[i++];
}

while(j <= r)
{
b[k++] = a[j++];
}

for(i=r; i >= p; i--)


{
a[i] = b[--k]; // copying back the sorted list to a[]
}
}

// function to print the array


void printArray(int a[], int size)
{
int i;
for (i=0; i < size; i++)
{
44
printf("%d ", a[i]);
}
printf("\n");
}

void main()
{
int arr[] = {32, 45, 67, 2, 7};
int len = sizeof(arr)/sizeof(arr[0]);

printf("Given array: \n");


printArray(arr, len);

// calling merge sort


mergeSort(arr, 0, len - 1);

printf("\nSorted array: \n");


printArray(arr, len);
getch();
// return 0;
}

Output:
Given array:
32 45 67 2 7

Sorted array:
2 7 32 45 67

Result:
Thus the C program to implement Merge sort has been successfully executed and
verified.

45
Ex.No:12
Implementation of hash functions, collision resolution technique
Date:

Aim:
To write a C program to implement Hash Tables with linear Probing and Quadratic
Probing

Algorithm:
Step 1:Start
Step 2:Read the size 'tsize' of the hash table.
Step 3:Read the elements to be inserted in the hash table
Step 4:Use formula (key + 1) % tsize to implement hash table using Linear Probing
Step 5: Use formula (key + (j * j)) % tsize to implement hash table using Quadratic
Probing where j= 1, 2, 3, 4 and so on.
Step 6:Exit

Program:
#include <stdio.h>
#include <conio.h>
int tsize;

int hasht(int key)


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

//-------LINEAR PROBING-------
int rehashl(int key)
{
int i ;
i = (key+1)%tsize ;
return i ;
}

//-------QUADRATIC PROBING-------
int rehashq(int key, int j)
{
int i ;
i = (key+(j*j))%tsize ;
46
return i ;
}

void main()
{
int key,arr[20],hash[20],i,n,s,op,j,k ;
clrscr() ;
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]);
}

do
{
printf("\n\n1.Linear Probing\n2.Quadratic Probing \n3.Exit \nEnter your option: ");
scanf("%d",&op);
switch(op)
{
case 1:
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 ;
}
47
printf("\nThe elements in the array are: ");
for (i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i]);
}
break ;

case 2:
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]);
}
break ;

}
}while(op!=3);

getch() ;
}

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

48
1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 1

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

1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 2

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

1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 3
Result:
Thus the C program to implement Hash Tables with linear Probing and Quadratic
Probing have been successfully executed and verified.
49
Ex.No :13
Implementation of File concepts
Date:

Aim:
To write a C program to illustrate data manipulation using file handling
Algorithm:
Step 1: Start
Step 2: Open file “input.txt” in read mode.
Step 3: Read the contents of file
Step 4: Reverse the contents of the file and print it on the standard output.
Step 5: Stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
int i,pos;
fp=fopen("input.txt","r");
if(fp==NULL) {
printf("File does not exist.."); }
fseek(fp,0,SEEK_END);
pos=ftell(fp);
//printf("Current postion is %d\n",pos);
i=0;
while(i<pos) {
i++;
fseek(fp,-i,SEEK_END);
//printf("%c",fgetc(fp));
ch=fgetc(fp);
printf("%c",ch); }
getch();}
Input.txt
hai
Output:
iah

50

You might also like