C Program to Display the Total Degree of Each Vertex in a Graph
In graph theory, the degree of a vertex is the number of edges incident to it. For undirected graphs, the degree can be calculated by counting the number of edges connected to each vertex. This program demonstrates how to calculate and display the total degree of each vertex using an adjacency matrix.
📝 Problem Statement
B) Write a C program to display the total degree of each vertex.
💡 Logic (Simple Steps)
- Represent the graph using an adjacency matrix.
- Read the number of vertices
n. - Accept the adjacency matrix from the user:
1indicates an edge between vertices.0indicates no edge.
- For each vertex, sum the row in the adjacency matrix to get the degree.
- Display the degree of each vertex.
💻 Source Code (Student-Friendly Version)
#include <stdio.h>
int main()
{
int n, i, j;
int adj[100][100];
printf("Enter number of vertices: ");
scanf("%d", &n);
printf("Enter adjacency matrix:\n");
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
scanf("%d", &adj[i][j]);
}
}
printf("Degree of each vertex:\n");
for(i = 0; i < n; i++)
{
int degree = 0;
for(j = 0; j < n; j++)
{
degree += adj[i][j]; // Count edges
}
printf("Vertex %d: %d\n", i+1, degree);
}
return 0;
}
🖥️ Sample Input/Output
Input (Adjacency Matrix for 4 vertices):
Enter number of vertices: 4
Enter adjacency matrix:
0 1 0 1
1 0 1 0
0 1 0 1
1 0 1 0
Output:
Degree of each vertex:
Vertex 1: 2
Vertex 2: 2
Vertex 3: 2
Vertex 4: 2
🎓 Viva Questions with Answers
1. What is the degree of a vertex?
The degree of a vertex is the number of edges connected to it.
2. What is an adjacency matrix?
A matrix representation of a graph where adj[i][j] = 1 indicates an edge between vertex i and j.
3. How do you calculate the degree from an adjacency matrix?
By summing all elements in the row corresponding to that vertex.
4. What is the degree of a vertex with a self-loop?
A self-loop contributes 2 to the total degree.
5. Can this program work for directed graphs?
No, this calculates total degree for undirected graphs. For directed graphs, you would separately calculate in-degree and out-degree.
