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.

IntermediateAdjacency matrixUndirected graphRepresentation

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

dsa-graph-adjacency-matrix.c
Open in compiler
#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;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

0 1 1 0
1 0 0 1
1 0 0 1
0 1 1 0
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Mark both matrix directions for every undirected edge.
  3. 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.