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

DSA Lab File

The document contains a lab record for Data Structures and Algorithms, detailing various programming exercises involving single and multi-dimensional arrays, as well as linked lists. Each program includes specific tasks such as searching, inserting, deleting, sorting arrays, and matrix operations, along with their respective code implementations. The document serves as a practical guide for students in the B. Tech. IT program during the 2020-21 academic session.

Uploaded by

Manan Singh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
2 views85 pages

DSA Lab File

The document contains a lab record for Data Structures and Algorithms, detailing various programming exercises involving single and multi-dimensional arrays, as well as linked lists. Each program includes specific tasks such as searching, inserting, deleting, sorting arrays, and matrix operations, along with their respective code implementations. The document serves as a practical guide for students in the B. Tech. IT program during the 2020-21 academic session.

Uploaded by

Manan Singh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 85

School of Computing & Information Technology

Department of Information Technology

LAB RECORD
DATA STRUCTURES AND ALGORITHMS LAB

199302163
Manan Singh

Program : B. Tech. Semester : III Semester IT

Session : 2020-21 Subject Code : IT2131


Lab 1.Single Dimensional Array

Program 1: Write a program to search an element in an array using linear


search technique. Write separate functions for reading the array, and for
searching the element in the array.

Code:

#include<stdio.h>

void read(int arr[] , int x)


{
printf("Enter array elements: ");
for(int i=0;i<x;++i)
{
scanf("%d",&arr[i]);
}
}

int search(int arr[] , int x , int y)


{
for(int i=0;i<x;++i)
{
if(arr[i]==y)
{
return i;
}
}
}

int main()
{
int a[20] , n , b , found;
printf("How many elements in the array? ");
scanf("%d",&n);
read(a , n);

printf("Enter element to search:");


scanf("%d",&b);
found = search(a , n , b);

if(found >= 0)
printf("Element found at index %d",found);
else
printf("Element not found");

return 0;
}

Execution:

Program 2: Write a program to search an element in an array using binary


search technique. Write separate functions for reading the array, and for
searching the element in the array.
Code:

#include<stdio.h>

void read(int arr[] , int x)


{
printf("Enter array elements: ");
for(int i=0;i<x;++i)
{
scanf("%d",&arr[i]);
}
}

int search(int arr[] , int x , int y)


{
int first = 0;
int last = x - 1;
int middle = (first+last)/2;

while (first <= last)


{
if(arr[middle] < y)
{
first = middle + 1;
}
else if (arr[middle] == y)
{
return middle;
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
}

int main()
{
int a[20] , n , b , found;
printf("How many elements in the array? ");
scanf("%d",&n);
read(a , n);

printf("Enter element to search:");


scanf("%d",&b);
found = search(a , n , b);

if(found >= 0)
printf("Element found at index %d",found);
else
printf("Element not found");
return 0;
}

Execution:

Program 3: Write a program to insert an integer in an array of N integers.


Write separate functions for reading the array, displaying the array and to
insert the element in the array.

Code:

#include <stdio.h>

int main()
{
int n;
printf("Enter no. of array elements:");
scanf("%d",&n);

int arr[n];

int i;

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

int pos;
printf("Enter pos to insert at:");
scanf("%d",&pos);
int ele;
printf("Enter element to insert:");
scanf("%d",&ele);

if(pos>n)
printf("Invalid Input");
else
{
for(i=n-1;i>=pos-1;i--)
arr[i+1]=arr[i];
arr[pos-1]=ele;

printf("Array after insertion is:\n");


for(i=0;i<=n;i++)
printf("%d\n",arr[i]);
}

return 0;
}

Execution:

Program 4: Write a program to delete an integer in an array of N integers.


Write separate functions for reading the array, displaying the array and to
delete the element from the array.
Code:

#include <stdio.h>

int main()
{
int array[100],position, c, n;
printf("Enter the number of elements of the array:");
scanf("%d", &n);

printf("\n Input the array elements:");


for(c=0; c<n; c++)
scanf("%d", &array[c]);

printf("\n Enter the position:");


scanf("%d", &position);

if(position>=n+1)
printf("\n Deletion not possible.\n");
else
{
for(c=position-1;c<n-1;c++)
array[c]=array[c+1];

printf("\n Array after deletion:");


for(c=0;c<n-1;c++)
printf("%d\n", array[c]);
}
return 0;
}

Execution:
Program 5: Write a program to sort an array of N integers using selection sort
technique. Write separate functions for reading the array, sorting the array
and to display the elements of the array.

Code :

#include<stdio.h>

void read(int arr[] , int x)


{
printf("Enter array elements: ");
for(int i=0;i<x;++i)
{
scanf("%d",&arr[i]);
}
}

void selsort(int arr[] , int x)


{
int pos, swap;
for (int i = 0; i < (x - 1); i++)
{
pos = i;
for (int j = i + 1; j < x; j++)
{
if (arr[pos] > arr[j])
pos = j;
}
if (pos != i)
{
swap = arr[i];
arr[i] = arr[pos];
arr[pos] = swap;
}
}
}

void display(int arr[] , int x)


{
for (int i = 0; i < x; i++)
{
printf("%d\t", arr[i]);
}
}

int main()
{
int a[20] , n , b , found;
printf("How many elements in the array? ");
scanf("%d",&n);
read(a , n);
selsort(a , n);
display(a , n);
}

Execution:
Program 6: Write a program to sort an array of N integers using bubble sort
technique. Write separate functions for reading the array, sorting the array
and to display the elements of the array.

Code:

#include<stdio.h>

void read(int arr[] , int x)


{
printf("Enter array elements: ");
for(int i=0;i<x;++i)
{
scanf("%d",&arr[i]);
}
}

void bubsort(int arr[] , int x)


{
int temp;
for (int i = 0; i < x-1; i++)
{
for (int j = 0; j < x-i-1; j++)
{
if (arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}

void display(int arr[] , int x)


{
for (int i = 0; i < x; i++)
{
printf("%d\t", arr[i]);
}
}

int main()
{
int a[20] , n , b , found;
printf("How many elements in the array? ");
scanf("%d",&n);
read(a , n);
bubsort(a , n);
display(a , n);
}

Execution:
Lab 2 & 3. Two Dimensional Array

Program1: Write a program to find the multiplication of two matrices. Write


separate functions for reading the matrix, displaying the matrix and to find the
multiplication of the matrices.

Code:
#include <stdio.h>
void read(int m1[][10], int m2[][10], int r1, int c1, int r2, int c2);
void multiply(int m1[][10], int m2[][10], int multResult[][10], int r1, int c1, int r2,
int c2);
void display(int mult[][10], int r1, int c2);
int main()
{
int m1[10][10], m2[10][10], mult[10][10], r1, c1, r2, c2, i, j, k;
printf("Enter rows and column for first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and column for second matrix: ");
scanf("%d %d", &r2, &c2);
while (c1 != r2)
{
printf("Error! column of first matrix not equal to row of second.\n");
printf("Enter rows and column for first matrix: ");
scanf("%d%d", &r1, &c1);
printf("Enter rows and column for second matrix: ");
scanf("%d%d", &r2, &c2);
}

read(m1, m2, r1, c1, r2, c2);


multiply(m1, m2, mult, r1, c1, r2, c2);
display(mult, r1, c2);
return 0;
}
void read(int m1[][10], int m2[][10], int r1, int c1, int r2, int c2)
{
int i, j;
printf("\nEnter elements of matrix 1:\n");
for(i = 0; i < r1; ++i)
{
for(j = 0; j < c1; ++j)
{
printf("Enter elements a%d%d: ", i + 1, j + 1);
scanf("%d", &m1[i][j]);
}
}

printf("\nEnter elements of matrix 2:\n");


for(i = 0; i < r2; ++i)
{
for(j = 0; j < c2; ++j)
{
printf("Enter elements b%d%d: ", i + 1, j + 1);
scanf("%d", &m2[i][j]);
}
}
}

void multiply(int m1[][10], int m2[][10], int mult[][10], int r1, int c1, int r2, int c2)
{
int i, j, k;

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


{
for(j = 0; j < c2; ++j)
{
mult[i][j] = 0;
}
}
for(i = 0; i < r1; ++i)
{
for(j = 0; j < c2; ++j)
{
for(k=0; k<c1; ++k)
{
mult[i][j] += m1[i][k] * m2[k][j];
}
}
}
}
void display(int mult[][10], int r1, int c2)
{
int i, j;
printf("\nOutput Matrix:\n");
for(i = 0; i < r1; ++i)
{
for(j = 0; j < c2; ++j)
{
printf("%d ", mult[i][j]);
if(j == c2 - 1)
printf("\n\n");
}
}
}
Execution:
Program2: Write a program to find the transpose of a matrix. Write separate
functions for reading, displaying and to find the transpose of the matrix.
Code:
#include <stdio.h>

void read(int m1[][10], int r1, int c1);


void transpose(int m1[][10], int transResult[][10], int r1, int c1);
void display(int trans[][10], int r1, int c2);

int main()
{
int m1[10][10], trans[10][10], r1, c1, i, j;

printf("Enter rows and column for first matrix: ");


scanf("%d %d", &r1, &c1);

read(m1,r1, c1);

transpose(m1, trans, r1, c1);

display(trans, r1, c1);

return 0;
}

void read(int m1[][10], int r1, int c1)


{
int i, j;
printf("\nEnter elements of matrix 1:\n");
for(i = 0; i < r1; ++i)
{
for(j = 0; j < c1; ++j)
{
printf("Enter elements a%d%d: ", i + 1, j + 1);
scanf("%d", &m1[i][j]);
}
}

void transpose(int m1[][10], int trans[][10], int r1, int c1)


{
int i, j, k;

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


for (j = 0; j < c1; ++j) {
trans[j][i] = m1[i][j];
}
}

void display(int trans[][10], int r1, int c1)


{
printf("\nTranspose of the matrix:\n");
for (int i = 0; i < c1; ++i)
for (int j = 0; j < r1; ++j) {
printf("%d ", trans[i][j]);
if (j == r1 - 1)
printf("\n");
}
}

Execution:

Program3: Write a program to find check whether the matrix is upper triangular
or not. Write separate functions for reading the matrix and to check whether the
matrix is upper triangular or not.
Code:
#include<stdio.h>

void read(int m1[][10],int n)


{
int i, j;
printf("\nEnter elements of matrix 1:\n");
for(i = 0; i < n; ++i)
{
for(j = 0; j < n; ++j)
{
printf("Enter elements a%d%d: ", i + 1, j + 1);
scanf("%d", &m1[i][j]);
}
}
}

int find_upper(int m1[][10] , int n)


{
int flag=0;
{
for (int i = 1; i < n; i++)
for (int j = 0; j < i; j++)
if (m1[i][j] != 0)
return 0;
}
return 1;
}

int main()
{
int m1[10][10],n, i, j,flag;

printf("Enter rows for matrix: ");


scanf("%d" , &n);
read(m1,n);

flag=find_upper(m1,n);

if(flag == 1)
printf(" upper triangular matrix");
else
printf("not upper triangular matrix");

return 0;
}

Execution:

Program4: Write a program to find check whether the matrix is lower


triangular or not. Write separate functions for reading the matrix and to check
whether the matrix is lower triangular or not.
Code:
#include<stdio.h>
void read(int m1[][10],int n)
{
int i, j;
printf("\nEnter elements of matrix 1:\n");
for(i = 0; i < n; ++i)
{
for(j = 0; j < n; ++j)
{
printf("Enter elements a%d%d: ", i + 1, j + 1);
scanf("%d", &m1[i][j]);
}
}
}

int find_lower(int m1[][10] , int n)


{
int flag=0;
{
for (int i = 0; i < n; i++)
for (int j = i+1; j < n; j++)
if (m1[i][j] != 0)
return 0;

}
return 1;
}
int main()
{
int m1[10][10],n, i, j,flag;

printf("Enter rows for matrix: ");


scanf("%d" , &n);

read(m1,n);
flag=find_lower(m1,n);

if(flag == 1)
printf(" lower triangular matrix");
else
printf("not lower triangular matrix");

return 0;
}

Execution:
Lab 4 & 5 : Linked List
Program 1: Write a program to perform following operations on the singly
linked list : Inserting a node (at the start, at the end, in between), deleting a
node (starting node, last node, in between node), displaying information
stored in the nodes. Write separate functions for each of the operations.

Code:

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

//creating node
struct node {
int data;
struct node *link;
};

struct node *head;

//inserting a node at the beginning


void add_at_beg() {
struct node *ptr = (struct node *) malloc(sizeof(struct node *));
int data;

if(ptr == NULL) {
printf("\nOVERFLOW");
}

else {
printf("\nEnter value\n");
scanf("%d",&data);
ptr->data = data;
ptr->link = head;
head = ptr;
printf("\nNode inserted");
}
}
//inserting a node at the end
void add_at_end() {
struct node *temp,*ptr;

int data;
temp = (struct node*)malloc(sizeof(struct node));

if(temp == NULL) {
printf("\nOVERFLOW");
}

else {
printf("\nEnter value?\n");
scanf("%d",&data);
temp->data = data;

if(head == NULL) {
temp -> link = NULL;
head = temp;
printf("\nNode inserted");
}
else {
ptr = head;

//
while (ptr -> link != NULL) {
ptr = ptr -> link;
}
ptr->link = temp;
temp->link = NULL;
printf("\nNode inserted");
}
}
}

//inserting a node after a specific position


void add_at_pos() {
int i,loc,data;
struct node *temp, *ptr;
temp = (struct node *) malloc (sizeof(struct node));
if(temp == NULL) {
printf("\nOVERFLOW");
}
else {
printf("\nEnter element value");
scanf("%d",&data);
temp->data = data;
printf("\nEnter the location after which you want to insert ");
scanf("\n%d",&loc);
ptr=head;

for(i=0;i<loc;i++) {
ptr = ptr->link;
if(ptr == NULL) {
printf("\ncan't insert\n");
return;
}
}
temp ->link = ptr ->link;
ptr ->link = temp;
printf("\nNode inserted");
}
}

//deleting a node from the beginning


void del_from_beg() {
struct node *ptr;
if(head == NULL) {
printf("\nList is empty\n");
}
else {
ptr = head;
head = ptr->link;
free(ptr);
printf("\nNode deleted from the begining ...\n");
}
}

//deleting a node from the end


void del_from_end() {
struct node *ptr,*ptr1;
if(head == NULL) {
printf("\nlist is empty");
}
else if(head -> link == NULL) {
head = NULL;
free(head);
printf("\nOnly node of the list deleted ...\n");
}
else {
ptr = head;
while(ptr->link != NULL) {
ptr1 = ptr;
ptr = ptr ->link;
}
ptr1->link = NULL;
free(ptr);
printf("\nDeleted Node from the last ...\n");
}
}

//deleting a node after a specific position


void del_from_pos() {
struct node *ptr,*ptr1;
int loc,i;
printf("\n Enter the location of the node after which you want to perform
deletion \n");
scanf("%d",&loc);
ptr=head;
for(i=0;i<loc;i++) {
ptr1 = ptr;
ptr = ptr->link;
if(ptr == NULL) {
printf("\nCan't delete");
return;
}
}
ptr1 ->link = ptr ->link;
free(ptr);
printf("\nDeleted node %d ",loc+1);
}

//display linked list


void display() {
struct node *ptr;
ptr = head;
if(ptr == NULL) {
printf("Nothing to print");
}
else {
printf("\nprinting values :-\n");
while (ptr!=NULL) {
printf("\n%d",ptr->data);
ptr = ptr -> link;
}
}
}

void main () {

int operation =0;

while(operation != 8) {
printf("\n\n====== Program 1: Operations on singly linked list ======\n");
printf("\nChoose an operation from the following list :-\n");
printf("\n===============================================\n");
printf("\n1.Insert at begining\n2.Insert at end\n3.Insert at a specific
location\n4.Delete from Beginning\n5.Delete from end\n6.Delete node at a
specific location\n7.Show\n8.Exit\n");
printf("\nEnter your operation\n");
scanf("\n%d",&operation);

switch(operation) {
case 1:
add_at_beg();
break;

case 2:
add_at_end();
break;
case 3:
add_at_pos();
break;

case 4:
del_from_beg();
break;

case 5:
del_from_end();
break;

case 6:
del_from_pos();
break;

case 7:
display();
break;

case 8:
exit(0);
break;

default:
printf("Please enter valid operation..");
}
}
}

Execution:
Program 2: Write a program to perform following operations on the circular
linked list : Inserting a node (at the start, at the end), deleting a node (starting
node, last node, in), displaying information stored in the nodes. Write
separate functions for each of the operations.

Code:

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

struct node {
struct node *prev;
struct node *next;
int data;
};

struct node *head;

void insertion_beginning() {
struct node *ptr,*temp;
int item;
ptr = (struct node *)malloc(sizeof(struct node));

if(ptr == NULL) {
printf("\nOVERFLOW");
}
else {
printf("\nEnter Item value");
scanf("%d",&item);
ptr->data=item;
if(head==NULL) {
head = ptr;
ptr -> next = head;
ptr -> prev = head;
}
else {
temp = head;
while(temp -> next != head) {
temp = temp -> next;
}
temp -> next = ptr;
ptr -> prev = temp;
head -> prev = ptr;
ptr -> next = head;
head = ptr;
}
printf("\nNode inserted\n");
}
}

void insertion_last() {
struct node *ptr,*temp;
int item;
ptr = (struct node *) malloc(sizeof(struct node));
if(ptr == NULL) {
printf("\nOVERFLOW");
}
else {
printf("\nEnter value");
scanf("%d",&item);
ptr->data=item;
if(head == NULL) {
head = ptr;
ptr -> next = head;
ptr -> prev = head;
}
else {
temp = head;
while(temp->next !=head) {
temp = temp->next;
}
temp->next = ptr;
ptr ->prev=temp;
head -> prev = ptr;
ptr -> next = head;
}
}
printf("\nnode inserted\n");
}

void deletion_beginning() {
struct node *temp;
if(head == NULL) {
printf("\n UNDERFLOW");
}
else if(head->next == head) {
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else {
temp = head;
while(temp -> next != head) {
temp = temp -> next;
}
temp -> next = head -> next;
head -> next -> prev = temp;
free(head);
head = temp -> next;
}
}

void deletion_last() {
struct node *ptr;
if(head == NULL) {
printf("\n UNDERFLOW");
}
else if(head->next == head) {
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else {
ptr = head;
if(ptr->next != head) {
ptr = ptr -> next;
}
ptr -> prev -> next = head;
head -> prev = ptr -> prev;
free(ptr);
printf("\nnode deleted\n");
}
}

void display() {
struct node *ptr;
ptr=head;
if(head == NULL) {
printf("\nnothing to print");
}
else {
printf("\n printing values ... \n");
while(ptr -> next != head) {
printf("%d\n", ptr -> data);
ptr = ptr -> next;
}
printf("%d\n", ptr -> data);
}
}

void main () {
int operation =0;

while(operation != 6) {
printf("\n\n====== Program 2: Operations on circular linked list ======\
n");
printf("\nChoose an operation from the following list :-\n");
printf("\n===============================================\n");
printf("\n1.Insert in Beginning\n2.Insert at last\n3.Delete from Beginning\
n4.Delete from last\n5.Show\n6.Exit\n");
printf("\nEnter your operation\n");
scanf("\n%d",&operation);
switch(operation) {
case 1:
insertion_beginning();
break;

case 2:
insertion_last();
break;

case 3:
deletion_beginning();
break;

case 4:
deletion_last();
break;

case 5:
display();
break;

case 6:
exit(0);
break;

default:
printf("Please enter valid operation..");
}
}
}
Execution:
Program 3: Write a program to perform following operations on the doubly
linked list : Inserting a node (at the start, at the end, in between), deleting a
node (starting node, last node, in between node), displaying information
stored in the nodes. Write separate functions for each of the operations.

Code:

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

struct node {
struct node *prev;
struct node *next;
int data;
};

struct node *head;

void insertion_beginning() {
struct node *ptr;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL) {
printf("\nOVERFLOW");
}
else {
printf("\nEnter Item value");
scanf("%d",&item);
if(head==NULL) {
ptr->next = NULL;
ptr->prev=NULL;
ptr->data=item;
head=ptr;
}
else {
ptr->data=item;
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
}
printf("\nNode inserted\n");
}
}

void insertion_last() {
struct node *ptr,*temp;
int item;
ptr = (struct node *) malloc(sizeof(struct node));
if(ptr == NULL) {
printf("\nOVERFLOW");
}
else {
printf("\nEnter value");
scanf("%d",&item);
ptr->data=item;
if(head == NULL) {
ptr->next = NULL;
ptr->prev = NULL;
head = ptr;
}
else {
temp = head;
while(temp->next!=NULL) {
temp = temp->next;
}
temp->next = ptr;
ptr ->prev=temp;
ptr->next = NULL;
}
}
printf("\nnode inserted\n");
}

void insertion_specified() {
struct node *ptr,*temp;
int item,loc,i;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL) {
printf("\n OVERFLOW");
}
else {
temp=head;
printf("Enter location after which we insert:");
scanf("%d",&loc);
for(i=0;i<loc;i++) {
temp = temp->next;
if(temp == NULL) {
printf("\n There are less than %d elements", loc);
return;
}
}
printf("Enter value");
scanf("%d",&item);
ptr->data = item;
ptr->next = temp->next;
ptr -> prev = temp;
temp->next = ptr;
temp->next->prev=ptr;
printf("\nnode inserted\n");
}
}

void deletion_beginning() {
struct node *ptr;
if(head == NULL) {
printf("\n UNDERFLOW");
}
else if(head->next == NULL) {
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else {
ptr = head;
head = head -> next;
head -> prev = NULL;
free(ptr);
printf("\nnode deleted\n");
}
}

void deletion_last() {
struct node *ptr;
if(head == NULL) {
printf("\n UNDERFLOW");
}
else if(head->next == NULL) {
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else {
ptr = head;
if(ptr->next != NULL) {
ptr = ptr -> next;
}
ptr -> prev -> next = NULL;
free(ptr);
printf("\nnode deleted\n");
}
}

void deletion_specified() {
struct node *ptr, *temp;
int val;
printf("\n Enter the data after which the node is to be deleted : ");
scanf("%d", &val);
ptr = head;
while(ptr -> data != val)
ptr = ptr -> next;
if(ptr -> next == NULL) {
printf("\nCan't delete\n");
}
else if(ptr -> next -> next == NULL) {
ptr ->next = NULL;
}
else {
temp = ptr -> next;
ptr -> next = temp -> next;
temp -> next -> prev = ptr;
free(temp);
printf("\nnode deleted\n");
}
}

void display() {
struct node *ptr;
printf("\n printing values...\n");
ptr = head;
while(ptr != NULL) {
printf("%d\n",ptr->data);
ptr=ptr->next;
}
}

void main () {
int operation =0;

while(operation != 6) {
printf("\n\n====== Program 3: Operations on doubly linked list ======\
n");
printf("\nChoose an operation from the following list :-\n");
printf("\n===============================================\n");
printf("\n1.Insert in begining\n2.Insert at last\n3.Insert at any random
location\n4.Delete from Beginning\n5.Delete from last\n6.Delete the node
after the given data\n7.Show\n8.Exit\n");
printf("\nEnter your operation?\n");
scanf("\n%d",&operation);

switch(operation) {
case 1:
insertion_beginning();
break;

case 2:
insertion_last();
break;

case 3:
insertion_specified();
break;

case 4:
deletion_beginning();
break;

case 5:
deletion_last();
break;

case 6:
deletion_specified();
break;

case 7:
display();
break;

case 8:
exit(0);
break;

default:
printf("Please enter valid operation..");
}
}
}
Execution:
Lab 6 & 7 : Stack
Program 1: Write a program to implement stack using array. Write separate
functions for the following operations on stack: Push (inserting element), Pop
(deleting element).

Code:

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

struct Stack {
int top;
unsigned capacity;
int* array;
};

struct Stack* createStack(unsigned capacity) {


struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array = (int*)malloc(stack->capacity * sizeof(int));
return stack;
}

int isFull(struct Stack* stack) {


return stack->top == stack->capacity - 1;
}

int isEmpty(struct Stack* stack) {


return stack->top == -1;
}

void push(struct Stack* stack, int item) {


if (isFull(stack))
return;
stack->array[++stack->top] = item;
printf("%d pushed to stack\n", item);
}

int pop(struct Stack* stack) {


if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top--];
}

int main(){
struct Stack* stack = createStack(100);
push(stack, 45);
push(stack, 67);
printf("%d popped from stack\n", pop(stack));
return 0;
}

Execution:

Program 2: Write a program to implement stack using linked list. Write


separate functions for the following operations on stack : Push (inserting
element), Pop (deleting element).

Code:

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

struct StackNode {
int data;
struct StackNode* next;
};

struct StackNode* newNode(int data){


struct StackNode* stackNode = (struct StackNode*)malloc(sizeof(struct
StackNode));
stackNode->data = data;
stackNode->next = NULL;
return stackNode;
}

int isEmpty(struct StackNode* root){


return !root;
}

void push(struct StackNode** root, int data){


struct StackNode* stackNode = newNode(data);
stackNode->next = *root;
*root = stackNode;
printf("%d pushed to stack\n", data);
}

int pop(struct StackNode** root){


if (isEmpty(*root))
return INT_MIN;
struct StackNode* temp = *root;
*root = (*root)->next;
int popped = temp->data;
free(temp);
return popped;
}

int main(){
struct StackNode* root = NULL;
push(&root, 73);
push(&root, 48);
printf("%d popped from stack\n", pop(&root));
return 0;
}

Execution:
Program 3: Write a program to convert an expression from infix notation to
postfix notation.

Code:

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

struct Stack{
int top;
unsigned capacity;
int* array;
};

struct Stack* createStack( unsigned capacity ){


struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
if (!stack)
return NULL;
stack->top = -1;
stack->capacity = capacity;
stack->array = (int*) malloc(stack->capacity *
sizeof(int));
return stack;
}

int isEmpty(struct Stack* stack){


return stack->top == -1 ;
}

char peek(struct Stack* stack){


return stack->array[stack->top];
}

char pop(struct Stack* stack){


if (!isEmpty(stack))
return stack->array[stack->top--] ;
return '$';
}

void push(struct Stack* stack, char op){


stack->array[++stack->top] = op;
}

int isOperand(char ch){


return (ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z');
}

int Prec(char ch){


switch (ch){
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}

int infixToPostfix(char* exp){


int i, k;
struct Stack* stack = createStack(strlen(exp));
if(!stack) // See if stack was created successfully
return -1 ;

for (i = 0, k = -1; exp[i]; ++i){


if (isOperand(exp[i]))
exp[++k] = exp[i];
else if (exp[i] == '(')
push(stack, exp[i]);
else if (exp[i] == ')'){
while (!isEmpty(stack) && peek(stack) != '(')
exp[++k] = pop(stack);
if (!isEmpty(stack) && peek(stack) != '(')
return -1; // invalid expression
else
pop(stack);
}
else{ // an operator is encountered
while (!isEmpty(stack) &&
Prec(exp[i]) <= Prec(peek(stack)))
exp[++k] = pop(stack);
push(stack, exp[i]);
}
}
while (!isEmpty(stack))
exp[++k] = pop(stack );
exp[++k] = '\0';
printf( "%s", exp );
}

int main(){
char exp[] = "a+b*(c^d-e)^(f+g*h)-i";
infixToPostfix(exp);
return 0;
}

Execution:

Program 4: Write a program to evaluate an expression in postfix notation.

Code:

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

// Stack type
struct Stack{
int top;
unsigned capacity;
int* array;
};

// Stack Operations
struct Stack* createStack( unsigned capacity ){
struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));
if (!stack) return NULL;
stack->top = -1;
stack->capacity = capacity;
stack->array = (int*) malloc(stack->capacity * sizeof(int));
if (!stack->array) return NULL;
return stack;
}

int isEmpty(struct Stack* stack){


return stack->top == -1 ;
}

char peek(struct Stack* stack){


return stack->array[stack->top];
}

char pop(struct Stack* stack){


if (!isEmpty(stack))
return stack->array[stack->top--] ;
return '$';
}

void push(struct Stack* stack, char op){


stack->array[++stack->top] = op;
}
int evaluatePostfix(char* exp){
// Create a stack of capacity equal to expression size
struct Stack* stack = createStack(strlen(exp));
int i;
if (!stack) return -1;
for (i = 0; exp[i]; ++i){
if (isdigit(exp[i]))
push(stack, exp[i] - '0');
else{
int val1 = pop(stack);
int val2 = pop(stack);
switch (exp[i]){
case '+': push(stack, val2 + val1); break;
case '-': push(stack, val2 - val1); break;
case '*': push(stack, val2 * val1); break;
case '/': push(stack, val2/val1); break;
}
}
}
return pop(stack);
}

int main(){
char exp[] = "243*+31-";
printf ("postfix evaluation: %d", evaluatePostfix(exp));
return 0;
}

Execution:
Lab 8 : Queue
Program 1: Write a program to implement simple queue using array. Write
separate functions for the following operations on queue : Enqueue (inserting
element), Dequeue (deleting element).

Code:

#include<stdio.h>
#include<stdlib.h>
#define maxsize 5

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

int front = -1, rear = -1;


int queue[maxsize];

void main () {

int operation;

while(operation != 4) {
printf("\n\n====== Program 1: Operations on singly linked list ======\n");
printf("\nChoose an operation from the following list :-\n");
printf("\n===============================================\n");
printf("\n1.insert an element\n2.Delete an element\n3.Display the queue\
n4.Exit\n");
printf("\nEnter your operation\n");
scanf("%d",&operation);

switch(operation) {
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\nEnter valid operation??\n");
}
}
}

void insert() {
int data;
printf("\nEnter the element\n");
scanf("\n%d",&data);
if(rear == maxsize-1) {
printf("\nOVERFLOW\n");
return;
}
if(front == -1 && rear == -1) {
front = 0;
rear = 0;
}
else {
rear = rear+1;
}
queue[rear] = data;
printf("Value inserted ");
}

void delete() {
int data;
if (front == -1 || front > rear) {
printf("\nUNDERFLOW\n");
return;
}
else {
data = queue[front];
if(front == rear) {
front = -1;
rear = -1 ;
}
else {
front = front + 1;
}
printf("\nvalue deleted ");
}
}

void display() {
int i;
if(rear == -1) {
printf("\nEmpty queue\n");
}
else {
printf("\nprinting values:\n");
for(i=front;i<=rear;i++) {
printf("%d\n",queue[i]);
}
}
}
Execution:
Program 2: Write a program to implement circular queue using linked list.
Write separate functions for the following operations on queue : Enqueue
(inserting element), Dequeue (deleting element).

Code:

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

struct node {
int data;
struct node *next;
};

struct node *front=-1;


struct node *rear=-1;

void enqueue(int x) {
struct node *newnode;
newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=x;
newnode->next=0;
if(rear==-1) {
front=rear=newnode;
rear->next=front;
}
else {
rear->next=newnode;
rear=newnode;
rear->next=front;
}
}

void dequeue() {
struct node *temp;
temp=front;
if((front==-1)&&(rear==-1)) {
printf("\nQueue is empty");
}
else if(front==rear) {
front=rear=-1;
free(temp);
}
else {
front=front->next;
rear->next=front;
free(temp);
}
}

int peek() {
if((front==-1) &&(rear==-1)) {
printf("\nQueue is empty");
}
else {
printf("\nThe front element after dequeue operation is %d", front->data);
}
}
void display() {
struct node *temp;
temp=front;
printf("\nThe elements in a Queue are : ");
if((front==-1) && (rear==-1)) {
printf("Queue is empty");
}
else {
while(temp->next!=front) {
printf("%d,", temp->data);
temp=temp->next;
}
printf("%d", temp->data);
}
}

void main() {
enqueue(98);
enqueue(666);
enqueue(37);
display();
dequeue();
peek();
}

Execution:
Lab 9 & 10 : Trees
Program 1: Write a program to implement binary search tree. Write separate functions for
each of the following operations on binary search tree: Creating Binary Search
Tree, Inserting a node in the tree, Deleting a node from the tree.

Code:

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

typedef struct node {


int data;
struct node *left;
struct node *right;
struct node *parent;
}

node;
typedef struct binary_search_tree {
node *root;
}
binary_search_tree;

node* new_node(int data) {


node *n = malloc(sizeof(node));
n->data = data;
n->left = NULL;
n->right = NULL;
n->parent = NULL;
return n;
}

binary_search_tree* new_binary_search_tree() {
binary_search_tree *t = malloc(sizeof(binary_search_tree));
t->root = NULL;
return t;
}

node* minimum(binary_search_tree *t, node *x) {


while(x->left != NULL)
x = x->left;
return x;
}

void insert(binary_search_tree *t, node *n) {


node *y = NULL;
node *temp = t->root;
while(temp != NULL) {
y = temp;
if(n->data < temp->data)
temp = temp->left;
else
temp = temp->right;
}
n->parent = y;
if(y == NULL)
t->root = n;
else if(n->data < y->data)
y->left = n;
else
y->right = n;
}

void transplant(binary_search_tree *t, node *u, node *v) {


if(u->parent == NULL)
t->root = v;
else if(u == u->parent->left)
u->parent->left = v;
else
u->parent->right = v;
if(v != NULL)
v->parent = u->parent;
}

void delete(binary_search_tree *t, node *z) {


if(z->left == NULL) {
transplant(t, z, z->right);
free(z);
}
else if(z->right == NULL) {
transplant(t, z, z->left);
free(z);
}
else {
node *y = minimum(t, z->right);
if(y->parent != z) {
transplant(t, y, y->right);
y->right = z->right;
y->right->parent = y;
}
transplant(t, z, y);
y->left = z->left;
y->left->parent = y;
free(z);
}
}

void inorder(binary_search_tree *t, node *n) {


if(n != NULL) {
inorder(t, n->left);
printf("%d\n", n->data);
inorder(t, n->right);
}
}

int main() {
binary_search_tree *t = new_binary_search_tree();
node *a, *b, *c, *d, *e, *f, *g, *h, *i, *j, *k, *l, *m;
a = new_node(15);
b = new_node(200);
c = new_node(30);
d = new_node(100);
e = new_node(90);
f = new_node(45);
g = new_node(500);
h = new_node(60);
i = new_node(1);
j = new_node(10);
k = new_node(150);
l = new_node(250);
m = new_node(120);
insert(t, a);
insert(t, b);
insert(t, c);
insert(t, d);
insert(t, e);
insert(t, f);
insert(t, g);
insert(t, h);
insert(t, i);
insert(t, j);
insert(t, k);
insert(t, l);
insert(t, m);
delete(t, e);
delete(t, f);
inorder(t, t->root);
return 0;
}

Execution:
Program 2: Write a program to traverse a binary search tree in pre-order, post-
order and in-order.

Code:

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

enum Traversal {PREORDER, INORDER, POSTORDER};


typedef enum Traversal Traversal;
typedef struct Node Node;

struct Node {
int value;
Node* left, *right;
};

Node* init_tree(int data) {


Node* root = (Node*) malloc (sizeof(Node));
root->left = root->right = NULL;
root->value = data;
return root;
}

Node* create_node(int data) {


Node* node = (Node*) malloc (sizeof(Node));
node->value = data;
node->left = node->right = NULL;
return node;
}

void free_tree(Node* root) {


Node* temp = root;
if (!temp)
return;
free_tree(temp->left);
free_tree(temp->right);
if (!temp->left && !temp->right) {
free(temp);
return;
}
}

void print_tree(Traversal traversal, Node* root) {


if (!root)
return;
switch(traversal) {
case (PREORDER):
printf("%d -> ", root->value);
print_tree(traversal, root->left);
print_tree(traversal, root->right);
break;
case (INORDER):
print_tree(traversal, root->left);
printf("%d -> ", root->value);
print_tree(traversal, root->right);
break;
case (POSTORDER):
print_tree(traversal, root->left);
print_tree(traversal, root->right);
printf("%d -> ", root->value);
break;
}
}

int main() {
Node* root = init_tree(10);
root->left = create_node(20);
root->right = create_node(30);
root->left->left = create_node(40);
root->left->right = create_node(50);
root->right->left = create_node(60);
root->right->right = create_node(70);
printf("----Preorder Traversal:----\n");
print_tree(PREORDER, root);
printf("\n\n");
printf("----Inorder Traversal:----\n");
print_tree(INORDER, root);
printf("\n\n");
printf("----Postorder Traversal:----\n");
print_tree(POSTORDER, root);
printf("\n\n");
free_tree(root);
return 0;
}

Execution:
LAB 11 & 12 – GRAPHS
Program 1: Write a program to find the transitive closure of a directed graph.
Code:
#include <stdio.h>
#include <conio.h>

int n,a[10][10],p[10][10];
void path() {
int i,j,k;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
p[i][j]=a[i][j];
for(k=0;k<n;k++)
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(p[i][k]==1&&p[k][j]==1) p[i][j]=1;
}

void main() {
int i,j;
printf("Enter the number of nodes:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
path();
printf("\nThe path matrix is showm below\n");
for(i=0;i<n;i++) {
for(j=0;j<n;j++)
printf("%d ",p[i][j]);
printf("\n");
}
getch();
}
Execution:

Program 2: Write a program to find the minimum spanning tree using


Prim’s algorithm
Code:
#include<stdio.h>
#include<conio.h>

int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];

void main() {
printf("Enter the number of nodes:");
scanf("%d",&n);
printf("Enter the adjacency matrix:");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++) {
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
visited[1]=1;
printf("n");
while(ne<n) {
for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]<min)
if(visited[i]!=0) {
min=cost[i][j];
a=u=i;
b=v=j;
}
if(visited[u]==0 || visited[v]==0) {
printf("Edge %d:(%d %d) cost:%d",ne++,a,b,min);
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
printf("Minimun cost=%d",mincost);
getch();
}

Execution:

Program 3: Write a program to implement BFS Algorithm.


Code:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 40
struct queue {
int items[SIZE];
int front;
int rear;
};

struct queue* createQueue();


void enqueue(struct queue* q, int);
int dequeue(struct queue* q);
void display(struct queue* q);
int isEmpty(struct queue* q);
void printQueue(struct queue* q);

struct node {
int vertex;
struct node* next;
};

struct node* createNode(int);


struct Graph {
int numVertices;
struct node** adjLists;
int* visited;
};

void bfs(struct Graph* graph, int startVertex) {


struct queue* q = createQueue();
graph->visited[startVertex] = 1;
enqueue(q, startVertex);
while (!isEmpty(q)) {
printQueue(q);
int currentVertex = dequeue(q);
printf("Visited %d\n", currentVertex);
struct node* temp = graph->adjLists[currentVertex];
while (temp) {
int adjVertex = temp->vertex;
if(graph->visited[adjVertex] == 0) {
graph->visited[adjVertex] = 1;
enqueue(q, adjVertex);
}
temp = temp->next;
}
}
}

struct node* createNode(int v) {


struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}

struct Graph* createGraph(int vertices) {


struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct node*));
graph->visited = malloc(vertices * sizeof(int));
int i;
for(i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}

void addEdge(struct Graph* graph, int src, int dest) {


struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}

struct queue* createQueue() {


struct queue* q = malloc(sizeof(struct queue));
q->front = -1;
q->rear = -1;
return q;
}
int isEmpty(struct queue* q) {
if (q->rear == -1)
return 1;
else
return 0;
}

void enqueue(struct queue* q, int value) {


if(q->rear == SIZE - 1)
printf("\nQueue is Full!!");
else {
if (q->front == -1)
q->front = 0;
q->rear++;
q->items[q->rear] = value;
}
}

int dequeue(struct queue* q) {


int item;
if(isEmpty(q)) {
printf("Queue is empty");
item = -1;
}
else {
item = q->items[q->front];
q->front++;
if(q->front > q->rear) {
printf("Resetting queue ");
q->front = q->rear = -1;
}
}
return item;
}

void printQueue(struct queue* q) {


int i = q->front;
if(isEmpty(q)) {
printf("Queue is empty");
}
else {
printf("\nQueue contains \n");
for (i = q->front; i < q->rear + 1; i++) {
printf("%d ", q->items[i]);
}
}
}

int main() {
struct Graph* graph = createGraph(6);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 1, 4);
addEdge(graph, 1, 3);
addEdge(graph, 2, 4);
addEdge(graph, 3, 4);
bfs(graph, 0);
return 0;
}

Execution:
LAB 13 – SORTING

Program 1: Write a program to sort an array of N integers using quick sort


technique.
Code:
#include<stdio.h>

void swap_elements(int* first, int* second) {


int temp = *first;
*first = *second;
*second = temp;
}

int partition_function(int arr[], int l, int h) {


int p = arr[h];
int i = (l - 1);
for (int j = l; j <= h- 1; j++) {
if (arr[j] < p) {
i++;
swap_elements(&arr[i], &arr[j]);
}
}
swap_elements(&arr[i + 1], &arr[h]);
return (i + 1);
}

void quick_sort(int arr[], int l, int h) {


if (l < h) {
int p_index = partition_function(arr, l, h);
quick_sort(arr, l, p_index - 1);
quick_sort(arr, p_index + 1, h);
}
}
void print_Array(int arr[], int len) {
int i;
for (i=0; i < len; i++)
printf("%d ", arr[i]);
}

int main() {
int array[] = {29, 50, 19, 4, 68, 33};
int length = sizeof(array)/sizeof(array[0]);
printf("Before Sorting the array: ");
print_Array(array, length);
printf("\n");
printf("After Sorting the array: ");
quick_sort(array, 0, length-1);
print_Array(array, length);
return 0;
}

Execution:

Program 2: Write a program to sort an array of N integers using heap sort


technique.
Code:
#include <stdio.h>

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

void heapify(int arr[], int n, int i) {


int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
swap(&arr[i], &arr[largest]);
heapify(arr, n, largest);
}
}

void heapSort(int arr[], int n) {


for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}

void printArray(int arr[], int n) {


for (int i = 0; i < n; ++i)
printf("%d ", arr[i]);
printf("\n");
}

int main() {
int arr[] = {53, 82, 15, 2, 46};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Array before sorting:\n");
printArray(arr, n);
heapSort(arr, n);
printf("Array after sorting is:\n");
printArray(arr, n);
}
Execution:

You might also like