# Implementation of Undirected Graph in C Programming

## Graph:

A graph is the collection of vertices and edges or the set of vertices and edges. Mostly represented as**G={V, E}**here, G is for "Graph", V is for Vertices and E is for "Edges" in the graph.

### Vertices and Edges:

Nodes in the graph are known as vertices whereas the line connecting two nodes in a graph is known as Edge between these two nodes or the connection between two nodes are known as an edge.### Types of Graph:

There are so many types and subtypes of the graph but I am writing three of them which are mostly used in programming- Directed
- Undirected
- Weighted

### Where Graphs are Used?

Graphs are mostly used to represent the relation between two or more things. For example, Facebook uses the graph structure to represent the connection between two friends, in Facebook people are the nodes and if two nodes have a connection between them that's mean these two nodes (persons) are friends on Facebook. Google maps tell us about the minimum distance between two cities or two places by using the weighted graph.### Representation of Graph:

In our daily life, we represent a graph by drawing nodes and connecting them by edges. But in programming, there is no way to represent the graph by drawing nodes, etc. We can represent the graph in two ways- Adjacency List

Uses Linked List. - Adjacency Matrix

Uses 2d arrays.

#### Code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | #include<stdio.h> #include<stdlib.h> int main(){ int choice,addMatrix[10][10],totalNodes; while(1){ printf("\nPress\n1 : Create a Graph\n2 : Display Graph\n3 : Exit\n"); scanf("%d",&choice); switch(choice){ case 1 : printf("Enter total No of Nodes : "); scanf("%d",&totalNodes); addMatrix[10][10]=0; createGraph(addMatrix,totalNodes); break; case 2 : displayAdjacencyMatrix(addMatrix,totalNodes); break; case 3 : exit(0); } } return 0; } void createGraph(int addMatrix[10][10],int totalNodes){ int i,j; char adjacent; for(i=0;i<totalNodes;i++){ printf("\n"); for(j=i;j<totalNodes;j++){ printf("Is Node %d is Adjacent to Node %d ? (Y/N): ",i,j); fflush(stdin); scanf("%c",&adjacent); if(adjacent=='Y' || adjacent=='y'){ addMatrix[i][j]=1; addMatrix[j][i]=1; }else{ addMatrix[i][j]=0; addMatrix[j][i]=0; } } } } void displayAdjacencyMatrix(int addMatrix[10][10],int totalNodes){ int i,j; printf("\n\n"); for(i=0;i<totalNodes;i++){ for(j=0;j<totalNodes;j++){ printf(" %d",addMatrix[i][j]); } printf("\n"); } } |

## No comments