Graph adjacency list in C: solved exercise

Graph adjacency list in C: solved exercise

This exercise is scheduled for daily publication and follows the standard site structure: statement, solution, and expected output.

Problem statement

Solve the practical case and verify the console output.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#include <stdio.h>

#define N 4
int g[N][N] = {0};

void add_edge(int u, int v) { g[u][v] = 1; g[v][u] = 1; }

int main(void) {
    add_edge(0, 1); add_edge(0, 2);
    printf("0 conectado con 1: %d\n", g[0][1]);
    printf("2 conectado con 3: %d\n", g[2][3]);
    return 0;
}

Expected output

1
2
0 conectado con 1: 1
2 conectado con 3: 0

Common mistakes

  • Not validating standard-function return values.
  • Ignoring edge cases for indices, pointers, or buffers.
  • Skipping example-based test runs before publishing.

Practical use

Adjacency list graphs are the most memory-efficient representation for sparse graphs: networks, maps, and dependencies.

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

Is this exercise useful for C exams and technical interviews?

Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.

Where can I keep practicing with more solved C exercises?

In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

How should I practice this exercise type to improve faster?

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.