Home C Graphs C Graphs Definition
Definition and Usage A graph is a set of vertices connected by edges . Graphs model maps, networks, dependencies, and social connections. In C you store one with an adjacency matrix (a 2D array) or an adjacency list (an array of linked lists) and explore it with breadth-first or depth-first search . This section covers terminology, directed, undirected, and weighted graphs, both representations, building a graph, BFS, DFS, and applications.
Always track visited. Because graphs can contain cycles, every traversal needs a visited array or it may loop forever.
Path
Learning Path Work through the stages in order, or jump to a topic from the index below (9 tutorials).
Code
C Examples A quick taste of graphs. Compile with gcc file.c -std=c11 -Wall -o out.
1. Edge list Example 1 — A graph as an edge list Count each vertex's connections.
#include <stdio.h>
int main(void) {
int edges[][2] = {{0, 1}, {0, 2}, {1, 2}, {2, 3}};
int deg[4] = {0};
for (int i = 0; i < 4; i++) {
deg[edges[i][0]]++;
deg[edges[i][1]]++;
}
for (int v = 0; v < 4; v++) printf("degree(%d)=%d\n", v, deg[v]);
return 0;
} degree(0)=2
degree(1)=2
degree(2)=3
degree(3)=1 How It Works Each edge adds one to the degree of both endpoints. Vertex 2 touches three edges. The four edges give a degree sum of 8. Index
C Graphs Topics Every guide in this section with a one-line summary (9 tutorials).
Graph concepts 3 tutorials Vocabulary and graph kinds.
Representation 3 tutorials Matrices, lists, and building graphs in C.
Traversal and use 3 tutorials BFS, DFS, and applications.
Edge Cases & Pitfalls Common mistakes when learning graphs in C.
visit Missing visited array Cycles make traversals run forever.
dir Treating directed as undirected For a directed edge store only one direction.
mem Matrix for sparse graphs An adjacency matrix uses O(V^2) memory even if there are few edges.
Remember
Key Takeaways Vertices and edges.
Matrix or list.
BFS and DFS explore.
One line: A graph is a set of vertices connected by edges.
Frequently Asked Questions What is a graph in C? A data structure of vertices and edges, usually stored as an adjacency matrix or an adjacency list.
Which is better, adjacency matrix or list? Use a matrix for dense graphs or constant-time edge checks; use lists for sparse graphs to save memory and iterate neighbors quickly.
What is the difference between BFS and DFS? BFS explores level by level using a queue; DFS goes as deep as possible first using recursion or a stack.
Next: Graph Terminology Learn degree, path, cycle, and connectivity with code.
Continue → CODETOFUN NEWS
Stay Ahead in Tech Get the latest IT news, programming updates, and technology trends directly on your phone.
About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
9 people found this page helpful
Helpful Share Copy link Suggestion