0% found this document useful (0 votes)
7 views21 pages

Manish Vishwakarma Software

The document outlines a series of computer software lab experiments conducted by a student at Vishwavidyalaya Engineering College during the 2020-21 session. Each experiment includes programming tasks such as implementing algorithms for sorting, solving the N-Queen problem, the Knapsack problem, graph traversal using DFS and BFS, finding the largest common subsequence, and using Dijkstra's algorithm for shortest path calculations. The document also contains sample code and outputs for each experiment.

Uploaded by

1teen1toon1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views21 pages

Manish Vishwakarma Software

The document outlines a series of computer software lab experiments conducted by a student at Vishwavidyalaya Engineering College during the 2020-21 session. Each experiment includes programming tasks such as implementing algorithms for sorting, solving the N-Queen problem, the Knapsack problem, graph traversal using DFS and BFS, finding the largest common subsequence, and using Dijkstra's algorithm for shortest path calculations. The document also contains sample code and outputs for each experiment.

Uploaded by

1teen1toon1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

VISHWAVIDYALAYA ENGINEERING COLLEGE LAKHANPUR


AMBIKAPUR
(A Constituent College of CSVTU Bhilai)

SESSION – 2020-21

COMPUTER SOFTWARE LAB

by
Manish Vishwakarma
Roll no. - 513304920002
Enrollment no. – BJ5659

Submitted to
Dr. Dipti Verma
S.no
Experiments Date Remark
.

1. Write a program to sort a given list of 25-04-21


numbers by using heap sort and find
the complexity of heap sort

2. Write a program for N-Queen 28-04-21


Problem by using backtracking.

3. Write a Program to implement 02-05-21


Knapsack Problem and find the
complexity of the problem.

4. Write a program to traverse a graph 05-05-21


by using DFS and BFS technique and
find the complexity of the techniques

5. Write a program to find the largest 05-05-21


common subsequence for the given
graph

6. Write a program to find the shortest 09-09-21


path for each pair of source and
destination by using Dijkstra’s
Algorithm

7. Write a Program to communicate 09-09-21


from one PC to another PC by using
Sockets

INDEX
EXPERIMENT - 01

Aim - Write a program to sort a given list of numbers by using heap


sort and
find the complexity of heap sort

#include <stdio.h>

void main()
{
int heap[10], no, i, j, c, root, temp;

printf("\n Enter no of elements :");


scanf("%d", &no);
printf("\n Enter the nos : ");
for (i = 0; i < no; i++)
scanf("%d", &heap[i]);
for (i = 1; i < no; i++)
{
c = i;
do
{
root = (c - 1) / 2;
if (heap[root] < heap[c]) /* to create MAX heap array */
{
temp = heap[root];
heap[root] = heap[c];
heap[c] = temp;
}
c = root;
} while (c != 0);
}

printf("Heap array : ");


for (i = 0; i < no; i++)
printf("%d\t ", heap[i]);
for (j = no - 1; j >= 0; j--)
{
temp = heap[0];
heap[0] = heap[j /* swap max element with rightmost leaf element
heap[j] = temp;
root = 0;
do
{
c = 2 * root + 1; /* left node of root element */
if ((heap[c] < heap[c + 1]) && c < j-1)
c++;
if (heap[root]<heap[c] && c<j)
{
temp = heap[root];
heap[root] = heap[c];
heap[c] = temp;

}
root = c;
} while (c < j);
}
printf("\n The sorted array is : ");
for (i = 0; i < no; i++)
printf("\t %d", heap[i]);
printf("\n Complexity : \n Best case = Avg case = Worst case = O(n
logn) \n");
}

Output:- Average case


Enter no of elements :7

Enter the nos : 6


5
3
1
8
7
2
Heap array : 8 6 7 1 5 3 2
The sorted array is : 1 2 3 5 6 7 8
Complexity :
Best case = Avg case = Worst case = O(n logn)
EXPERIMENT - 02

Aim - Write a program for N-Queen Problem by using backtracking.

#include<stdio.h>
#include<math.h>

int board[20],count;

int main()
{
int n,i,j;
void queen(int row,int n);

printf(" - N Queens Problem Using Backtracking -");


printf("\n\nEnter number of Queens:");
scanf("%d",&n);
queen(1,n);
return 0;
}

//function for printing the solution


void print(int n)
{
int i,j;
printf("\n\nSolution %d:\n\n",++count);

for(i=1;i<=n;++i)
printf("\t%d",i);

for(i=1;i<=n;++i)
{
printf("\n\n%d",i);
for(j=1;j<=n;++j) //for nxn board
{
if(board[i]==j)
printf("\tQ"); //queen at i,j position
else
printf("\t-"); //empty slot
}
}
}

/*funtion to check conflicts


If no conflict for desired postion returns 1 otherwise returns 0*/
int place(int row,int column)
{
int i;
for(i=1;i<=row-1;++i)
{
//checking column and digonal conflicts
if(board[i]==column)
return 0;
else
if(abs(board[i]-column)==abs(i-row))
return 0;
}

return 1; //no conflicts


}

//function to check for proper positioning of queen


void queen(int row,int n)
{
int column;
for(column=1;column<=n;++column)
{
if(place(row,column))
{
board[row]=column; //no conflicts so place queen
if(row==n) //dead end
print(n); //printing the board configuration
else //try queen with next position
queen(row+1,n);
}
}
}
OUTPUT:-
EXPERIMENT - 03

Aim - Write a Program to implement Knapsack Problem and find the


complexity of the problem

#include <stdio.h>

int max(int a, int b) { return (a > b)? a : b; }

int knapsack(int W, int wt[], int val[], int n)


{
int i, w;
int K[n+1][W+1];

// Build table K[][] in bottom up manner


for (i = 0; i <= n; i++)
{
for (w = 0; w <= W; w++)
{
if (i==0 || w==0)
K[i][w] = 0;
else if (wt[i-1] <= w)
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]);
else
K[i][w] = K[i-1][w];
}
}

return K[n][W];
}

int main()
{
int val[] = {60, 100, 120};
int wt[] = {10, 20, 30};
int W = 50;
int n = sizeof(val)/sizeof(val[0]);
printf("\nValue = %d", knapsack(W, wt, val, n));
return 0;
}

Output:- Value = 220


EXPERIMENT - 04
Aim - Write a program to traverse a graph by using DFS and BFS
technique and find the complexity of the techniques

#include<stdio.h>

void DFS(int);
int G[10][10],visited[10],n; //n is no of vertices and graph is sorted in array
G[10][10]

void main()
{
int i,j;
printf("Enter number of vertices:");

scanf("%d",&n);

//read the adjecency matrix


printf("\nEnter adjecency matrix of the graph:");

for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);

//visited is initialized to zero


for(i=0;i<n;i++)
visited[i]=0;

DFS(0);
}

void DFS(int i)
{
int j;
printf("\n%d",i);
visited[i]=1;

for(j=0;j<n;j++)
if(!visited[j]&&G[i][j]==1)
DFS(j);
}

OUTPUT:-
BFS: #include<iostream>
#include<list>

using namespace std;

// This class represents a directed graph


using
// adjacency list representation
class Graph
{
int V; // No. of vertices

// Pointer to an array containing adjacency


// lists
list<int> *adj;
public:
Graph(int V); // Constructor

// function to add an edge to graph


void addEdge(int v, int w);

// prints BFS traversal from a given source s


void BFS(int s);
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}

void Graph::addEdge(int v, int w)


{
adj[v].push_back(w); // Add w to v’s list.
}

void Graph::BFS(int s)
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
for(int i = 0; i < V; i++)
visited[i] = false;

// Create a queue for BFS


list<int> queue;

// Mark the current node as visited and enqueue it


visited[s] = true;
queue.push_back(s);

// 'i' will be used to get all adjacent


// vertices of a vertex
list<int>::iterator i;

while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";
queue.pop_front();

// Get all adjacent vertices of the dequeued


// vertex s. If a adjacent has not been visited,
// then mark it visited and enqueue it
for (i = adj[s].begin(); i != adj[s].end(); ++i)
{
if (!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
}

// Driver program to test methods of graph class


int main()
{
// Create a graph given in the above diagram
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

cout << "Following is Breadth First Traversal "


<< "(starting from vertex 2) \n";
g.BFS(2);

return 0;
}

Output:- Following is Breadth First Traversal (starting from vertex


2)
2 0 3 1
EXPERIMENT - 05

Aim - Write a program to find the largest common subsequence for the
given graph
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int i,j,m,n,matrix[10][10];

char x[10],y[10],matrix2[10][10]; /* x and y is the array to store


both sequence */

void print(int i,int j)

if(i==0||j==0) /* print function is used to print


subsequence */

return;

if(matrix2[i][j]=='c')

{
print(i-1,j-1); /*recursive call */

printf("%c",y[j-1]);

else if(matrix2[i][j]=='u') /*u stands for upper*/

print(i-1,j);

else

print(i,j-1);
}

void lcs() /*lcs function is used to generate the matrix


to find lcs */

m=strlen(x);

n=strlen(y);

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

matrix[i][0]=0;

matrix2[i][0]='0';

for(j=0;j<=n;j++)

matrix[0][j]=0;

matrix2[0][j]='0';
\
}

for(i=1;i<=m;i++)

for(j=1;j<=n;j++)

if(x[i-1]==y[j-1])

matrix[i][j]=matrix[i-1][j-1]+1;

matrix2[i][j]='c';

else if(matrix[i-1][j]>=matrix[i][j-1])
{

matrix[i][j]=matrix[i-1][j];

matrix2[i][j]='u'; /*u stands for


upper*/

else

{
matrix[i][j]=matrix[i][j-1];
matrix2[i][j]='l';
}
}
int main()

{
printf("\nEnter the first sequence: \n");
scanf("%s",x);
printf("\nEnter the second sequence: \n");
scanf("%s",y);
lcs();
printf("\nThe longest common subsequence is: \n");
print(m,n);
return 0

OUTPUT:-
EXPERIMENT – 06

Aim - Write a program to find the shortest path for each pair of source
and destination by using Dijkstra’s Algorithm

#include<iostream>
#include<conio.h>
#include<stdio.h>
using namespace std;
int shortest(int ,int);
int cost[10][10],dist[20],i,j,n,k,m,S[20],v,totcost,path[20],p;
main()
{
int c;
cout <<"enter no of vertices";
cin >> n;
cout <<"enter no of edges";
cin >>m;
cout <<"\nenter\nEDGE Cost\n";
for(k=1;k<=m;k++)
{
cin >> i >> j >>c;
cost[i][j]=c;
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]==0)
cost[i][j]=31999;
cout <<"enter initial vertex";
cin >>v;
cout << v<<"\n";
shortest(v,n);
}

int shortest(int v,int n)


{
int min;
for(i=1;i<=n;i++)
{
S[i]=0;
dist[i]=cost[v][i];
}
path[++p]=v;
S[v]=1;
dist[v]=0;
for(i=2;i<=n-1;i++)
{
k=-1;
min=31999;
for(j=1;j<=n;j++)
{
if(dist[j]<min && S[j]!=1)
{
min=dist[j];
k=j;
}
}
if(cost[v][k]<=dist[k])
p=1;
path[++p]=k;
for(j=1;j<=p;j++)
cout<<path[j];
cout <<"\n";
//cout <<k;
S[k]=1;
for(j=1;j<=n;j++)
if(cost[k][j]!=31999 && dist[j]>=dist[k]+cost[k][j] && S[j]!=1)
dist[j]=dist[k]+cost[k][j];
}
}

OUTPUT:-
enter no of vertices6
enter no of edges11
enter
EDGE Cost
1 2 50
1 3 45
1 4 10
2 3 10
2 4 15
3 5 30
4 1 10
4 5 15
5 2 20
5 3 35
653
enter initial vertex1
1
14
145
1452
13
EXPERIMENT – 06

Aim - Write a Program to communicate from one PC to another PC by


using Sockets

Server side
//*******************************udp_server.c*******************************//
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

int main()
{
int sock;
int IPlength, TotalByte;
char message[512];
struct sockaddr_in serverAdd , clientAdd;
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("Socket Creation Failed");
exit(1);
}
serverAdd.sin_family = AF_INET;
serverAdd.sin_port = htons(5000);
serverAdd.sin_addr.s_addr = INADDR_ANY;
bzero(&(serverAdd.sin_zero),8);
if (bind(sock,(struct sockaddr *)&serverAdd,sizeof(struct sockaddr)) == -1)
{
perror("Bind Error");
exit(1);
}
IPlength = sizeof(struct sockaddr);
printf("\nUDP Server Waiting for client Message\n");
fflush(stdout);
while (1)
{
TotalByte = recvfrom(sock,message,512,0,(struct sockaddr *)&clientAdd,
&IPlength);
message[TotalByte] = '\0';
printf("Received Message: %s", message);
fflush(stdout);
}
return 0;
}
//*******************************udp_server.c*******************************//

Save the file in directory and compile it. After successful compilation, run the
executable file from command terminal. You may refer to the tutorial How to
make first C program in Linux if you are not aware of compilation and
execution process.

The following tasks are done at server side program:


- Define the necessary library file at server side
- Create a socket for end point communication
- Define the UDP protocol (i.e SOCK_DGRAM) and bind the communication port
(in this case: port number is 5000).
- After successful binding, server waits to receive the data from client
- If data is received from client, the server displays it on the command terminal.

Client side
//*******************************udp_client.c*******************************//
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int sock;
struct sockaddr_in serverAdd;
struct hostent *host;
char sendMessage[512];
host= (struct hostent *) gethostbyname((char *)"Server’s IP address");
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("socket Creation Failed");
exit(1);
}
serverAdd.sin_family = AF_INET;
serverAdd.sin_port = htons(5000);
serverAdd.sin_addr = *((struct in_addr *)host->h_addr);
bzero(&(serverAdd.sin_zero),8);
while (1)
{
printf("Enter the Message:");
fgets(sendMessage,100,stdin);
sendto(sock, sendMessage, strlen(sendMessage), 0,(struct sockaddr
*)&serverAdd, sizeof(struct sockaddr));
memset (sendMessage , 0 , sizeof(sendMessage));
}
}

You might also like