0% found this document useful (0 votes)
82 views29 pages

Chirag Saraswat 289 (DSA Lab)

Uploaded by

Chirag Saraswat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views29 pages

Chirag Saraswat 289 (DSA Lab)

Uploaded by

Chirag Saraswat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Name:- Chirag Saraswat

Roll Number: - 20/289


Subject:- DSA Lab
Branch:- ECE
E-mail:- chirag.20ec289@rtu.ac.in
Question-1: Write a simple C program on a 32-bit compiler to understand the
concept of array storage, size of a word. The program shall be written illustrating
the concept of row-major and column-major storage. Find the address of the
element and verify it with the theoretical value. A program may be written for
arrays up to 4-dimensions.
Solution:-

#include <stdio.h>

int main()
{
int a[4][4], b[4][4], c[4][4], d[4][4], i, j;
// clrscr();
printf("Enter element of first matrix :\n"); for (i = 0; i < 4; i++)

{
for (j = 0; j < 4; j++)
{
printf("Enter matrix element :");
scanf("%d", &a[i][j]);
}
}
printf("\nEnter the elementof second matrix :\n");
for (i = 0; i < 4; i++)

{
for (j = 0; j < 4; j++)
{
printf("Enter matrix element :");
scanf("%d", &b[i][j]);
}
}
// Addition of matrix : /
for (i = 0; i < 4; i++)

{
for (j = 0; j < 4; j++)
c[i][j] = a[i][j] + b[i][j];
}
printf("\naddition of 1 and 2 matrix : \n\n"); for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
printf("%d\t", c[i][j]);
printf("\n");
}
}
Output:-

Size of word:-

#include <stdio.h>
int main()
{
char str[20];
int i, count = 0;
// clrser();

printf("\n Enter a string : ");


gets(str);
for (i = 0; str[i] != '\0'; i++) count++;
printf("\n Length of the string is : %d\n", count);
printf("\n *** Here we are finding the address of elemnts *** : \n");
char *p = &str[0];
printf("\nThe address of the first array element : %p", p);
p = str;
printf("\nThe address obtained from the array name: %p\n", p); return 0;
Output:-

Question -2: Simulate a stack, queue, circular queue and dequeue using a one-
dimensional array as a storage element. The program should implement the
basic addition, deletion and traversal operations.
Solution:-
Stack:-
#include <stdio.h> #include <stdlib.h>
#include<cstring>
#include<cstdlib>
#include <limits.h> // For INT_MIN

#define SIZE 100

// Create a stack with capacity of 100 elements


int stack[SIZE];

// Initially stack is empty


int top = -1;

/* Function declaration to perform push and pop on stack */


void push(int element); int pop();

int main()
{
int choice, data;

while (1)
{
/* Menu */
printf(" \n"); printf(" STACK IMPLEMENTATION PROGRAM \n");
printf(" \n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Size\n");
printf("4. Exit\n");
printf(" \n"); printf("Enter your choice: ");
scanf("%d", &choice); switch (choice)
{
case 1:
printf("Enter data to push into stack: ");
scanf("%d", &data);
// Push element to stack
push(data); break;

case 2:
data = pop();

// If stack is not empty


if (data != INT_MIN)
printf("Data => %d\n", data); break;

case 3:
printf("Stack size: %d\n", top + 1); break;

case 4:
printf("Exiting from app.\n");
exit(0);
break;

default:
printf("Invalid choice, please try again.\n");
}

printf("\n\n");
}

return 0;
}

/**
* Functiont to push a new element in stack.
*/
void push(int element)
{
// Check stack overflow
if (top >= SIZE)
{
printf("Stack Overflow, can't add more element element to stack.\n");
return;
}

// Increase element count in stack


top++;

// Push element in stack


stack[top] = element;
printf("Data pushed to stack.\n");
}

/**
* Function to pop element from top of stack.
*/
int pop()
{
// Check stack underflow
if (top < 0)
{
printf("Stack is empty.\n");

// Throw empty stack error/exception


// Since C does not have concept of exception
// Hence return minimum integer value as error value
// Later in code check if return value is INT_MIN, then
// stack is empty
return INT_MIN;
}

// Return stack top and decrease element count in stack


return stack[top--];
}

Output:-

Queue:-
#include <stdio.h> #include <stdlib.h> #define MAX 50

void insert(); void delete (); void display();


int queue_array[MAX]; int rear = -1;
int front = -1; int main()
{
int choice; while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n"); printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice); switch (choice)
{
case 1:
insert(); break;
case 2:
delete (); break;
case 3:
display(); break;
case 4:
exit(1); default:
printf("Wrong choice \n");
} /* End of switch */
} /* End of while */
} /* End of main() */
void insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n"); else
{
if (front == -1)
/*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item); rear = rear + 1;
queue_array[rear] = add_item;
}
} /* End of insert() */

void delete()
{
if (front == -1 || front > rear)
{
printf("Queue Underflow \n"); return;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /* End of delete() */
void display()
{
int i;
if (front == -1)
printf("Queue is empty \n"); else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
}

Output:-
Circular Queue:-
#include <stdio.h> #define MAX 5
int cqueue_arr[MAX]; int front = -1;
int rear = -1;
void insert(int item)
{
if ((front == 0 && rear == MAX - 1) || (front == rear + 1))
{
printf("Queue Overflow n"); return;
}
if (front == -1)
{
front = 0;
rear = 0;
}
else
{
if (rear == MAX - 1) rear = 0;
else
rear = rear + 1;
}
cqueue_arr[rear] = item;
}
void deletion()
{
if (front == -1)
{
printf("Queue Underflown"); return;
}
printf("Element deleted from queue is : %dn", cqueue_arr[front]); if (front
== rear)
{
front = -1;
rear = -1;
}
else
{
if (front == MAX - 1) front = 0;
else
front = front + 1;
}
}

void display()
{
int front_pos = front, rear_pos = rear; if (front == -1)
{
printf("Queue is emptyn"); return;
}
printf("Queue elements :n"); if (front_pos <= rear_pos)
while (front_pos <= rear_pos)
{
}
else
{

printf("%d ", cqueue_arr[front_pos]); front_pos++;

while (front_pos <= MAX - 1)


{
printf("%d ", cqueue_arr[front_pos]); front_pos++;
}
front_pos = 0;
while (front_pos <= rear_pos)
{
printf("%d ", cqueue_arr[front_pos]); front_pos++;
}
}
printf("n");
}
int main()
{
int choice, item; do
{
printf("1.Insertn"); printf("2.Deleten"); printf("3.Displayn"); printf("4.Quitn");
printf("Enter your choice : "); scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Input the element for insertion in queue : ");
scanf("%d", &item);
insert(item);
break; case 2:
deletion(); break;
case 3:
display(); break;
case 4:
break; default:
printf("Wrong choicen");
}
} while (choice != 4); return 0;
}
Output:-

Dequeue:-
#include <stdio.h> #define MAX 5
int deque_arr[MAX]; int left = -1;
int right = -1; void insert_right()
{
int added_item;
if ((left == 0 && right == MAX - 1) || (left == right + 1))
{
printf("Queue Overflow\n"); return;
}
if (left == -1) /* if queue is initially empty */
{
left = 0;
right = 0;
}
else if (right == MAX - 1) /*right is at last position of queue */
right = 0; else
right = right + 1;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item); deque_arr[right] = added_item;
}
void insert_left()
{
int added_item;
if ((left == 0 && right == MAX - 1) || (left == right + 1))
{
printf("Queue Overflow \n"); return;
}
if (left == -1) /*If queue is initially empty*/
{
left = 0;
right = 0;
}
else if (left == 0) left = MAX - 1;
else
left = left - 1;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item); deque_arr[left] = added_item;
}

void delete_left()
{
if (left == -1)
{
printf("Queue Underflow\n"); return;
}
printf("Element deleted from queue is : %d\n", deque_arr[left]); if (left ==
right) /*Queue has only one element */
{
left = -1;
right = -1;
}
else if (left == MAX - 1) left = 0;
else
left = left + 1;
}
void delete_right()
{
if (left == -1)
{
printf("Queue Underflow\n"); return;
}
printf("Element deleted from queue is : %d\n", deque_arr[right]); if (left ==
right) /*queue has only one element*/
{
left = -1;
right = -1;
}
else if (right == 0) right = MAX - 1;
else
right = right - 1;
}
void display_queue()
{
int front_pos = left, rear_pos = right; if (left == -1)
{
printf("Queue is empty\n"); return;
}
printf("Queue elements :\n"); if (front_pos <= rear_pos)
{
while (front_pos <= rear_pos)

{
printf("%d ", deque_arr[front_pos]); front_pos++;
}
}
else
{
while (front_pos <= MAX - 1)
{
printf("%d ", deque_arr[front_pos]); front_pos++;
}
front_pos = 0;
while (front_pos <= rear_pos)
{
printf("%d ", deque_arr[front_pos]); front_pos++;
}
}
printf("\n");
}
void input_que()
{
int choice; do
{
printf("1.Insert at right\n"); printf("2.Delete from left\n");
printf("3.Delete from right\n"); printf("4.Display\n"); printf("5.Quit\n");
printf("Enter your choice : "); scanf("%d", &choice);

switch (choice)
{
case 1:
insert_right(); break;
case 2:
delete_left(); break;
case 3:
delete_right(); break;
case 4:
display_queue(); break;

case 5:
break; default:
printf("Wrong choice\n");
}
} while (choice != 5);
}
void output_que()
{
int choice; do
{
printf("1.Insert at right\n"); printf("2.Insert at left\n");
printf("3.Delete from left\n"); printf("4.Display\n"); printf("5.Quit\n");
printf("Enter your choice : "); scanf("%d", &choice);
switch (choice)
{
case 1:
insert_right(); break;
case 2:
insert_left(); break;
case 3:
delete_left(); break;
case 4:
display_queue(); break;
case 5:
break; default:
printf("Wrong choice\n");
}
} while (choice != 5);
}
int main()
{
int choice;
printf("1.Input restricted dequeue\n"); printf("2.Output restricted dequeue\n");
printf("Enter your choice : "); scanf("%d", &choice);
switch (choice)
{
case 1:
input_que(); break;
case 2:
output_que(); break;
default:
printf("Wrong choice\n");
}
}
Output:-

Question-3: Represent a 2-variable polynomial using array. Use this


representation to implement addition of polynomials.
Solutions:-
#include <stdio.h>

int main(){
int poly_first[10], poly_second[10], poly_sum[10], first_term,
second_terms, a, m, n, y, b;
printf("\nAdding Polynomial using arrays\n");
printf("\nNumber of terms for the first polynomial:");
scanf("%d", &first_term);
printf("\nEnter terms and coefficient for the first polynomial:\n");
for (n = 0; n < 2 * first_term; n++)
scanf("%d", &poly_first[n]); printf("\n\The first polynomial:\n"); m = 0;
if (poly_first[m + 1] == 1)
printf("x^%d", poly_first[m]); else
printf("%dx^%d", poly_first[m + 1], poly_first[m]); m += 2;
while (m < n)
{
printf("+%dx^%d", poly_first[m + 1], poly_first[m]); m += 2;
}
printf("\nTotal terms for the second polynomial:\n");
scanf("%d", &second_terms);
printf("\nEnter terms and coefficient for the second polynomial:\n");
for (y = 0; y < 2 * second_terms; y++)
scanf("%d", &poly_second[y]); printf("The Second polynomial:\n"); m = 0;
if (poly_second[m + 1] == 1)
printf("x^%d", poly_second[m]); else
printf("%dx^%d", poly_second[m + 1], poly_second[m]); m += 2;
while (m < 2 * second_terms)
{
printf("+%dx^%d", poly_second[m + 1], poly_second[m]); m += 2;
}
n = 0;
y = 0;
a = 0;

while (first_term > 0 && second_terms > 0)


{
if (poly_first[n] == poly_second[y])
{
poly_sum[a + 1] = poly_first[n + 1] + poly_second[y + 1];
poly_sum[a] = poly_first[n];
first_term--; second_terms--; n += 2;
y += 2;
}
else if (poly_first[n] > poly_second[y])
{
poly_sum[a + 1] = poly_first[n + 1]; poly_sum[a] = poly_first[n];
first_term--;
n += 2;
}
else
{
poly_sum[a + 1] = poly_second[y + 1]; poly_sum[a] = poly_second[y];
second_terms--;
y += 2;
}
a += 2;
}
while (first_term > 0)
{
poly_sum[a + 1] = poly_first[n + 1]; poly_sum[a] = poly_first[n];
a += 2;
n += 2;
first_term--;
}
while (second_terms > 0)
{
poly_sum[a + 1] = poly_second[y + 1]; poly_sum[a] = poly_second[y];
a += 2;
y += 2;
second_terms--;
}
printf("\nThe sum polynomial is:"); m = 0;
if (poly_sum[m + 1] == 1)
printf("x^%d", poly_sum[m]); else
printf("%dx^%d", poly_sum[m + 1], poly_sum[m]); m += 2;
while (m < a)
{
if (poly_sum[m + 1] == 1)
printf("+x^%d", poly_sum[m]); else
printf("+%dx^%d", poly_sum[m + 1], poly_sum[m]); m += 2;
}
return 0;
}

Output:-

Question-4: Represent a sparse matrix using array implement addition and


transposition operations using the representation.
Solution:-
#include <stdio.h>
int main()
{
int sparseMatrix[4][5] =
{
{0, 0, 3, 0, 4},
{0, 0, 5, 7, 0},
{0, 0, 0, 0, 0},
{0, 2, 6, 0, 0}};

int size = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0) size++;
int compactMatrix[3][size]; int k = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
{
compactMatrix[0][k] = i; compactMatrix[1][k] = j;
compactMatrix[2][k] = sparseMatrix[i][j]; k++;
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < size; j++)
printf("%d ", compactMatrix[i][j]);
printf("\n");
}
return 0;
}

Output:-

Question-5 Implement singly, doubly and circularly connected linked lists


illustrating operations like addition at different locations, deletion from specified
locations and traversal.
Solution:-
Singly linked list:
#include <stdio.h>
#include <stdlib.h>
// Create a node
struct Node
{
int data;
struct Node *next;
};
// Insert at the beginning
void insertAtBeginning(struct Node **head_ref, int new_data)
{
// Allocate memory to a node
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));

// insert the data


new_node->data = new_data; new_node->next = (*head_ref);
// Move head to new node
(*head_ref) = new_node;
}

// Insert a node after a node


void insertAfter(struct Node *prev_node, int new_data)
{
if (prev_node == NULL)
{
printf("the given previous node cannot be NULL"); return;
}

struct Node *new_node = (struct Node *)malloc(sizeof(struct Node)); new_node-


>data = new_data;
new_node->next = prev_node->next; prev_node->next = new_node;
}

// Insert the the end


void insertAtEnd(struct Node **head_ref, int new_data)
{
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
struct Node *last = *head_ref; /* used in step 5*/

new_node->data = new_data; new_node->next = NULL;

if (*head_ref == NULL)
{
*head_ref = new_node; return;
}

while (last->next != NULL) last = last->next;

last->next = new_node; return;


}

// Delete a node
void deleteNode(struct Node **head_ref, int key)
{
struct Node *temp = *head_ref, *prev;

if (temp != NULL && temp->data == key)


{
*head_ref = temp->next;
free(temp); return;
}
// Find the key to be deleted
while (temp != NULL && temp->data != key)
{
prev = temp;
temp = temp->next;
}

// If the key is not present


if (temp == NULL) return;

// Remove the node


prev->next = temp->next;

free(temp);
}
// Search a node

int searchNode(struct Node **head_ref, int key)


{
struct Node *current = *head_ref;

while (current != NULL)


{
if (current->data == key) return 1;
current = current->next;
}
return 0;
}

// Sort the linked list


void sortLinkedList(struct Node **head_ref)
{
struct Node *current = *head_ref, *index = NULL; int temp;

if (head_ref == NULL)
{
return;
}
else
{
while (current != NULL)
{
// index points to the node next to current
index = current->next;

while (index != NULL)


{
if (current->data > index->data)
{
temp = current->data; current->data = index->data; index->data = temp;
}
index = index->next;
}
current = current->next;
}
}
}

// Print the linked list


void printList(struct Node *node)
{
while (node != NULL)
{
printf(" %d ", node->data); node = node->next;
}
}
// Driver program
int main()
{
struct Node *head = NULL; insertAtEnd(&head, 1);
insertAtBeginning(&head, 2);
insertAtBeginning(&head, 3);
insertAtEnd(&head, 4);
insertAfter(head->next, 5);

printf("Linked list: ");


printList(head);

printf("\nAfter deleting an element: ");


deleteNode(&head, 3);
printList(head);
int item_to_find = 3;
if (searchNode(&head, item_to_find))
{
printf("\n%d is found", item_to_find);
}
else
{
printf("\n%d is not found", item_to_find);
}
sortLinkedList(&head); printf("\nSorted List: "); printList(head);
}

Output:-

Doubly:-
#include <stdio.h>
#include <stdlib.h>

// A linked list node


struct Node
{
int data;
struct Node *next; struct Node *prev;
};

/* Given a reference (pointer to pointer) to the head of a


list and an int, inserts a new node on the front of the list. */
void push(struct Node **head_ref, int new_data)
{
/* 1. allocate node */
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));

/* 2. put in the data */


new_node->data = new_data;

/* 3. Make next of new node as head and previous as NULL


*/
new_node->next = (*head_ref); new_node->prev = NULL;

/* 4. change prev of head node to new node */


if ((*head_ref) != NULL) (*head_ref)->prev = new_node;

/* 5. move the head to point to the new node */


(*head_ref) = new_node;
}

/* Given a node as prev_node, insert a new node after the


* given node */
void insertAfter(struct Node *prev_node, int new_data)
{
/*1. check if the given prev_node is NULL */
if (prev_node == NULL)
{
printf("the given previous node cannot be NULL"); return;
}

/* 2. allocate new node */

struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));

/* 3. put in the data */


new_node->data = new_data;

/* 4. Make next of new node as next of prev_node */


new_node->next = prev_node->next;

/* 5. Make the next of prev_node as new_node */


prev_node->next = new_node;

/* 6. Make prev_node as previous of new_node */


new_node->prev = prev_node;

/* 7. Change previous of new_node's next node */


if (new_node->next != NULL) new_node->next->prev = new_node;
}

/* Given a reference (pointer to pointer) to the head


of a DLL and an int, appends a new node at the end */
void append(struct Node **head_ref, int new_data)
{
/* 1. allocate node */
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));

struct Node *last = *head_ref; /* used in step 5*/

/* 2. put in the data */


new_node->data = new_data;

/* 3. This new node is going to be the last node, so


make next of it as NULL*/
new_node->next = NULL;
/* 4. If the Linked List is empty, then make the new node as head */
if (*head_ref == NULL)
{
new_node->prev = NULL;
*head_ref = new_node; return;
}

/* 5. Else traverse till the last node */


while (last->next != NULL) last = last->next;

/* 6. Change the next of last node */


last->next = new_node;

/* 7. Make last node as previous of new node */


new_node->prev = last;

return;
}

// This function prints contents of linked list starting


// from the given node
void printList(struct Node *node)
{
struct Node *last;
printf("\nTraversal in forward direction \n"); while (node != NULL)
{
printf(" %d ", node->data); last = node;
node = node->next;
}

printf("\nTraversal in reverse direction \n"); while (last != NULL)


{
printf(" %d ", last->data); last = last->prev;
}
}

/* Driver program to test above functions*/


int main()
{
/* Start with the empty list */
struct Node *head = NULL;

// Insert 6. So linked list becomes 6->NULL


append(&head, 6);

// Insert 7 at the beginning. So linked list becomes


// 7->6->NULL
push(&head, 7);

// Insert 1 at the beginning. So linked list becomes


// 1->7->6->NULL
push(&head, 1);

// Insert 4 at the end. So linked list becomes


// 1->7->6->4->NULL
append(&head, 4);
// Insert 8, after 7. So linked list becomes
// 1->7->8->6->4->NULL
insertAfter(head->next, 8);

printf("Created DLL is: ");


printList(head);

getchar(); return 0;
}

Output:-

Circularly:-
#include <stdio.h>
#include <stdlib.h>

// Structure of a linked list node


struct node
{
int info;
struct node *next;
};
// Pointer to last node in the list
struct node *last = NULL;

// Function to insert a node in the


// starting of the list
void insertAtFront()
{
// Stores the number to be inserted
int data;

// Initialize a new node


struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));

// Input data
printf("\nEnter data to be " "inserted: \n");
scanf("%d", &data);

// If the new node is the only


// node in the list
if (last == NULL)
{
temp->info = data; temp->next = temp; last = temp;
}

// Else last node contains the


// reference of the new node and
// new node contains the reference
// of the previous first node
else
{
temp->info = data;
temp->next = last->next;

// last node now has reference


// of the new node temp
last->next = temp;
}
}

// Function to print the list


void viewList()
{
// If list is empty
if (last == NULL)
printf("\nList is empty\n");

// Else print the list


else
{
struct node *temp; temp = last->next;

// While first node is not


// reached again, print,
// since the list is circular
do
{
printf("\nData = %d", temp->info); temp = temp->next;
} while (temp != last->next);
}
}
// Driver Code
int main() {
// Function Call insertAtFront(); insertAtFront(); insertAtFront();
// Print list
viewList();

return 0;
}
Output:-

Question-6: Implementation of binary tree with operations like addition, deletion,


traversal.
Solution:-
#include <stdlib.h>
include <stdio.h>
struct bin_tree {
int data;
struct bin_tree *right, *left;
};
typedef struct bin_tree node;
void insert(node **tree, int val) {
node *temp = NULL; if (!(*tree))
{
temp = (node *)malloc(sizeof(node));
temp->left = temp->right = NULL;
temp->data = val;
*tree = temp;
return;
}
if (val < (*tree)->data)
{
insert(&(*tree)->left, val);
}
else if (val > (*tree)->data)
{
insert(&(*tree)->right, val);
}
}
void print_preorder(node *tree)
{
if (tree)
{
printf("%d\n", tree->data);
print_preorder(tree->left);
print_preorder(tree->right);
}
}
void print_inorder(node *tree)
{
if (tree)
{
print_inorder(tree->left);
printf("%d\n", tree->data);
print_inorder(tree->right);
}
}

void print_postorder(node *tree) { if (tree) {


print_postorder(tree->left);
print_postorder(tree->right);
printf("%d\n", tree->data);
}
}
void deltree(node *tree) { if (tree) {
deltree(tree->left);
deltree(tree->right);
free(tree);
}
}
node *search(node **tree, int val) { if (!(*tree)) {
return NULL;
}
if (val < (*tree)->data) {
search(&((*tree)->left), val);
}
else if (val > (*tree)->data){
search(&((*tree)->right), val);
}
else if (val == (*tree)->data){ return *tree;
}
}
void main() {
node *root;
node *tmp;
// int i;
root = NULL;
/* Inserting nodes into tree */
insert(&root, 9);
insert(&root, 4);
insert(&root, 15);
insert(&root, 6);
insert(&root, 12);
insert(&root, 17);
insert(&root, 2);
/* Printing nodes of tree */ printf("Pre Order Display\n"); print_preorder(root);
printf("In Order Display\n"); print_inorder(root);
printf("Post Order Display\n"); print_postorder(root);
/* Search node into tree */
tmp = search(&root, 4); if (tmp) {
printf("Searched node=%d\n", tmp->data);
}
else {
printf("Data Not found in tree.\n");
}
/* Deleting all nodes of tree */
deltree(root);
}

Output:-

Question-7: Depth first and breadth first traversal of graph represented using
adjacency matrix and list.
Solution:-
Depth First Transversal
// C code to implement above approach
#include <stdio.h>
#include <stdlib.h>

// Globally declared visited array


int vis[100];

// Graph structure to store number


// of vertices and edges and
// Adjacency matrix
struct Graph
{
int V; int E;
int **Adj;
};

// Function to input data of graph


struct Graph *adjMatrix()
{
struct Graph *G = (struct Graph *)
malloc(sizeof(struct Graph)); if (!G)
{
printf("Memory Error\n"); return NULL;
}
G->V = 7;
G->E = 7;

G->Adj = (int **)malloc((G->V) * sizeof(int *)); for (int k = 0; k < G-


>V; k++)
{
G->Adj[k] = (int *)malloc((G->V) * sizeof(int));
}

for (int u = 0; u < G->V; u++)


{
for (int v = 0; v < G->V; v++)
{
G->Adj[u][v] = 0;
}
}
G->Adj[0][1] = G->Adj[1][0] = 1;
G->Adj[0][2] = G->Adj[2][0] = 1;
G->Adj[1][3] = G->Adj[3][1] = 1;
G->Adj[1][4] = G->Adj[4][1] = 1;
G->Adj[1][5] = G->Adj[5][1] = 1;
G->Adj[1][6] = G->Adj[6][1] = 1;
G->Adj[6][2] = G->Adj[2][6] = 1;

return G;
}

// DFS function to print DFS traversal of graph


void DFS(struct Graph *G, int u)
{
vis[u] = 1;
printf("%d ", u);
for (int v = 0; v < G->V; v++)
{
if (!vis[v] && G->Adj[u][v])
{
DFS(G, v);
}
}
}

// Function for DFS traversal


void DFStraversal(struct Graph *G)
{
for (int i = 0; i < 100; i++)
{
vis[i] = 0;
}
for (int i = 0; i < G->V; i++) { if (!vis[i])
{
DFS(G, i);
}
}
}
// Driver code
void main()
{
struct Graph *G; G = adjMatrix(); DFStraversal(G);
}

Output:-

Breadth first traversal:-


#include <stdio.h>
#include <conio.h>
int a[20][20], q[20], visited[20], n, i, j, f = 0, r = -1; void
bfs(int v)
{
for (i = 1; i <= n; i++)
if (a[v][i] && !visited[i]) q[++r] = i;
if (f <= r){
visited[q[f]] = 1;
bfs(q[f++]);
}
}
void main(){
int v;
printf("n Enter the number of vertices:");
scanf("%d", &n);
for (i = 1; i <= n; i++) { q[i] = 0;
visited[i] = 0;
}
printf("n Enter graph data in matrix form:n");
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
scanf("%d", &a[i][j]); printf("n Enter the starting vertex:");
scanf("%d", &v);
bfs(v);
printf("n The node which are reachable are:n");
for (i = 1; i <= n; i++)
if (visited[i])
printf("%dt", i); else
printf("n Bfs is not possible");
getch();
}

Output:-

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy