SPP 4
SPP 4
Que 1)Write a C program that accepts the vertices and edges of a graph and
stores it as an adjacency matrix. Display the adjacency matrix.
Program :-
#include<stdio.h>
#define MAX 30
void main()
{
int i,j,n,a[MAX][MAX];
printf("\n enter the vertices of graph");
scanf("%d",&n);
printf("\n accept value of adjacency matrix");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("\n edges from %dto%d\n",i,j);
scanf("%d",&a[i][j]);
}
}
printf("\n Display adjacency matrix\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
}
Output :-
enter the vertices of graph3
accept value of adjacency matrix
edges from 0to0
1
Que 2) Write a C program that accepts the vertices and edges of a graph and
store it as an adjacency matrix. Implement functions to print indegree,
outdegree and total degree of all vertices of graph.
Program :-
#include<stdio.h>
#define MAX 10
void degree(int[MAX][MAX],int, int);
int main()
{
int n,i,j,g[MAX][MAX];
printf("How many vertices");
scanf("%d",&n);
printf("Enter matrix elements\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("[%d][%d]=",i,j);
scanf("%d",&g[i][j]);
}
}
printf("Adjacency matrix is\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",g[i][j]);
}
printf("\n");
}
for(i=0;i<n;i++)
{
degree(g,i,n);
}
}
void degree(int g[MAX][MAX],int j,int n)
{
int i,id=0,od=0,td;
for(i=0;i<n;i++)
{
if(g[i][j]==1)
id++;
if(g[j][i]==1)
od++;
}
printf("V%d indegree=%d\t\t Outdegree=%d\n",j,id,od);
td=id+od;
printf("total degree=%d",td);
printf("\n");
}
Output :-
How many vertices4
Enter matrix elements
[0][0]=0
[0][1]=0
[0][2]=1
[0][3]=0
[1][0]=1
[1][1]=0
[1][2]=0
[1][3]=1
[2][0]=0
[2][1]=0
[2][2]=0
[2][3]=1
[3][0]=0
[3][1]=0
[3][2]=0
[3][3]=0
Adjacency matrix is
0 0 1 0
1 0 0 1
0 0 0 1
0 0 0 0
V0 indegree=1 Outdegree=1
total degree=2
V1 indegree=0 Outdegree=2
total degree=2
V2 indegree=1 Outdegree=1
total degree=2
V3 indegree=2 Outdegree=0
total degree=2