MANNAR THIRUMALAI NAICKER COLLEGE (AUTONOMOUS)
(Affiliated to Madurai Kamaraj University) A Linguistic Minority Co-Educational Institution.
Re-accredited with ‘A’ Grade by NAAC
Pasumalai, Madurai-625004.
DEPARTMENT OF COMPUTER SCIENCE
WITH ARTIFICIAL INTELLIGFENCE
BONAFIDE CERTIFICATE
Name: Subject: DATA STRUCTURE AND ALGORITHM LAB
Register Number: Subject Code: 23UAICP31
Class: II B.Sc CS (AI)
This is to certify that this record is a bonafide work done by the above mentioned
student. The certificate is awarded for the same.
HEAD OF THE DEPARTMENT STAFF INCHARGE
Mrs.R.Vasuki Dr.G.Parkavi
Submitted for Practical Examination held on at
Mannar Thirumalai Naicker College (Autonomous), Madurai.
Internal Examiner External Examiner
INDEX
S.No Date Content Sign
1. Perform Stack Operation
2. Perform Queue Operation
3. Perform Tree Traversal Operation
4. Search An Element In An Array Using
Linear Search
5. Search An Element In An Array Using
Binary Search
6. Sort The Given Set Of Element Using
Insertion Sort
7. Sort The Given Set Of Element Using
Quick Sort
8. Search The Kth Smallest Element Using
Selection Sort
9. Find The Optimal Solution For The
Given Knapsack Problem Using Greedy
Method
10. Find All Pairs Shortest Path For The
Given Graph Using Dynamic
Programming Method
11. Traveling Salesman Problem Using
Dynamic Programming Method
12. Find All Possible Solution For An N-
Queen Problem Using Backtracking
Method
13. Find All Possible Hamiltonian Cycle For
The Given Graph Using Backtracking
Method
14. Sum Of Subsets
15. Bubble Sort
EX.NO : 1
PERFORM STACK OPERATION
AIM: Write a c program to perform Stack operation
SOURCECODE:
#include <stdio.h>
int MAXSIZE = 8;
int stack[8];
int top = -1;
int isempty(){
if(top == -1)
return 1;
else
return 0;
}
int isfull(){
if(top == MAXSIZE)
return 1;
else
return 0;
}
int peek(){
return stack[top];
}
int pop(){
int data;
if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
} else {
printf("Could not retrieve data, Stack is empty.n");
}
}
int push(int data){
if(!isfull()) {
top = top + 1;
stack[top] = data;
} else {
printf("Could not insert data, Stack is full.n");
}
}
int main(){
push(44);
push(10);
push(62);
push(123);
push(15);
printf("Element at top of the stack: %dn" ,peek());
printf("Elements: n");
while(!isempty()) {
int data = pop();
printf("%dn",data);
}
printf("Stack full: %sn" , isfull()?"true":"false");
printf("Stack empty: %sn" , isempty()?"true":"false");
return 0;
}
OUTPUT:
Element at top of the stack: 15
Elements:
15
123
62
10
44
Stack full: false
Stack empty: true
Result :
Thus the program was executed successfully and the output is verified
EX.NO :2
PERFORM QUEUE OPERATION
AIM: write a c program to perform queue operation
SOURCECODE :
#include<stdio.h>
int queue[10], n=5, front=-1, rear=-1;
void insert()
{
int val;
if(rear==n-1)
printf("queue overflown");
else
{
if(front==-1)
front=0;
printf("insert the element in queue:n");
scanf("%d", &val);
rear++;
queue[rear]=val;
}
}
void delete1()
{
if(front==-1||front>rear)
{
printf("queue underflown");
return;
}
else
{
printf("element deleted from queue is:%dn", queue[front]);
front++;
}
}
void display()
{
if(front==-1 || front>rear)
printf("queue is emptyn");
else
{
printf("queue elements are:n");
for(int i=front;i<=rear;i++)
printf("%d ", queue[i]);
printf("n");
}
}
int main()
{
int ch;
printf("1.insert element to queue:n");
printf("2.delete element from queue:n");
printf("3.display all the element of queue:n");
printf("4.exitn");
do
{
printf("enter your choice:n");
scanf("%d", &ch);
switch(ch)
{
case 1:
insert();
break;
case 2:
delete1();
break;
case 3:
display();
break;
case 4:
printf("exitn");
break;
default:
printf("invalid choicen");
}
}
while(ch!=4);
return 0;
}
OUTPUT:
1.insert element to queue:
2.delete element from queue:
3.display all the element of queue:
4.exit
enter your choice:
1
insert the element in queue:
45
enter your choice:
1
insert the element in queue:
67
enter your choice:
1
insert the element in queue:
95
enter your choice:
3
queue elements are:
45 67 95
enter your choice:
4
exit
Result :
Thus the program was successfully executed and the output was verified.
EX.NO :3
Tree Traversal
AIM: To write a c program to perform Tree Traversal
SOURCECODE :
#include <stdio.h>
#include <stdlib.h>
struct node {
int item;
struct node* left;
struct node* right;
};
void inorderTraversal(struct node* root) {
if (root == NULL) return;
inorderTraversal(root->left);
printf("%d ->", root->item);
inorderTraversal(root->right);
}
void preorderTraversal(struct node* root) {
if (root == NULL) return;
printf("%d ->", root->item);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
void postorderTraversal(struct node* root) {
if (root == NULL) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ->", root->item);
}
struct node* createNode(value) {
struct node* newNode = malloc(sizeof(struct node));
newNode->item = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct node* insertLeft(struct node* root, int value) {
root->left = createNode(value);
return root->left;
}
struct node* insertRight(struct node* root, int value) {
root->right = createNode(value);
return root->right;
}
int main() {
int a;
struct node* root = createNode(1);
insertLeft(root, 12);
insertRight(root, 9);
insertLeft(root->left, 5);
insertRight(root->left, 6);
printf("Inorder traversal n");
inorderTraversal(root);
printf("nPreorder traversal n");
preorderTraversal(root);
printf("nPostorder traversal n");
postorderTraversal(root);
scanf("%d",&a);
}
OUTPUT:
Inorder traversal
5 ->12 ->6 ->1 ->9 ->
Preorder traversal
1 ->12 ->5 ->6 ->9 ->
Postorder traversal
5 ->6 ->12 ->9 ->1 ->

Result :
Thus the program was successfully executed and the output was verified.
EX.NO:4
Search An Element In An Array
Using Linear Search
AIM: To write a c program to search an element in an array using linear search
SOURCECODE :
#include <stdio.h>
int linearSearch(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Return the index of the target
}
}
return -1; // Target not found
}
int main() {
int array[5];
int a;
int target;
printf("Enter 5 elements: ");
for(int i=0;i<=5;i++){
scanf("%d",&a);
array[i]=a;
}
printf("Enter the element to seach: ");
scanf("%d",&target);
int size = sizeof(array) / sizeof(array[0]);
int result = linearSearch(array, size, target);
if (result != -1) {
printf("Element found at index: %dn", result);
} else {
printf("Element not found in the array.n");
}
return 0;
}
OUTPUT:
Enter 5 elements: 67
4
9
7
3
Enter the element to seach: 3
Element found at index: 4
Result :
Thus the program was successfully executed and the output was verified
EX.NO :5
Search An Element In An Array
Using Binary Search
AIM: To write a c program to search an element in an array using binary search
SOURCECODE :
#include <stdio.h>
int binarySearch(int a[], int beg, int end, int val)
{
int mid;
if(end >= beg)
{ mid = (beg + end)/2;
if(a[mid] == val)
{
return mid+1;
}
else if(a[mid] < val)
{
return binarySearch(a, mid+1, end, val);
}
else
{
return binarySearch(a, beg, mid-1, val);
}
}
return -1;
}
int main() {
int a[] = {11, 14, 25, 30, 40, 41, 52, 57, 70};
int val = 40;
int n = sizeof(a) / sizeof(a[0]);
int res = binarySearch(a, 0, n-1, val);
printf("The elements of the array are: ");
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("nElement to be searched is: %d", val);
if (res == -1)
printf("nElement is not present in the array");
else
printf("nElement is present at %d position of array", res);
return 0;
}
OUTPUT:
The elements of the array are: 11 14 25 30 40 41 52 57 70
Element to be searched is: 40
Element is present at 5 position of array
Result :
Thus the program was successfully executed and the output was verified
EX.NO :6
SORT THE GIVEN SET OF
ELEMENT USING INSERTION SORT
AIM: To write a c program to sort the elements using insertion sort
SOURCECODE :
#include <stdio.h>
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
void printArray(int arr[], int n) {
int i;
for ( i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("n");
}
int main() {
int i;
int arr[5];
printf("Enter 5 elements of the array:n");
for ( i = 0; i < 5; i++) {
scanf("%d", &arr[i]);
}
insertionSort(arr, 5);
printf("Sorted array: n");
printArray(arr, 5);
return 0;
}
OUTPUT:
Enter 5 elements of the array:
8
1
7
4
0
Sorted array:
0 1 4 7 8
Result:
Thus the program was successfully executed and the output was verified
EX.NO :7
SORT THE GIVEN SET OF
ELEMENT USING QUICK SORT
AIM: To write a c program to sort the elements using quick sort
SOURCECODE :
#include<stdio.h>
#include<stdlib.h>
int compare(const void* a, const void* b)
{
return (*(int*)a-*(int*)b);
}
int main()
{
int a;
int arr[5];
int b,c;
int n= sizeof (arr) / sizeof (arr[0]);
printf("Enter any 5 elements: ");
for(b=0;b<=4;b++){
scanf("%d",&c);
arr[b]=c;
}
qsort(arr, n, sizeof(int), compare);
printf("Sorted array: n");
for(int i = 0; i < n; i++){
printf("%d ",arr[i]);
}
scanf("%d",&a);
return 0;
}
OUTPUT:
Enter any 5 elements: 7
3
9
1
2
Sorted array:
1 2 3 7 9
Result:
Thus the program was successfully executed and the output was verified
EX.NO :8
SEARCH THE Kth SMALLEST
ELEMENT USING SELECTION SORT
AIM: To write a c program to search the Kth smallest element using sort
SOURCECODE :
#include <stdio.h>
int selection_sort(int arr[], int n, int k) {
for (int i = 0; i < k; i++) {
int min_index = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_index]) {
min_index = j;
}
}
int temp = arr[i];
arr[i] = arr[min_index];
arr[min_index] = temp;
}
return arr[k - 1]; // Kth smallest element
}
int main() {
int my_array[6];
int k_value,m,v;
int n = sizeof(my_array) / sizeof(my_array[0]);
printf("Enter any 6 elements: ");
for(m=0;m<=5;m++){
scanf("%d",&v);
my_array[m]=v;
}
printf("Enter the kth value to find: ");
scanf("%d",&k_value);
int result = selection_sort(my_array, n, k_value);
printf("The %dth smallest element is: %dn", k_value, result);
return 0;
}
OUTPUT:
Enter any 6 elements: 6
2
3
9
1
6
Enter the kth value to find: 2
The 2th smallest element is: 2
Result:
Thus the program was successfully executed and the output was verified
EX.NO :9
FIND THE OPTIMAL SOLUTION
FOR THE GIVEN KNAPSACK PROBLEM USING
GREEDY METHOD
AIM: To write a c program to find the optimal solution given knapsack problem using
greedy method
SOURCECODE :
#include<stdio.h>
int main()
{
float weight[50],profit[50],ratio[50],Totalvalue,temp,capacity,amount;
int n,i,j;
printf("Enter the number of items :");
scanf("%d",&n);
for (i = 0; i < n; i++)
{
printf("Enter Weight and Profit for item[%d] :n",i);
scanf("%f %f", &weight[i], &profit[i]);
}
printf("Enter the capacity of knapsack :n");
scanf("%f",&capacity);
for(i=0;i<n;i++)
ratio[i]=profit[i]/weight[i];
for (i = 0; i < n; i++)
for (j = i + 1; j < n; j++)
if (ratio[i] < ratio[j])
{
temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = temp;
temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;
temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
printf("Knapsack problems using Greedy Algorithm:n");
for (i = 0; i < n; i++)
{
if (weight[i] > capacity)
break;
else
{
Totalvalue = Totalvalue + profit[i];
capacity = capacity - weight[i];
}
}
if (i < n)
Totalvalue = Totalvalue + (ratio[i]*capacity);
printf("nThe maximum value is :%fn",Totalvalue);
return 0;
}
OUTPUT:
Enter the number of items :3
Enter Weight and Profit for item[0] :
45
77
Enter Weight and Profit for item[1] :
21
97
Enter Weight and Profit for item[2] :
34
24
Enter the capacity of knapsack :
2
Knapsack problems using Greedy Algorithm:
The maximum value is :9.238095
Result:
Thus the program was successfully executed and the output was verified
EX.NO :10
FIND ALL PAIRS SHORTEST PATH
FOR THE GIVEN GRAPH USING DYNAMIC
PROGRAMMING METHOD
AIM: To write a c program to find all shortest path for the given graph using dynamic
programming method
SOURCECODE :
#include <stdio.h>
#include <limits.h>
#define INF INT_MAX
void floydWarshall(int graph[][10], int dist[][10], int n) {
int i,j,k;
for ( i = 0; i < n; i++) {
for ( j = 0; j < n; j++) {
dist[i][j] = graph[i][j];
}
}
for ( k = 0; k < n; k++) {
for( i = 0; i < n; i++) {
for ( j = 0; j < n; j++) {
if (dist[i][k] != INF && dist[k][j] != INF && dist[i][j] > dist[i][k] + dist[k][j])
{
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
}
int main() {
int n,i,j;
int graph[10][10], dist[10][10];
printf("Enter the number of vertices: ");
scanf("%d", &n);
printf("Enter the adjacency matrix row by row:n");
for ( i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
if (graph[i][j] == 0 && i != j) {
graph[i][j] = INF;
}
}
}
floydWarshall(graph, dist, n);
printf("nShortest path matrix:n");
for ( i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (dist[i][j] == INF) {
printf("INFt");
} else {
printf("%dt", dist[i][j]);
}
}
printf("n");
}
return 0;
}
OUTPUT:
Enter the number of vertices: 4
Enter the adjacency matrix row by row (use a large number for no edge, e.g., 999999):
0 3 0 7
0 0 2 0
0 0 0 1
0 0 0 0
Shortest path matrix:
0 3 5 7
INF 0 2 3
INF INF 0 1
INF INF INF 0
Result:
Thus the program was successfully executed and the output was verified
EX.NO :11
Traveling Salesman Problem Using Dynamic
Programming Method
AIM: To write a c program to do Travelling salesman problem using Dynamic programing
Method
SOURCECODE :
#include <stdio.h>
#include <limits.h>
#define MAX 20
#define INF INT_MAX
int n;
int dist[MAX][MAX];
int dp[ MAX][MAX];
int tsp(int mask, int pos) {
int city,ans;
if (mask == (1 << n) - 1) {
return dist[pos][0];
}
if (dp[mask][pos] != -1) {
return dp[mask][pos];
}
ans = INF;
for ( city = 0; city < n; city++) {
if ((mask & (1 << city)) == 0) {
int newAns = dist[pos][city] + tsp(mask | (1 << city), city);
ans = ans < newAns ? ans : newAns;
}
}
return dp[mask][pos] = ans;
}
int main() {
int i,j,result;
printf("Enter the number of cities: ");
scanf("%d", &n);
printf("Enter the distance matrix:n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &dist[i][j]);
}
}
for (i = 0; i < (1 << n); i++) {
for (j = 0; j < n; j++) {
dp[i][j] = -1;
}
}
result = tsp(1, 0);
printf("Minimum cost of visiting all cities: %dn", result);
return 0;
}
OUTPUT:
Enter the number of cities: 2
Enter the distance matrix:
43
22
1
78
Minimum cost of visiting all cities: 23
Result:
Thus the program was successfully executed and the output was verified
EX.NO :12
FIND ALL POSSIBLE SOLUTION FOR AN
N-QUEEN PROBLEM USING BACKTRACKING
METHOD
AIM: To write a c program to find all possible solution for an N-queen using backtracking
SOURCECODE :
#include <stdio.h>
#include <stdlib.h>
typedef int bool;
#define false 0
#define true 1
#define MAX 20
int board[MAX], count = 0;
void print(int n) {
int i, j;
printf("nnSolution %d:nn", ++count);
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
if (board[i] == j)
printf("Qt");
else
printf("*t");
}
printf("n");
}
}
bool place(int row, int column) {
int i;
for (i = 1; i <= row - 1; i++) {
if (board[i] == column)
return false;
else if (abs(board[i] - column) == abs(i - row))
return false;
}
return true;
}
void queen(int row, int n) {
int column;
for (column = 1; column <= n; column++) {
if (place(row, column)) {
board[row] = column;
if (row == n)
print(n);
else
queen(row + 1, n);
}
}
}
int main() {
int n;
printf("Enter number of Queens: ");
scanf("%d", &n);
if (n <= 0 || n > MAX) {
printf("Please enter a value between 1 and %d.n", MAX);
return 1;
}
queen(1, n);
return 0;
}
OUTPUT:
Enter number of Queens: 4
Solution 1:
* Q * *
* * * Q
Q * * *
* * Q *
Solution 2:
* * Q *
Q * * *
* * * Q
* Q * *
Result:
Thus the program was successfully executed and the output was verified
EX.NO :13
Find all possible Hamiltonian Cycle
for the given graph using backtracking method
AIM: To write a c program to find all possible Hamiltonian cycle for the given using
backtracking method
SOURCECODE :
#include <stdio.h>
typedef int bool;
#define false 0
#define true 1
#define V 5
void printCycle(int path[]) {
int i;
for (i = 0; i < V; i++) {
printf("%d ", path[i]);
}
printf("%dn", path[0]);
}
bool isSafe(int v, int graph[V][V], int path[], int pos) {
int i;
if (graph[path[pos - 1]][v] == 0) {
return false;
}
for (i = 0; i < pos; i++) {
if (path[i] == v) {
return false;
}
}
return true;
}
bool hamiltonianCycleUtil(int graph[V][V], int path[], int pos) {
int v;
bool foundCycle;
if (pos == V) {
if (graph[path[pos - 1]][path[0]] == 1) {
printCycle(path);
return true;
}
else {
return false;
}
}
foundCycle = false;
for (v = 1; v < V; v++) {
if (isSafe(v, graph, path, pos)) {
path[pos] = v;
if (hamiltonianCycleUtil(graph, path, pos + 1)) {
foundCycle = true;
}
path[pos] = -1;
}
}
return foundCycle;
}
void hamiltonianCycle(int graph[V][V]) {
int i;
int path[V];
for (i = 0; i < V; i++) {
path[i] = -1;
}
path[0] = 0;
if (!hamiltonianCycleUtil(graph, path, 1)) {
printf("No Hamiltonian cycle existsn");
}
}
int main() {
int a;
int graph[V][V] = {
{0, 1, 0, 1, 1},
{1, 0, 1, 1, 0},
{0, 1, 0, 1, 1},
{1, 1, 1, 0, 1},
{1, 0, 1, 1, 0}
};
hamiltonianCycle(graph);
scanf("%d",&a);
return 0;
}
OUTPUT:
0 1 2 3 4 0
0 1 2 4 3 0
0 1 3 2 4 0
0 3 1 2 4 0
0 3 4 2 1 0
0 4 2 1 3 0
0 4 2 3 1 0
0 4 3 2 1 0
Result:
Thus the program was successfully executed and the output was verified
EX.NO :14
SUM OF SUBSETS
AIM: To write a c program to show sum of subsets
SOURCECODE :
#include <stdio.h>
typedef int bool;
#define false 0
#define true 1
void printSubset(int subset[], int size) {
int i;
printf("{ ");
for ( i = 0; i < size; i++) {
printf("%d ", subset[i]);
}
printf("}n");
}
void findSubsetSum(int arr[], int n, int sum, int subset[], int subsetSize, int index) {
if (sum == 0) {
printSubset(subset, subsetSize);
return;
}
if (n == 0 || sum < 0) {
return;
}
subset[subsetSize] = arr[index];
findSubsetSum(arr, n - 1, sum - arr[index], subset, subsetSize + 1, index + 1);
findSubsetSum(arr, n - 1, sum, subset, subsetSize, index + 1);
}
int main() {
int n, sum,i;
int arr[5];
int subset[5];
printf("Enter the elements:n");
for ( i = 0; i < 4; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the sum to find: ");
scanf("%d", &sum);
printf("Subsets with the given sum are:n");
findSubsetSum(arr, 5, sum, subset, 0, 0);
return 0;
}
OUTPUT:
Enter the number of elements: 4
Enter the elements:
4
0
1
2
Enter the sum to find: 6
Subsets with the given sum are:
{ 4 0 2 }
{ 4 2 }
Result:
Thus the program was successfully executed and the output was verified
EX.NO :15
BUBBLE SORT
AIM: To write a c program to sort the elements using bubble sort
SOURCECODE :
#include<stdio.h>
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n-1; i++) {
int swapped = 0;
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
swapped = 1;
}
}
if (swapped == 0)
break;
}
}
void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}
int main() {
int i;
int arr[5];
printf("Enter 5 elements:n");
for (i = 0; i < 5; i++) {
scanf("%d", &arr[i]);
}
bubbleSort(arr, 5);
printf("Sorted array: n");
printArray(arr, 5);
return 0;
}
OUTPUT:
Enter the number of elements: 4
Enter 4 elements:
56
22
45
90
Sorted array:
22 45 56 90
Result:
Thus the program was successfully executed and the output was verified

Data structure and algorithm lab spiral (1) (4) (1).docx

  • 1.
    MANNAR THIRUMALAI NAICKERCOLLEGE (AUTONOMOUS) (Affiliated to Madurai Kamaraj University) A Linguistic Minority Co-Educational Institution. Re-accredited with ‘A’ Grade by NAAC Pasumalai, Madurai-625004. DEPARTMENT OF COMPUTER SCIENCE WITH ARTIFICIAL INTELLIGFENCE BONAFIDE CERTIFICATE Name: Subject: DATA STRUCTURE AND ALGORITHM LAB Register Number: Subject Code: 23UAICP31 Class: II B.Sc CS (AI) This is to certify that this record is a bonafide work done by the above mentioned student. The certificate is awarded for the same. HEAD OF THE DEPARTMENT STAFF INCHARGE Mrs.R.Vasuki Dr.G.Parkavi Submitted for Practical Examination held on at Mannar Thirumalai Naicker College (Autonomous), Madurai. Internal Examiner External Examiner
  • 2.
    INDEX S.No Date ContentSign 1. Perform Stack Operation 2. Perform Queue Operation 3. Perform Tree Traversal Operation 4. Search An Element In An Array Using Linear Search 5. Search An Element In An Array Using Binary Search 6. Sort The Given Set Of Element Using Insertion Sort 7. Sort The Given Set Of Element Using Quick Sort 8. Search The Kth Smallest Element Using Selection Sort 9. Find The Optimal Solution For The Given Knapsack Problem Using Greedy Method 10. Find All Pairs Shortest Path For The Given Graph Using Dynamic Programming Method 11. Traveling Salesman Problem Using Dynamic Programming Method 12. Find All Possible Solution For An N- Queen Problem Using Backtracking Method 13. Find All Possible Hamiltonian Cycle For The Given Graph Using Backtracking Method 14. Sum Of Subsets
  • 3.
  • 4.
    EX.NO : 1 PERFORMSTACK OPERATION AIM: Write a c program to perform Stack operation SOURCECODE: #include <stdio.h> int MAXSIZE = 8; int stack[8]; int top = -1; int isempty(){ if(top == -1) return 1; else return 0; } int isfull(){ if(top == MAXSIZE) return 1; else return 0; } int peek(){ return stack[top]; } int pop(){ int data; if(!isempty()) { data = stack[top]; top = top - 1; return data; } else { printf("Could not retrieve data, Stack is empty.n"); } } int push(int data){ if(!isfull()) {
  • 5.
    top = top+ 1; stack[top] = data; } else { printf("Could not insert data, Stack is full.n"); } } int main(){ push(44); push(10); push(62); push(123); push(15); printf("Element at top of the stack: %dn" ,peek()); printf("Elements: n"); while(!isempty()) { int data = pop(); printf("%dn",data); } printf("Stack full: %sn" , isfull()?"true":"false"); printf("Stack empty: %sn" , isempty()?"true":"false"); return 0; }
  • 6.
    OUTPUT: Element at topof the stack: 15 Elements: 15 123 62 10 44 Stack full: false Stack empty: true Result : Thus the program was executed successfully and the output is verified
  • 7.
    EX.NO :2 PERFORM QUEUEOPERATION AIM: write a c program to perform queue operation SOURCECODE : #include<stdio.h> int queue[10], n=5, front=-1, rear=-1; void insert() { int val; if(rear==n-1) printf("queue overflown"); else { if(front==-1) front=0; printf("insert the element in queue:n"); scanf("%d", &val); rear++; queue[rear]=val; } } void delete1() { if(front==-1||front>rear) { printf("queue underflown"); return; } else { printf("element deleted from queue is:%dn", queue[front]); front++; } } void display() { if(front==-1 || front>rear)
  • 8.
    printf("queue is emptyn"); else { printf("queueelements are:n"); for(int i=front;i<=rear;i++) printf("%d ", queue[i]); printf("n"); } } int main() { int ch; printf("1.insert element to queue:n"); printf("2.delete element from queue:n"); printf("3.display all the element of queue:n"); printf("4.exitn"); do { printf("enter your choice:n"); scanf("%d", &ch); switch(ch) { case 1: insert(); break; case 2: delete1(); break; case 3: display(); break; case 4: printf("exitn"); break; default: printf("invalid choicen"); } } while(ch!=4); return 0; }
  • 9.
    OUTPUT: 1.insert element toqueue: 2.delete element from queue: 3.display all the element of queue: 4.exit enter your choice: 1 insert the element in queue: 45 enter your choice: 1 insert the element in queue: 67 enter your choice: 1 insert the element in queue: 95 enter your choice: 3 queue elements are: 45 67 95 enter your choice: 4 exit Result : Thus the program was successfully executed and the output was verified.
  • 10.
    EX.NO :3 Tree Traversal AIM:To write a c program to perform Tree Traversal SOURCECODE : #include <stdio.h> #include <stdlib.h> struct node { int item; struct node* left; struct node* right; }; void inorderTraversal(struct node* root) { if (root == NULL) return; inorderTraversal(root->left); printf("%d ->", root->item); inorderTraversal(root->right); } void preorderTraversal(struct node* root) { if (root == NULL) return; printf("%d ->", root->item); preorderTraversal(root->left); preorderTraversal(root->right); } void postorderTraversal(struct node* root) { if (root == NULL) return; postorderTraversal(root->left); postorderTraversal(root->right); printf("%d ->", root->item); }
  • 11.
    struct node* createNode(value){ struct node* newNode = malloc(sizeof(struct node)); newNode->item = value; newNode->left = NULL; newNode->right = NULL; return newNode; } struct node* insertLeft(struct node* root, int value) { root->left = createNode(value); return root->left; } struct node* insertRight(struct node* root, int value) { root->right = createNode(value); return root->right; } int main() { int a; struct node* root = createNode(1); insertLeft(root, 12); insertRight(root, 9); insertLeft(root->left, 5); insertRight(root->left, 6); printf("Inorder traversal n"); inorderTraversal(root); printf("nPreorder traversal n"); preorderTraversal(root); printf("nPostorder traversal n"); postorderTraversal(root); scanf("%d",&a); }
  • 12.
    OUTPUT: Inorder traversal 5 ->12->6 ->1 ->9 -> Preorder traversal 1 ->12 ->5 ->6 ->9 -> Postorder traversal 5 ->6 ->12 ->9 ->1 -> Result : Thus the program was successfully executed and the output was verified.
  • 13.
    EX.NO:4 Search An ElementIn An Array Using Linear Search AIM: To write a c program to search an element in an array using linear search SOURCECODE : #include <stdio.h> int linearSearch(int arr[], int size, int target) { for (int i = 0; i < size; i++) { if (arr[i] == target) { return i; // Return the index of the target } } return -1; // Target not found } int main() { int array[5]; int a; int target; printf("Enter 5 elements: "); for(int i=0;i<=5;i++){ scanf("%d",&a); array[i]=a; } printf("Enter the element to seach: "); scanf("%d",&target); int size = sizeof(array) / sizeof(array[0]); int result = linearSearch(array, size, target); if (result != -1) { printf("Element found at index: %dn", result); } else { printf("Element not found in the array.n"); } return 0; }
  • 14.
    OUTPUT: Enter 5 elements:67 4 9 7 3 Enter the element to seach: 3 Element found at index: 4 Result : Thus the program was successfully executed and the output was verified
  • 15.
    EX.NO :5 Search AnElement In An Array Using Binary Search AIM: To write a c program to search an element in an array using binary search SOURCECODE : #include <stdio.h> int binarySearch(int a[], int beg, int end, int val) { int mid; if(end >= beg) { mid = (beg + end)/2; if(a[mid] == val) { return mid+1; } else if(a[mid] < val) { return binarySearch(a, mid+1, end, val); } else { return binarySearch(a, beg, mid-1, val); } } return -1; } int main() { int a[] = {11, 14, 25, 30, 40, 41, 52, 57, 70}; int val = 40; int n = sizeof(a) / sizeof(a[0]); int res = binarySearch(a, 0, n-1, val); printf("The elements of the array are: "); for (int i = 0; i < n; i++) printf("%d ", a[i]); printf("nElement to be searched is: %d", val); if (res == -1) printf("nElement is not present in the array"); else printf("nElement is present at %d position of array", res); return 0; }
  • 16.
    OUTPUT: The elements ofthe array are: 11 14 25 30 40 41 52 57 70 Element to be searched is: 40 Element is present at 5 position of array Result : Thus the program was successfully executed and the output was verified
  • 17.
    EX.NO :6 SORT THEGIVEN SET OF ELEMENT USING INSERTION SORT AIM: To write a c program to sort the elements using insertion sort SOURCECODE : #include <stdio.h> void insertionSort(int arr[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } void printArray(int arr[], int n) { int i; for ( i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("n"); } int main() { int i; int arr[5]; printf("Enter 5 elements of the array:n"); for ( i = 0; i < 5; i++) { scanf("%d", &arr[i]); } insertionSort(arr, 5);
  • 18.
  • 19.
    OUTPUT: Enter 5 elementsof the array: 8 1 7 4 0 Sorted array: 0 1 4 7 8 Result: Thus the program was successfully executed and the output was verified
  • 20.
    EX.NO :7 SORT THEGIVEN SET OF ELEMENT USING QUICK SORT AIM: To write a c program to sort the elements using quick sort SOURCECODE : #include<stdio.h> #include<stdlib.h> int compare(const void* a, const void* b) { return (*(int*)a-*(int*)b); } int main() { int a; int arr[5]; int b,c; int n= sizeof (arr) / sizeof (arr[0]); printf("Enter any 5 elements: "); for(b=0;b<=4;b++){ scanf("%d",&c); arr[b]=c; } qsort(arr, n, sizeof(int), compare); printf("Sorted array: n"); for(int i = 0; i < n; i++){ printf("%d ",arr[i]); } scanf("%d",&a); return 0; }
  • 21.
    OUTPUT: Enter any 5elements: 7 3 9 1 2 Sorted array: 1 2 3 7 9 Result: Thus the program was successfully executed and the output was verified
  • 22.
    EX.NO :8 SEARCH THEKth SMALLEST ELEMENT USING SELECTION SORT AIM: To write a c program to search the Kth smallest element using sort SOURCECODE : #include <stdio.h> int selection_sort(int arr[], int n, int k) { for (int i = 0; i < k; i++) { int min_index = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[min_index]) { min_index = j; } } int temp = arr[i]; arr[i] = arr[min_index]; arr[min_index] = temp; } return arr[k - 1]; // Kth smallest element } int main() { int my_array[6]; int k_value,m,v; int n = sizeof(my_array) / sizeof(my_array[0]); printf("Enter any 6 elements: "); for(m=0;m<=5;m++){ scanf("%d",&v); my_array[m]=v; } printf("Enter the kth value to find: "); scanf("%d",&k_value); int result = selection_sort(my_array, n, k_value); printf("The %dth smallest element is: %dn", k_value, result); return 0; }
  • 23.
    OUTPUT: Enter any 6elements: 6 2 3 9 1 6 Enter the kth value to find: 2 The 2th smallest element is: 2 Result: Thus the program was successfully executed and the output was verified
  • 24.
    EX.NO :9 FIND THEOPTIMAL SOLUTION FOR THE GIVEN KNAPSACK PROBLEM USING GREEDY METHOD AIM: To write a c program to find the optimal solution given knapsack problem using greedy method SOURCECODE : #include<stdio.h> int main() { float weight[50],profit[50],ratio[50],Totalvalue,temp,capacity,amount; int n,i,j; printf("Enter the number of items :"); scanf("%d",&n); for (i = 0; i < n; i++) { printf("Enter Weight and Profit for item[%d] :n",i); scanf("%f %f", &weight[i], &profit[i]); } printf("Enter the capacity of knapsack :n"); scanf("%f",&capacity); for(i=0;i<n;i++) ratio[i]=profit[i]/weight[i]; for (i = 0; i < n; i++) for (j = i + 1; j < n; j++) if (ratio[i] < ratio[j]) { temp = ratio[j]; ratio[j] = ratio[i]; ratio[i] = temp; temp = weight[j]; weight[j] = weight[i]; weight[i] = temp; temp = profit[j]; profit[j] = profit[i];
  • 25.
    profit[i] = temp; } printf("Knapsackproblems using Greedy Algorithm:n"); for (i = 0; i < n; i++) { if (weight[i] > capacity) break; else { Totalvalue = Totalvalue + profit[i]; capacity = capacity - weight[i]; } } if (i < n) Totalvalue = Totalvalue + (ratio[i]*capacity); printf("nThe maximum value is :%fn",Totalvalue); return 0; }
  • 26.
    OUTPUT: Enter the numberof items :3 Enter Weight and Profit for item[0] : 45 77 Enter Weight and Profit for item[1] : 21 97 Enter Weight and Profit for item[2] : 34 24 Enter the capacity of knapsack : 2 Knapsack problems using Greedy Algorithm: The maximum value is :9.238095 Result: Thus the program was successfully executed and the output was verified
  • 27.
    EX.NO :10 FIND ALLPAIRS SHORTEST PATH FOR THE GIVEN GRAPH USING DYNAMIC PROGRAMMING METHOD AIM: To write a c program to find all shortest path for the given graph using dynamic programming method SOURCECODE : #include <stdio.h> #include <limits.h> #define INF INT_MAX void floydWarshall(int graph[][10], int dist[][10], int n) { int i,j,k; for ( i = 0; i < n; i++) { for ( j = 0; j < n; j++) { dist[i][j] = graph[i][j]; } } for ( k = 0; k < n; k++) { for( i = 0; i < n; i++) { for ( j = 0; j < n; j++) { if (dist[i][k] != INF && dist[k][j] != INF && dist[i][j] > dist[i][k] + dist[k][j]) { dist[i][j] = dist[i][k] + dist[k][j]; } } } } } int main() { int n,i,j; int graph[10][10], dist[10][10]; printf("Enter the number of vertices: "); scanf("%d", &n); printf("Enter the adjacency matrix row by row:n"); for ( i = 0; i < n; i++) { for (j = 0; j < n; j++) {
  • 28.
    scanf("%d", &graph[i][j]); if (graph[i][j]== 0 && i != j) { graph[i][j] = INF; } } } floydWarshall(graph, dist, n); printf("nShortest path matrix:n"); for ( i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (dist[i][j] == INF) { printf("INFt"); } else { printf("%dt", dist[i][j]); } } printf("n"); } return 0; }
  • 29.
    OUTPUT: Enter the numberof vertices: 4 Enter the adjacency matrix row by row (use a large number for no edge, e.g., 999999): 0 3 0 7 0 0 2 0 0 0 0 1 0 0 0 0 Shortest path matrix: 0 3 5 7 INF 0 2 3 INF INF 0 1 INF INF INF 0 Result: Thus the program was successfully executed and the output was verified
  • 30.
    EX.NO :11 Traveling SalesmanProblem Using Dynamic Programming Method AIM: To write a c program to do Travelling salesman problem using Dynamic programing Method SOURCECODE : #include <stdio.h> #include <limits.h> #define MAX 20 #define INF INT_MAX int n; int dist[MAX][MAX]; int dp[ MAX][MAX]; int tsp(int mask, int pos) { int city,ans; if (mask == (1 << n) - 1) { return dist[pos][0]; } if (dp[mask][pos] != -1) { return dp[mask][pos]; } ans = INF; for ( city = 0; city < n; city++) { if ((mask & (1 << city)) == 0) { int newAns = dist[pos][city] + tsp(mask | (1 << city), city); ans = ans < newAns ? ans : newAns; } } return dp[mask][pos] = ans; } int main() { int i,j,result; printf("Enter the number of cities: "); scanf("%d", &n); printf("Enter the distance matrix:n"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { scanf("%d", &dist[i][j]);
  • 31.
    } } for (i =0; i < (1 << n); i++) { for (j = 0; j < n; j++) { dp[i][j] = -1; } } result = tsp(1, 0); printf("Minimum cost of visiting all cities: %dn", result); return 0; } OUTPUT:
  • 32.
    Enter the numberof cities: 2 Enter the distance matrix: 43 22 1 78 Minimum cost of visiting all cities: 23 Result: Thus the program was successfully executed and the output was verified
  • 33.
    EX.NO :12 FIND ALLPOSSIBLE SOLUTION FOR AN N-QUEEN PROBLEM USING BACKTRACKING METHOD AIM: To write a c program to find all possible solution for an N-queen using backtracking SOURCECODE : #include <stdio.h> #include <stdlib.h> typedef int bool; #define false 0 #define true 1 #define MAX 20 int board[MAX], count = 0; void print(int n) { int i, j; printf("nnSolution %d:nn", ++count); for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { if (board[i] == j) printf("Qt"); else printf("*t"); } printf("n"); } } bool place(int row, int column) { int i; for (i = 1; i <= row - 1; i++) { if (board[i] == column) return false; else if (abs(board[i] - column) == abs(i - row)) return false; }
  • 34.
    return true; } void queen(introw, int n) { int column; for (column = 1; column <= n; column++) { if (place(row, column)) { board[row] = column; if (row == n) print(n); else queen(row + 1, n); } } } int main() { int n; printf("Enter number of Queens: "); scanf("%d", &n); if (n <= 0 || n > MAX) { printf("Please enter a value between 1 and %d.n", MAX); return 1; } queen(1, n); return 0; } OUTPUT:
  • 35.
    Enter number ofQueens: 4 Solution 1: * Q * * * * * Q Q * * * * * Q * Solution 2: * * Q * Q * * * * * * Q * Q * * Result: Thus the program was successfully executed and the output was verified EX.NO :13
  • 36.
    Find all possibleHamiltonian Cycle for the given graph using backtracking method AIM: To write a c program to find all possible Hamiltonian cycle for the given using backtracking method SOURCECODE : #include <stdio.h> typedef int bool; #define false 0 #define true 1 #define V 5 void printCycle(int path[]) { int i; for (i = 0; i < V; i++) { printf("%d ", path[i]); } printf("%dn", path[0]); } bool isSafe(int v, int graph[V][V], int path[], int pos) { int i; if (graph[path[pos - 1]][v] == 0) { return false; } for (i = 0; i < pos; i++) { if (path[i] == v) { return false; } } return true; } bool hamiltonianCycleUtil(int graph[V][V], int path[], int pos) { int v; bool foundCycle; if (pos == V) { if (graph[path[pos - 1]][path[0]] == 1) { printCycle(path); return true; }
  • 37.
    else { return false; } } foundCycle= false; for (v = 1; v < V; v++) { if (isSafe(v, graph, path, pos)) { path[pos] = v; if (hamiltonianCycleUtil(graph, path, pos + 1)) { foundCycle = true; } path[pos] = -1; } } return foundCycle; } void hamiltonianCycle(int graph[V][V]) { int i; int path[V]; for (i = 0; i < V; i++) { path[i] = -1; } path[0] = 0; if (!hamiltonianCycleUtil(graph, path, 1)) { printf("No Hamiltonian cycle existsn"); } } int main() { int a; int graph[V][V] = { {0, 1, 0, 1, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 1, 1}, {1, 1, 1, 0, 1}, {1, 0, 1, 1, 0} }; hamiltonianCycle(graph); scanf("%d",&a); return 0; } OUTPUT:
  • 38.
    0 1 23 4 0 0 1 2 4 3 0 0 1 3 2 4 0 0 3 1 2 4 0 0 3 4 2 1 0 0 4 2 1 3 0 0 4 2 3 1 0 0 4 3 2 1 0 Result: Thus the program was successfully executed and the output was verified EX.NO :14
  • 39.
    SUM OF SUBSETS AIM:To write a c program to show sum of subsets SOURCECODE : #include <stdio.h> typedef int bool; #define false 0 #define true 1 void printSubset(int subset[], int size) { int i; printf("{ "); for ( i = 0; i < size; i++) { printf("%d ", subset[i]); } printf("}n"); } void findSubsetSum(int arr[], int n, int sum, int subset[], int subsetSize, int index) { if (sum == 0) { printSubset(subset, subsetSize); return; } if (n == 0 || sum < 0) { return; } subset[subsetSize] = arr[index]; findSubsetSum(arr, n - 1, sum - arr[index], subset, subsetSize + 1, index + 1); findSubsetSum(arr, n - 1, sum, subset, subsetSize, index + 1); } int main() { int n, sum,i; int arr[5]; int subset[5]; printf("Enter the elements:n"); for ( i = 0; i < 4; i++) { scanf("%d", &arr[i]); } printf("Enter the sum to find: "); scanf("%d", &sum); printf("Subsets with the given sum are:n"); findSubsetSum(arr, 5, sum, subset, 0, 0); return 0; }
  • 40.
    OUTPUT: Enter the numberof elements: 4 Enter the elements: 4 0 1 2 Enter the sum to find: 6 Subsets with the given sum are: { 4 0 2 } { 4 2 } Result: Thus the program was successfully executed and the output was verified EX.NO :15
  • 41.
    BUBBLE SORT AIM: Towrite a c program to sort the elements using bubble sort SOURCECODE : #include<stdio.h> void bubbleSort(int arr[], int n) { int i, j, temp; for (i = 0; i < n-1; i++) { int swapped = 0; for (j = 0; j < n-i-1; j++) { if (arr[j] > arr[j+1]) { temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; swapped = 1; } } if (swapped == 0) break; } } void printArray(int arr[], int size) { int i; for (i = 0; i < size; i++) printf("%d ", arr[i]); printf("n"); } int main() { int i; int arr[5]; printf("Enter 5 elements:n"); for (i = 0; i < 5; i++) { scanf("%d", &arr[i]); } bubbleSort(arr, 5); printf("Sorted array: n"); printArray(arr, 5); return 0; } OUTPUT: Enter the number of elements: 4
  • 42.
    Enter 4 elements: 56 22 45 90 Sortedarray: 22 45 56 90 Result: Thus the program was successfully executed and the output was verified