Q1)Write a C program that accepts the vertices and edges of a graph and stores it
as an adjacency matrix. Display the adjacency matrix.
ANS:-
#include <stdio.h>
#define MAX_VERTICES 100
int main() {
int vertices, edges;
printf("Enter the number of vertices in the graph: ");
scanf("%d", &vertices);
int adjMatrix[MAX_VERTICES][MAX_VERTICES] = {0}; // Initialize adjacency matrix
with zeros
printf("Enter the number of edges in the graph: ");
scanf("%d", &edges);
printf("Enter the edges (from_vertex to_vertex):\n");
for (int i = 0; i < edges; i++) {
int from, to;
scanf("%d %d", &from, &to);
adjMatrix[from][to] = 1; // Mark the edge between vertices as 1 in the
adjacency matrix
}
// Display the adjacency matrix
printf("Adjacency Matrix:\n");
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
printf("%d ", adjMatrix[i][j]);
}
printf("\n");
}
return 0;
}
Q.2) Write a program which uses binary search tree library and counts the total
nodes in the tree. int count(T)-returns the total number of nodes from BST
ANS
#include <stdio.h>
#include <stdlib.h>
// Binary Search Tree Node
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
// Function to create a new node
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// Function to insert a new node into BST
Node* insert(Node* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insert(root->left, data);
} else if (data > root->data) {
root->right = insert(root->right, data);
}
return root;
}
// Function to count the total number of nodes in the BST
int count(Node* root) {
if (root == NULL) {
return 0;
}
return 1 + count(root->left) + count(root->right);
}
int main() {
Node* root = NULL;
int data;
printf("Enter the nodes of the BST (enter -1 to stop):\n");
while (1) {
printf("Enter node value: ");
scanf("%d", &data);
if (data == -1) {
break;
}
root = insert(root, data);
}
// Count the total number of nodes in the BST
int totalNodes = count(root);
printf("Total number of nodes in the BST: %d\n", totalNodes);
return 0;
}