w1coding.comAll tutorials

C Graph

C lessons
  1. Environment Setup
  2. Introduction
  3. Variables
  4. Operators
  5. Condition
  6. Loops
  7. Functions
  8. Arrays
  9. Pointers
  10. Strings
  11. Struct
  12. File
  13. Memory
  14. Recursions
  15. Bitwise
  16. Directives
  17. Commandline
  18. Switch
  19. Enum
  20. Structp
  21. Arraysofstr
  22. Macros
  23. Pointer Arrays
  24. Linked
  25. Stack
  26. Queue
  27. Graph

In C, a graph can be represented using an adjacency matrix or an adjacency list. Here, we will use an adjacency matrix representation to store the graph structure.

Graph Using Adjacency Matrix

#include 

#define V 5  // Number of vertices

void printGraph(int graph[V][V]) {
    for (int i = 0; i < V; i++) {
        for (int j = 0; j < V; j++) {
            printf("%d ", graph[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int graph[V][V] = { {0, 1, 0, 1, 0},
                        {1, 0, 1, 1, 0},
                        {0, 1, 0, 0, 1},
                        {1, 1, 0, 0, 1},
                        {0, 0, 1, 1, 0} };

    printf("Adjacency Matrix of the Graph:\n");
    printGraph(graph);

    return 0;
}
    

This program demonstrates how to represent a graph using an adjacency matrix in C. It prints the matrix of a simple graph with 5 vertices.