DS Lab
DS Lab
Submitted by:
Diwakara Vasuman.M.S
Assistant Professor, BCA Department
DSCASC
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>
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]) ;
}
Output:
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:
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>
case 2:
insertion_sort(arr,n);
break;
case 3:
return 0;
default:
printf("\nPlease Select only 1-3 option ----\n");
}
}
return 0;
}
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;
}
printf("After Insertion sort Elements are : ");
display(arr,n);
}
Output:
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");
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;
}
}
}
}
else
printf("\nInvalid Position \n\n");
}
void display()
{
int count = 0;
temp_node = first_node;
printf("\nDisplay Linked List : \n");
while (temp_node != 0)
{
Output:
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;
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");
}
}
return 0;
}
Output:
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);
}
}
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");
}
}while(opt!=0);
return 0;
}
Output:
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;
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);
sortLinkedList(&head);
printf("\nSorted List: ");
printList(head);
deleteNode(&head, 61);
deleteNode(&head, 27);
printList(head);
Output:
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int coeff;
int pow;
struct Node* next;
};
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)
{
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:
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:
{
}
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");
}
}
Output:
#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:
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 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);
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");
scanf("%d",&val);
qinsert(val);
break;
case 2:
qdelete();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
}
}while(choice != 4);
}
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];
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;
else
return 0;
}
int isoperator(char symbol)
{
if(symbol == '^' || symbol == '$' || symbol == '+' || symbol == '-' || symbol == '*' ||
symbol == '/' || symbol == '(' || symbol == ')')
return 1;
else
return 0;
}
Output:
#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;
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:
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>
}
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
{
Output:
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>
}
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;
}
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:
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]);
}
Output:
#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:
#include<stdio.h>
#include<string.h>
}
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:
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:
#include<stdio.h>
#include<string.h>
}
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>
while(str2[i]='\0')
{
str1[i]=str2[i];
i++;
j++;
}
str1[i]='\0';
}
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****************************************");
case 5: exit(0);
default: printf("Invalid Option");
break;
}
}
}