DATA STRUCTURES PROGRAM • GRAPHS
Represent an Undirected Graph with an Adjacency Matrix
Learn how to represent an undirected graph with an adjacency matrix using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int matrix[4][4] = {{0}};
int edges[][2] = {{0, 1}, {0, 2}, {1, 3}, {2, 3}};
for (int index = 0; index < 4; index++) {
int first = edges[index][0], second = edges[index][1];
matrix[first][second] = matrix[second][first] = 1;
}
for (int row = 0; row < 4; row++) {
for (int column = 0; column < 4; column++) printf("%d ", matrix[row][column]);
putchar('\n');
}
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Mark both matrix directions for every undirected edge.
- Display the computed result.
Mark both matrix directions for every undirected edge.
EFFICIENCY
Time and space complexity
Time complexity
O(V²) display
Auxiliary space
O(V²)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
