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

DS Lab

The document outlines a Data Structures Lab course at Dayananda Sagar College, detailing various programming tasks related to data structures such as searching algorithms, sorting algorithms, linked lists, queues, and binary trees. Each task includes specific input data and expected operations, along with example code snippets for implementation. The document serves as a guide for students to practice and demonstrate their understanding of fundamental data structure concepts.

Uploaded by

gopalk5652
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)
7 views

DS Lab

The document outlines a Data Structures Lab course at Dayananda Sagar College, detailing various programming tasks related to data structures such as searching algorithms, sorting algorithms, linked lists, queues, and binary trees. Each task includes specific input data and expected operations, along with example code snippets for implementation. The document serves as a guide for students to practice and demonstrate their understanding of fundamental data structure concepts.

Uploaded by

gopalk5652
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/ 68

Data Structures Lab Prof. Diwakara Vasuman.M.

DAYANANDA SAGAR COLLEGE OF ARTS SCIENCE AND COMMERCE


Shavige Malleshwara Hills, Kumaraswamy Layout, Bengaluru –
560078
Department of Computer Applications
Data Structure Lab

Submitted by:
Diwakara Vasuman.M.S
Assistant Professor, BCA Department
DSCASC

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

Data Structures Lab


CA-C5P: DATA STRUCTURES LAB PROGRAMS
1. Given {4,7,3,2,1,7,9,0} find the location of 7 using Linear and Binary search and also
display its first occurrence.
2. Given {5,3,1,6,0,2,4} order the numbers in ascending order using Bubble Sort
Algorithm.
3. Perform the Insertion and Selection Sort on the input {75,8,1,16,48,3,7,0} and
display the output in descending order.
4. Write a program to insert the elements {61,16,8,27} into singly linked list and delete
8,61,27 from the list. Display your list after each insertion and deletion.
5. Write a program to insert the elements {61,16,8,27} into linear queue and delete
three elements from the list. Display your list after each insertion and deletion.
6. Write a program to insert the elements {61,16,8,27} into circular queue and delete
4 elements from the list. Display your list after each insertion and deletion.
7. Write a program to insert the elements {61,16,8,27} into ordered singly linked list
and delete 8,61,27 from the list. Display your list after each insertion and deletion.
8. Write a program to add 6x3+10x2+0x+5 and 4x2+2x+1 using linked list.
9. Write a program to push 5,9,34,17,32 into stack and pop 3 times from the stack, also
display the popped numbers.
10. Write a recursive program to find GCD of 4,6,8.
11. Write a program to inert the elements {5,7,0,6,3,9} into circular queue and delete
6,9&5 from it (using linked list implementation).
12. Write a program to convert an infix expression x^y/(5*z)+2 to its postfix expression.
13. Write a program to evaluate a postfix expression 5 3+8 2 - *.
14. Write a program to create a binary tree with the elements {18,15,40,50,30,17,41}
after creation insert 45 and 19 into tree and delete 15,17 and 41 from tree. Display
the tree on each insertion and deletion operation.
15. Write a program to create binary search tree with the elements {2,5,1,3,9,0,6} and
perform inorder, preorder and post order traversal.
16. Write a program to Sort the following elements using heap sort {9.16,32,8,4,1,5,8,0}.
17. Given S1={“Flowers”} ; S2={“are beautiful”} I. Find the length of S1 II. Concatenate
S1 and S2 III. Extract the substring “low” from S1 IV. Find “are” in S2 and replace it
with “is”

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

1. Given {4,7,3,2,1,7,9,0} find the location of 7 using Linear and Binary search and also
display its first occurrence.

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

void lsearch(int [] , int); //3


int bsearch(int [], int); //9
void sortarray(int []) ; //6
void main() 1
{
int a[] = {4,7,3,2,1,7,9,0};

int i, S_ele = 7 ,B, loc;


printf("\n This program performs linear and binary search and first occurrence of the
element\n");
printf(" \n The input values of the array are\n");
for(i=0;i<=7;i++)
printf("\t %d", a[i]) ;
printf(" \n\nThe given element to be searched is %d", S_ele) ;
printf("\n \nPerforming linear search and finding the element 7\n") ;
lsearch(a , S_ele) ; //2
printf("\n\nSorting the array elements before applying Binary search") ;
sortarray(a) ; //5
printf("\n\n Performing Binary search and finding the element 7") ;
B= bsearch(a,S_ele) ; //8
printf(" \n\n The element's first occurrence is at the position %d", B+1) ;
}

void lsearch(int a[] ,int S_ele) //4


{
int i;
for(i=0;i<=7;i++)
{
if(a[i] == S_ele)
{
printf(" \n\nThe element 7 is found at the location %d", i + 1 ) ;
break;
}
}
}

void sortarray(int a[])//7


{

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

int i,j,temp;
for(i=0;i<8;i++)
{
for(j=i+1;j<8;j++)
{
if(a[i] > a[j])
{
temp = a[i];
a[i] = a[j] ;
a[j] = temp ;
}
}
}
printf("\n\n The sorted elements of the input array are:\n\n") ;
for(i=0;i<=7;i++)
printf("\t %d", a[i]) ;
}

int bsearch(int a[], int S_ele) //10


{
int beg=0, end = 8 , mid, result = -1;
mid = (beg + end) / 2;
while (beg <= end)
{
mid=(beg+end) / 2;
if(a[mid]==S_ele) // if search ele is middle
{
result = mid;
end = mid-1;
}
else if ( S_ele < a[mid]) //if the item to be searched is smaller than middle, then it can only
be in left subarray
end = mid - 1;
else //if the item to be searched is greater than middle, then it can only be in right subarrays
beg = mid + 1;
}
return result;
}

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

Output:

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

2. Given {5,3,1,6,0,2,4} order the numbers in ascending order using Bubble Sort
Algorithm.
#include <stdio.h>
int main()
{
int a[100], number, i, j, temp;
printf("\n Please Enter the total Number of Elements : ");
scanf("%d", &number);
printf("\n Please Enter the Array Elements : ");
for(i = 0; i < number; i++)
scanf("%d", &a[i]);
for(i = 0; i < number - 1; i++)
{
for(j = 0; j < number - i - 1; j++)
{
if(a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
printf("\n List Sorted in Ascending Order : ");
for(i = 0; i < number; i++)
{
printf(" %d \t", a[i]);
}
printf("\n");
return 0;
}

Output:

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

3. Perform the Insertion and Selection Sort on the input {75,8,1,16,48,3,7,0} and
display the output in descending order.

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

void selection_sort(int a[],int n);


void insertion_sort(int a[],int n);
int main()
{
int n,choice,i;
char ch[20];
printf("Enter no. of elements u want to sort : ");
scanf("%d",&n);
int arr[n];
for(i=0;i<n;i++)
{
printf("Enter %d Element : ",i+1);
scanf("%d",&arr[i]);
}
printf("Please select any option Given Below for Sorting : \n");
while(1)
{
printf("\n1. Selection Sort\n2. Insertion Sort\n3. Exit the Program.\n");
printf("\nEnter your Choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
selection_sort(arr,n);
break;

case 2:
insertion_sort(arr,n);
break;
case 3:
return 0;

default:
printf("\nPlease Select only 1-3 option ----\n");
}
}
return 0;
}

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

void display(int arr[],int n)


{
for(int i=0;i<n;i++)
{
printf(" %d ",arr[i]);
}
}
//------------------Selection Sort Function---------
void selection_sort(int arr[],int n)
{
int i,j,temp;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(arr[i]<arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
printf("After Selection sort Elements are : ");
display(arr,n);
}

//---------------Insertion Sort Function-------------------

void insertion_sort(int arr[],int n)


{

int i,j,min;
for(i=1;i<n;i++)
{
min=arr[i];
j=i-1;
while(min>arr[j] && j>=0)
{
arr[j+1]=arr[j];
j=j-1;
}
arr[j+1]=min;

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

}
printf("After Insertion sort Elements are : ");
display(arr,n);
}

Output:

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

4. Write a program to insert the elements {61,16,8,27} into singly linked list and delete
8,61,27 from the list. Display your list after each insertion and deletion.

#include <stdio.h>
#include <malloc.h> //calloc: static & malloc: dynamic
#include <stdlib.h>
struct node { int value;
struct node *next;
};
void insert();
void display();
void delete();
int count();
typedef struct node DATA_NODE;//renaming struct with new name
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 (1) //true in all ca
{
printf("\nOptions\n");
printf("1 : Insert into Linked List \n");
printf("2 : Delete from Linked List \n");
printf("3 : Display Linked List\n");
printf("Others : Exit()\n"); // printf(“case 4: exit()\n”);
printf("Enter your option:");
scanf("%d", &option);
switch (option)
{
case 1:
insert();
display(); break;
case 2:
delete(); display(); break;
case 3:
display(); break;
case 4: default:
exit(0);
}
}
return 0;
}
void insert()
{
printf("\nEnter Element for Insert Linked List : \n");

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

scanf("%d", &data);
temp_node = (DATA_NODE *) malloc(sizeof (DATA_NODE));
temp_node->value = data;
if (first_node == 0) //first node= header node
{
first_node = temp_node;
} else {
head_node->next = temp_node;
}
temp_node->next = 0;
head_node = temp_node;
fflush(stdin);
}
void delete()
{
Int countvalue, pos, i = 0;
countvalue = count();
temp_node = first_node;
printf("\nEnter Position for Delete Element : \n");
scanf("%d", &pos); //input pos=2;
if (pos> 0 &&pos<= countvalue) //(if (2>0 && 2<=4) true)
{
if (pos == 1)// (2==1) false//exit goto else
{
temp_node = temp_node -> next;
first_node = temp_node;
printf("\nDeleted Successfully \n\n");
} else
{
while (temp_node != 0)
{
if (i == (pos - 1)) //0==2-1false(0==1)
{
prev_node->next = temp_node->next;
if(i == (countvalue - 1))//0==4-1->0==3
{
head_node = prev_node;
}
printf("\nDeleted Successfully \n\n");
break;
} else {
i++;//i=1
prev_node = temp_node;
temp_node = temp_node -> next;
}
}
}

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

}
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\t ", 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;
}

Output:

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

5. Write a program to insert the elements {61,16,8,27} into linear queue and delete
three elements from the list. Display your list after each insertion and deletion.

#include <stdio.h>
#define MAX 20
#include<stdlib.h>
int queue_array[MAX];
int rear = - 1;
int front = - 1;
void insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty */
front = 0;
printf("\nEnter element : ");
scanf("%d", &add_item);
printf("\n%d is inserted in queue\n",add_item);
printf("------------------------------\n");
rear = rear + 1;
queue_array[rear] = add_item;
}
}
void delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("\nElement deleted from queue is : %d\n", queue_array[front]);
printf("------------------------------\n");
front = front + 1;
}
}
void display()
{
int i;

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

if (front == - 1)
printf("Queue is empty \n");
else
{
printf("\nQueue is : ");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n------------------------------");
printf("\n");
}
}
int main()
{
printf("Perform operations on queue\n");
printf("------------------------------\n");
printf("\tMenu");
printf("\n------------------------------\n");
printf("1. Insert element \n");
printf("2. Delete element \n");
printf("3. Display queue\n");
printf("4. Exit\n");
printf("------------------------------\n");
int ch;
while (1)
{
printf("Choose operation : ");
scanf("%d", &ch);
switch(ch)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Invalid operation \n");
}
}

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

return 0;
}

Output:

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

6. Write a program to insert the elements {61,16,8,27} into circular queue and delete
4 elements from the list. Display your list after each insertion and deletion.

#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
struct node *f = NULL;
struct node *r = NULL;
void enqueue(int d) //Insert elements in Queue
{
struct node* n;
n = (struct node*)malloc(sizeof(struct node));
n->data = d;
n->next = NULL;
if((r==NULL)&&(f==NULL))
{
f = r = n;
r->next = f;
}
else
{
r->next = n;
r = n;
n->next = f;
}
}
void dequeue() // Delete an element from Queue
{
struct node* t;
t = f;
if((f==NULL)&&(r==NULL))
printf("\nQueue is Empty");
else if(f == r){
f = r = NULL;
free(t);
}
else{
f = f->next;
r->next = f;
free(t);

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

}
}
void print(){ // Print the elements of Queue
struct node* t;
t = f;
if((f==NULL)&&(r==NULL))
printf("\nQueue is Empty");
else{
do{
printf("\n%d",t->data);
t = t->next;
}while(t != f);
}
}
int main()
{
int opt,n,i,data;
printf("Enter Your Choice:-");
do{
printf("\n\n1 for Insert the Data in Queue\n2 for show the Data in Queue \n3
for Delete the data from the Queue\n0 for Exit\n");
scanf("%d",&opt);
switch(opt){
case 1:
printf("\nEnter the size of data");
scanf("%d",&n);
printf("\nEnter your data");
i=0;
while(i<n){
scanf("%d",&data);
enqueue(data);
i++;
}
break;
case 2:
print();
break;
case 3:
dequeue();
break;
case 0:
break;
default:
printf("\nIncorrect Choice");

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

}
}while(opt!=0);
return 0;
}

Output:

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

7. Write a program to insert the elements {61,16,8,27} into ordered singly linked list
and delete 8,61,27 from the list. Display your list after each insertion and deletion.

#include <stdio.h>
#include <stdlib.h>
// Create a node
struct Node {
int data;
struct Node* next;
};
// Insertion operation
void insert(struct Node** head_ref, int new_data) {
// Allocate memory to a node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
// insert the data
new_node->data = new_data;
new_node->next = (*head_ref);
// Move head to new node
(*head_ref) = new_node;
}
// Delete a node
void deleteNode(struct Node** head_ref, int key) {
struct Node *temp = *head_ref, *prev;
if (temp != NULL && temp->data == key) {
*head_ref = temp->next;
free(temp);
return;
}
// Find the key to be deleted
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
// If the key is not present
if (temp == NULL) return;
// Remove the node
prev->next = temp->next;
free(temp);
}
// Sort the linked list
void sortLinkedList(struct Node** head_ref)
{
struct Node *current = *head_ref, *index = NULL;
int temp;

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

if (head_ref == NULL) {
return;
} else {
while (current != NULL) {
// index points to the node next to current
index = current->next;
while (index != NULL) {
if (current->data > index->data) {
temp = current->data;
current->data = index->data;
index->data = temp;
}
index = index->next;
}
current = current->next;
}
}
}
// Print the linked list
void printList(struct Node* node) {
while (node != NULL) {
printf(" %d ", node->data);
node = node->next;
}
}
// Driver program
int main() {
struct Node* head = NULL;

insert(&head, 27);
insert(&head, 8);
insert(&head, 16);
insert(&head, 61);

printf("Linked list: ");


printList(head);

sortLinkedList(&head);
printf("\nSorted List: ");
printList(head);

printf("\nAfter deleting an element: ");


deleteNode(&head, 8);

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

deleteNode(&head, 61);
deleteNode(&head, 27);
printList(head);

Output:

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

8. Write a program to add 6x3+10x2+0x+5 and 0x3+4x2+2x+1 using linked list.

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

struct Node
{
int coeff;
int pow;
struct Node* next;
};

void readPolynomial(struct Node** poly)


{
int coeff, exp, cont;
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
*poly = temp;
do{
printf("\n Coeffecient: ");
scanf("%d", &coeff);
printf("\n Exponent: ");
scanf("%d", &exp);
temp->coeff = coeff;
temp->pow = exp;
temp-> next = NULL;
printf("\nHave more terms? 1 for y and 0 for no: ");
scanf("%d", &cont);
if(cont)
{
temp->next = (struct Node*)malloc(sizeof(struct Node));
temp = temp->next;
temp->next = NULL;
}
}while(cont);
}

void displayPolynomial(struct Node* poly)


{
printf(" Polynomial expression is: ");
while(poly != NULL)
{
printf("%dX^%d", poly->coeff, poly->pow);
poly = poly->next;
if(poly != NULL)//6x^3 + 4x^2

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

printf("+");
}
}
void addPolynomials(struct Node** result, struct Node* first, struct Node* second)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->next = NULL;
*result = temp;
while(first && second)
{
if(first->pow> second->pow)
{
temp->coeff = first->coeff;
temp->pow = first->pow;
first = first->next;
}
else if(first->pow< second->pow)
{
temp->coeff = second->coeff;
temp->pow = second->pow;
second = second->next;
}
else
{
temp->coeff = first->coeff + second->coeff; 6x^3+0x^3//10x^2+4x^2//0x+2x//5+1
temp->pow = first->pow;//6x^3 + 14 x^2 + 2x + 6
first = first->next;
second = second->next;
}
if(first && second)
{
temp->next = (struct Node*)malloc(sizeof(struct Node));
temp = temp->next;
temp->next = NULL;
}
}
while(first || second)
{
temp->next = (struct Node*)malloc(sizeof(struct Node));
temp = temp->next;
temp->next = NULL;

if(first)
{

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

temp->coeff = first->coeff;
temp->pow = first->pow;
first = first->next;
}

else if(second)
{
temp->coeff = second->coeff;
temp->pow = second->pow;
second = second->next;
}
}
}
void main()
{
struct Node* first = NULL;
struct Node* second = NULL;
struct Node* result = NULL;
printf("\nEnter the corresponding data:-\n");
printf("\nFirst polynomial:\n");
readPolynomial(&first);
printf("\nFirst");
displayPolynomial(first);
printf("\nSecond polynomial:\n");
readPolynomial(&second); printf("\nSecond");
displayPolynomial(second);
addPolynomials(&result, first, second);
printf("\n\nAdded");
displayPolynomial(result);
}

Output:

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

9. Write a program to push 5,9,34,17,32 into stack and pop 3 times from the stack,
also display the popped numbers.

#include<stdio.h>
int stack[10],choice,n,top,x,i; // Declaration of variables

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

int main()
{
top = -1; // Initially there is no element in stack
printf("\n Enter the size of STACK : ");
scanf("%d",&n);
printf("\nSTACK IMPLEMENTATION\n");
do
{
printf("\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT\n");
printf("\nEnter the choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
break;
}
default:
{

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

printf ("\nInvalid Choice\n");


}}}
while(choice!=4);
return 0;
}
void push()
{
if(top >= n - 1)
{
printf("\nSTACK OVERFLOW\n");

}
else
{
printf("Enter a value to be pushed : ");
scanf("%d",&x);
top++; // TOP is incremented after an element is pushed
stack[top] = x; // The pushed element is made as TOP
}}
void pop()
{
if(top <= -1)
{
printf("\nSTACK UNDERFLOW\n");
}
else
{
printf("\nThe popped element is %d",stack[top]);
top--; // Decrement TOP after a pop
}}
void display()
{
if(top >= 0)
{
// Print the stack
printf("\nELEMENTS IN THE STACK\n\n");
for(i = top ; i >= 0 ; i--)
printf("%d\t",stack[i]);
}
else
{
printf("\nEMPTY STACK\n");
}
}

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

Output:

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

10. Write a recursive program to find GCD of 4,6,8.

#include<stdio.h>
#include<stdlib.h>
int gcd(int , int);
void main()
{
int a, b, c, gcd1,gcd2;
printf("\n\nEnter three numbers to find GCD of \n");
scanf("%d%d%d", &a, &b, &c);
if(a==0 && b==0 && c==0)
{
printf("\nInvalid number");
exit(0);
}
gcd1=gcd(a,b);
gcd2=gcd(c,gcd1);
printf("\n\nGCD of %d ,%d and %d is: %d\n\n", a, b, c,gcd2);}
//a=&x;b=&y//x=4,y=6//c=&x, gc1=&y
// defining the function
int gcd(int x, int y)// gcd(x,y)
{
if(x > y) //if(4>6)//if(8>2) true
gcd(x-y, y);gcd(8-2,2)//gcd(6,2)//2
else if(y > x)//(6>4)
gcd(x, y-x); //gcd(4,6-4)//gcd(4,2)//2
else
return x;
}
Output:

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

11. Write a program to insert the elements {5,7,0,6,3,9} into circular queue and delete
6, 9 & 5 from it (using linked list implementation).

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

struct queue
{
int info;
struct queue *link;
};
struct queue *front=NULL, *rear=NULL;

void qinsert(int item)


{
struct queue *newnode;
newnode=(struct queue*)malloc(sizeof(struct queue));
newnode -> info=item;
newnode -> link=NULL;
if(front == NULL && rear == NULL)
{
front=rear=newnode;
rear -> link= front;
}
else
{
rear -> link=newnode;
rear=newnode;
rear -> link = front;
}
}

void qdelete()
{
struct queue *ptr;
ptr = front;
if(front == NULL && rear == NULL)
printf("\n Queue is Empty");
else if(front == rear)
{
front=rear=NULL;
printf("The value being deleted is: %d",ptr -> info);

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

free(ptr);
}
else
{
front = front -> link;
rear -> link = front;
printf("The value being deleted is: %d",ptr -> info);
free(ptr);
}
}

void display()
{
struct queue *ptr;
ptr=front;
if(front == NULL && rear == NULL)
printf("\n Queue is Empty");
else
{
printf("\n The Queue Elements are:");
do
{
printf("%d",ptr -> info);
ptr = ptr -> link;
}
while(ptr != front);
}
}

void main()
{
int val, choice;
do
{
printf("\n*******MAIN MENU******");
printf("\n 1. Insert");
printf("\n 2. Delete");
printf("\n 3. Display");
printf("\n 4. Exit");
printf("\n Enter your choice");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter number to insert into queue");

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

scanf("%d",&val);
qinsert(val);
break;

case 2:
qdelete();
break;

case 3:
display();
break;

case 4:
exit(0);
break;
}
}while(choice != 4);
}

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

12. Write a program to convert an infix expression x^y/(5*z)+2 to its postfix expression.

#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 20

char stack[MAX];
int top=0;
char pop();
void push(char);
int prcd(char);
int isoperator(char);
void convertip(char [],char []);

void main()
{
char infix[20],postfix[20];

printf("Enter the valid infix string:\n");


gets(infix);
convertip(infix,postfix);
printf("The corresponding postfix string is: ");
puts(postfix);
getch();
}
void push(char item)
{
top++;
stack[top]=item;
}
char pop()
{
char a;
a=stack[top];
top--;
return a;
}
void convertip(char infix[],char postfix[])
{
int i,symbol,j=0;
stack[++top]='#';
for(i=0;i<strlen(infix);i++)
{

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

symbol=infix[i];
if(symbol=='(')
push(symbol);
else if(symbol==')')
{
while(stack[top]!='(')
{
postfix[j]=pop();
j++;
}
pop();//pop out (.
}
else if (isoperator(symbol)==1)
{
while(stack[top] != '#' && prcd(symbol)<=prcd(stack[top]))
{
postfix[j]=pop();
j++;
}
push(symbol);
}//end of else.
else if(isoperator(symbol)==0)
{
postfix[j]=symbol;
j++;
}
}//end of for.
while(stack[top]!='#')
{
postfix[j]=pop();
j++;
}
postfix[j]='\0';//null terminate string.
}
int prcd(char symbol)
{
if(symbol == '^' || symbol == '$')
return 6;
else if(symbol == '*' || symbol == '/')
return 4;
else if(symbol == '+' || symbol == '-')
return 2;
else if(symbol == '(' || symbol == ')' || symbol == '#')
return 1;

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

else
return 0;
}
int isoperator(char symbol)
{
if(symbol == '^' || symbol == '$' || symbol == '+' || symbol == '-' || symbol == '*' ||
symbol == '/' || symbol == '(' || symbol == ')')
return 1;
else
return 0;
}
Output:

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

13. Write a program to evaluate a postfix expression 5 3+8 2 - *.//(5+3)*(8-2)

#include<stdio.h>
#include<string.h>

float stack[20];
int top=0;
float pop();
void push(float);
int isoperator(char);
float evaluate(char []);
float calculate(float,char,float);

void main()
{
char postfix[20];
float solution;
printf("Enter the valid postfix string:\n");
gets(postfix);
solution = evaluate(postfix);
printf("The result value is : %f",solution);
}
void push(float item)
{
top++;
stack[top]=item;
}
float pop()
{
float a;
a=stack[top];
top--;
return a;
}
int isoperator(char symbol)
{
if(symbol == '+' || symbol == '-' || symbol == '*' || symbol == '/' )
return 1;
else
return 0;
}
float evaluate(char postfix[])
{
int i;

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

char symbol;
float oper1,oper2,result;
for(i=0;i<strlen(postfix);i++)
{
symbol = postfix[i];
if (isoperator(symbol)==0)
{
push(symbol-48);
}
else
{
oper2 = pop();
oper1 = pop();
result = calculate(oper1,symbol,oper2);
push(result);
}
}//end of for.
result = pop();
return(result);
}
float calculate(float oper1,char symbol,float oper2)
{
switch(symbol)
{
case '+' : return(oper1+oper2);
case '-' : return(oper1-oper2);
case '*' : return(oper1* oper2);
case '/' : return(oper1/oper2);
default : return(0);
}
}
Output:

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

14. Write a program to create a binary tree with the elements {18,15,40,50,30,17,41}
after creation insert 45 and 19 into tree and delete 15,17 and 41 from tree. Display
the tree on each insertion and deletion operation.

#include<stdio.h>

typedef struct node


{
struct node *left;
int info;
struct node *right;
}stype;
stype *root=NULL,*par,*cur,*newnode;
void main()
{
int choice,number;
do
{

printf("\n\t\tBinary Search Tree operations");


printf("\n1.Initializing BST to empty");
printf("\n2.Inserting an element into BST");
printf("\n3.Deleting an element from BST");
printf("\n4.Display the tree elements : ");
printf("\n5.Exit");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 : initialize();
break;
case 2 : printf("\nEnter number to insert into BST : ");
scanf("%d",&number);
insert(number);
break;
case 3 : printf("\nEnter number to delete from BST : ");
scanf("%d",&number);
delete_bst(number);
break;
case 4 : inorder(root);
break;
default : printf("\nProgram Terminated");
}
}

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

while(choice>0 && choice<5);


}
initialize()
{
root=NULL;
printf("\nThe Binary Search Tree is initialized");
return;
}
insert(int elem)
{
newnode=(stype *)malloc(sizeof(stype));
newnode->info=elem;
newnode->left=NULL;
newnode->right=NULL;
if(root == NULL)
root = newnode;
else
{
cur = root;
while(cur !=NULL)
{
par=cur;
if(elem<=cur->info)
cur=cur->left;
else
cur=cur->right;
}
if(elem<=par->info)
par->left=newnode;
else
par->right=newnode;
}
printf("\nThe element inserted into BST successfully");
return;
}
inorder(stype *root)
{
if(root!=NULL)
{
inorder(root->left);
printf("%4d",root->info);
inorder(root->right);
}
return;

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

}
delete_bst(int elem)
{
stype *temp;
if (root == NULL)
{
printf("\nTree is empty, hence deletion cannot be performed");
return;
}
cur = root;
par = NULL;
while(cur != NULL && cur->info !=elem)
{
par = cur;
if (elem <= (cur->info) )
cur = cur->left;
else
cur = cur->right;
}
if (cur == NULL)
{
printf("\nGiven element is not found in BST and hence it cannot be deleted");
return;
}
if ( cur == root )
{
if (cur->left == NULL && cur->right == NULL)
root = NULL;
else if (cur->left != NULL && cur->right == NULL)
root = root->left;
else if (cur->left == NULL && cur->right != NULL)
root = root->right;
else
{
temp = (root->left);
root = root->right;
cur = root;
while ( cur->left != NULL)
cur = cur->left;
cur->left = temp;
}
}
else
{

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

if ( cur->left == NULL && cur->right == NULL)


{
if( (cur->info) <= (par->info))
par->left = NULL;
else
par->right = NULL;
}
else if ( cur->left != NULL && cur->right == NULL)
{
if( (cur->info) <= (par->info))
par->left = cur->left;
else
par->right = cur->left;
}
else if ( cur->left == NULL && cur->right != NULL)
{
if( (cur->info) <= (par->info))
par->left = cur->right;
else
par->right = cur->right;
}
else
{
temp = (cur->left);
if( (cur->info) <= (par->info))
par->left = cur->right;
else
par->right = cur->right;
cur = (cur->right);
while( cur->left != NULL)
cur = cur->left;
cur->left = temp;
}
}
printf("\nThe element deleted from BST successfully");
return;
}

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

Output:

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

15. Write a program to create binary search tree with the elements {2,5,1,3,9,0,6} and
perform inorder, preorder and post order traversal.

#include<stdio.h>

typedef struct node


{
struct node *left;
int info;
struct node *right;
}stype;
stype *root=NULL,*par,*cur,*newnode;
void main()
{
int choice,number;
do
{
printf("\n\t\tBST Recursive Traversal Techniques");
printf("\n1.Initializing BST to empty");
printf("\n2.Inserting element into BST");
printf("\n3.Preorder Traversal");
printf("\n4.Inorder Traversal");
printf("\n5.Postorder Traversal");
printf("\n6.Exit");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 : initialize();
break;
case 2 : printf("\nEnter number to insert into BST : ");
scanf("%d",&number);
insert(number);
break;
case 3 : preorder(root);
break;
case 4 : inorder(root);
break;
case 5 : postorder(root);
break;
default : printf("\nProgram Terminated");
}
}
while(choice>0 && choice<6 );

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

}
initialize()
{
root=NULL;
printf("\nThe Binary Search Tree is initialized");
return;
}
insert(int elem)
{
newnode=(stype *)malloc(sizeof(stype));
newnode->info=elem;
newnode->left=NULL;
newnode->right=NULL;
if(root == NULL)
root = newnode;
else
{
cur = root;
while(cur != NULL)
{
par = cur;
if(elem<=cur->info)
cur=cur->left;
else
cur=cur->right;
}
if(elem<=par->info)
par->left=newnode;
else
par->right=newnode;
}
printf("\nThe element inserted into BST successfully");
return;
}
preorder(stype *root)
{
if(root!=NULL)
{
printf("%4d",root->info);
preorder(root->left);
preorder(root->right);
}
return;
}

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

inorder(stype *root)
{
if(root!=NULL)
{
inorder(root->left);
printf("%4d",root->info);
inorder(root->right);
}
return;
}
postorder(stype *root)
{
if(root!=NULL)
{
postorder(root->left);
postorder(root->right);
printf("%4d",root->info);
}
return;
}

Output:

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

16. Write a program to Sort the following elements using heap sort {9.16,32,8,4,1,5,8,0}.

#include<stdio.h>
int temp;
void heapify(int arr[], int size, int i)
{
int largest = i;
int left = 2*i + 1;
int right = 2*i + 2;
if (left < size && arr[left] >arr[largest])
largest = left;
if (right < size && arr[right] > arr[largest])
largest = right;
if (largest != i)
{
temp = arr[i];
arr[i]= arr[largest];
arr[largest] = temp;
heapify(arr, size, largest);
}
}
void heapSort(int arr[], int size)
{
int i;
for (i = size / 2 - 1; i >= 0; i--)
heapify(arr, size, i);
for (i=size-1; i>=0; i--)
{
temp = arr[0];
arr[0]= arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}
}
void main()
{
int arr[] = {9,16,32,8,4,1,5,8,0};
int i;
int size = sizeof(arr)/sizeof(arr[0]);
heapSort(arr, size);
printf("The sorted elements are : \n\n");
for (i=0; i<size; ++i)
printf("%d\n",arr[i]);
}

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

Output:

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

17. Given S1={“Flowers”} ; S2={“are beautiful”}


I. Find the length of S1.
II. Concatenate S1 and S2.
III. Extract the substring “low” from S1.
IV. Find “are” in S2 and replace it with “is”

I. Find the length of S1 without using library functions.

#include<stdio.h>
void main()
{
char str[100];
int len;
printf("\n\t\tENTER A STRING: ");
gets(str);
for(len=0;str[len]!=NULL;len++);
printf("\n\t\tTHE LENGTH OF THE STRING IS %d",len);
}
Output:

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

II. Concatenate S1 and S2 without using library functions.

#include<stdio.h>
#include<string.h>

void addstrings(char[], char[]);


int main()
{
char s1[50], s2[50];

printf("\n\t\t Enter String 1 : ");


gets(s1);
printf("\n\t\t Enter String 2 : ");
gets(s2);
addstrings(s1, s2);
printf("\nConcatenated string is : %s\t ", s1);

}
void addstrings(char s1[], char s2[]) {
int i, j;
i = strlen(s1);
for (j = 0; s2[j] != '\0'; i++, j++) {
s1[i] = s2[j];
}
s1[i] = '\0';
}
Output:

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

III. Extract the substring “low” from S1 without using library functions.

#include<stdio.h>
void main()
{
char str[100], sstr[100];
int pos, l, c = 0;
printf("\n\nExtract a substring from a given string:\n");
printf("--------------------------------------------\n");
printf("Input the string : ");
fgets(str, sizeof str, stdin);
printf("Input the position to start extraction :");
scanf("%d", &pos);
printf("Input the length of substring :");
scanf("%d", &l);
while (c < l)
{
sstr[c] = str[pos+c-1];
c++;
}
sstr[c] = '\0';
printf("The substring retrieve from the string is : %s \n", sstr);
}

Output:

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

IV. Find “are” in S2 and replace it with “is”

#include<stdio.h>
#include<string.h>

void replaceSubstring(char [],char[],char[]);


main()
{
char string[100],sub[100],new_str[100];
printf("\nEnter a string: ");
gets(string);
printf("\nEnter the substring: ");
gets(sub);
printf("\nEnter the new substring: ");
gets(new_str);
replaceSubstring(string,sub,new_str);
printf("\nThe string after replacing : %s\n",string);
}
void replaceSubstring(char string[],char sub[],char new_str[])
{
int stringLen,subLen,newLen;
int i=0,j,k;
int flag=0,start,end;
stringLen=strlen(string);
subLen=strlen(sub);
newLen=strlen(new_str);
for(i=0;i<stringLen;i++)
{
flag=0;
start=i;
for(j=0;string[i]==sub[j];j++,i++)
if(j==subLen-1)
flag=1;
end=i;
if(flag==0)
i-=j;
else
{
for(j=start;j<end;j++)
{
for(k=start;k<stringLen;k++)
string[k]=string[k+1];
stringLen--;
i--;

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

}
for(j=start;j<start+newLen;j++)
{
for(k=stringLen;k>=j;k--)
string[k+1]=string[k];
string[j]=new_str[j-start];
stringLen++;
i++;
}
}
}
}

Output:

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

int length(char *str)


{
int i=0;
while(str[i]!='\0')
i++;
return i;
}

void concat(char *str1, char *str2)


{
int i=0,j=0;
while(str1[i]='\0')
i++;

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

while(str2[i]='\0')
{
str1[i]=str2[i];
i++;
j++;
}
str1[i]='\0';
}

void substr(char str[], int pos, int len)


{
char sub[50];
int slen=length(str);
int p,j,max_ext;
if(pos>slen)
{
printf("Invalid Position");
return;
}
max_ext=slen-pos+1;
if(len > max_ext)
{
printf("Invalid SubString Length");
return;
}
p=pos-1;
for(j=0;j<len;j++)
{
sub[j]=str[p];
p++;
}
sub[j]='\0';
printf("\n SubString = %s",sub);
}

void replace(char str[], char substr[],char replacestr[])


{
char output[50];
int i=0,j=0,flag=0,start=0;
while(str[i] !='\0')
{
if(str[i] == substr[j])
{
if (!flag)

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

start = i;
j++;
if(substr[j]=='\0')
break;
flag=1;
}
else
{
flag=start=j=0;
}
i++;
}
if(substr[j] == '\0' && flag)
{
for(i=0;i<start;i++)
output[i]=str[i];
//replace substring with another string
for(j=0;j<length(replacestr);j++)
{
output[i]=replacestr[j];
i++;
}
//copy remaining portion of the input string
for(j=start+length(substr);j<length(str);j++)
{
output[i]=str[j];
i++;
}
//printf the final string
output[i]='\0';
printf("Output: %s\n",output);
}
else
printf("%s is not a substring of %s\n",substr,str);
}

void main()
{
char str1[100],str2[100],substr[100],repstr[100];
int len,pos,ch;
while(1)
{
printf("String Opeartions");
printf("\n****************************************");

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

printf("\n 1. String Length");


printf("\n 2. String Concatenation");
printf("\n 3. Extract a substring from a string");
printf("\n 4. Repalce a String");
printf("\n 5. Exit");
printf("\n Enter Your Choice");
scanf("%d",&ch);
fflush(stdin);
switch(ch)
{
case 1: printf("Enter a String:");
gets(str1);
printf("\n The length of a string is : %d",length(str1));
break;

case 2: printf("Enter first String:");


gets(str1);
printf("Enter second String:");
gets(str2);
concat(str1,str2);
printf("\n The Concetenation string is : %s",str1);
break;

case 3: printf("Enter the String:");


gets(str1);
printf("Enter position of a SubString:");
scanf("%d",&pos);
printf("Enter length of a SubString:");
scanf("%d",&len);
substr(str1,pos,len);
break;

case 4: printf("Enter the String:");


gets(str1);
printf("Enter the String to be removed:");
gets(substr);
printf("Enter the String to replace:");
fgets(repstr);
replace(str1,substr,repstr);

case 5: exit(0);
default: printf("Invalid Option");
break;
}

Department of Computer Applications


Data Structures Lab Prof. Diwakara Vasuman.M.S

}
}

Department of Computer Applications

You might also like