Practical Exam Flashcards

1
Q

gi3. BST of integers, pre-order and post-order

A

Pre-order traversal in BST
Data Left Right

int preOrder(){

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

explain what is adjency matrix

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

what are some characteristics of adjacency matrix

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

how to build adjacency matrix

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

how to accept graph as an adjacency matrix

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

applications of adjacency matrix

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

some advantages and disadvantages of adjacency matrix

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Implement DFS in C and accept graph as an adjacency matrix

A

include <stdio.h></stdio.h>

#include <stdlib.h></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 create and initialize the adjacency matrix for the graph
struct Graph* createGraph(int vertices) {
struct Graph* G = (struct Graph*)malloc(sizeof(struct Graph));
if (!G) {
printf(“Memory Error\n”);
return NULL;
}
G->V = vertices;
G->E = 0;

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 v = 0; v < G->V; v++) {
        G->Adj[k][v] = 0; // Initialize adjacency matrix to 0
    }
}
return G; }

// Function to add an edge to the graph
void addEdge(struct Graph* G, int u, int v) {
if (u >= 0 && u < G->V && v >= 0 && v < G->V) {
G->Adj[u][v] = 1;
G->Adj[v][u] = 1; // Undirected graph
G->E++;
} else {
printf(“Invalid vertices!\n”);
}
}

// 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 < G->V; i++) {
vis[i] = 0; // Reset visited array
}
for (int i = 0; i < G->V; i++) {
if (!vis[i]) {
DFS(G, i);
}
}
}

// Function to display the adjacency matrix
void displayAdjacencyMatrix(struct Graph* G) {
printf(“Adjacency Matrix:\n”);
for (int i = 0; i < G->V; i++) {
for (int j = 0; j < G->V; j++) {
printf(“%d “, G->Adj[i][j]);
}
printf(“\n”);
}
}

// Function to free the graph memory
void freeGraph(struct Graph* G) {
for (int i = 0; i < G->V; i++) {
free(G->Adj[i]);
}
free(G->Adj);
free(G);
}

// Driver code with menu
int main() {
struct Graph* G = createGraph(7);
int choice, u, v;

while (1) {
    printf("\nMenu:\n");
    printf("1. Add Edge\n");
    printf("2. Display Adjacency Matrix\n");
    printf("3. Perform DFS Traversal\n");
    printf("4. Exit\n");
    printf("Enter your choice: ");
    scanf("%d", &choice);

    switch (choice) {
        case 1:
            printf("Enter vertices to add an edge (u v): ");
            scanf("%d %d", &u, &v);
            addEdge(G, u, v);
            break;
        case 2:
            displayAdjacencyMatrix(G);
            break;
        case 3:
            printf("DFS Traversal: ");
            DFStraversal(G);
            printf("\n");
            break;
        case 4:
            freeGraph(G);
            exit(0);
        default:
            printf("Invalid choice! Please try again.\n");
    }
}

return 0; }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

doubly linked list, create insert and display operation

A

include<stdio.h></stdio.h>

#include<stdlib.h>
struct node
{
struct node *prev;
struct node *next;
int data;
};
struct node *head;
void insertion_beginning();
void insertion_last();
void insertion_specified();
void deletion_beginning();
void deletion_last();
void deletion_specified();
void display();
void search();
void main ()
{
int choice =0;
while(choice != 9)
{
printf("\n*********Main Menu*********\n");
printf("\nChoose one option from the following list ...\n");
printf("\n===============================================\n");
printf("\n1.Insert in begining\n2.Insert at last\n3.Insert at any random location\n4.Delete from Beginning\n");
printf("5.Delete from last\n6.Delete the node after the given data\n7.Search\n8.Show\n9.Exit\n");
printf("\nEnter your choice?\n");
scanf("\n%d",&choice);
switch(choice)
{
case 1:
insertion_beginning();
break;
case 2:
insertion_last();
break;
case 3:
insertion_specified();
break;
case 4:
deletion_beginning();
break;
case 5:
deletion_last();
break;
case 6:
deletion_specified();
break;
case 7:
search();
break;
case 8:
display();
break;
case 9:
exit(0);
break;
default:
printf("Please enter valid choice..");
}
}
}
void insertion_beginning()
{
struct node *ptr;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter Item value");
scanf("%d",&item);</stdlib.h>

if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
ptr->data=item;
head=ptr;
}
else
{
ptr->data=item;
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
}
printf(“\nNode inserted\n”);
}

}
void insertion_last()
{
struct node ptr,temp;
int item;
ptr = (struct node *) malloc(sizeof(struct node));
if(ptr == NULL)
{
printf(“\nOVERFLOW”);
}
else
{
printf(“\nEnter value”);
scanf(“%d”,&item);
ptr->data=item;
if(head == NULL)
{
ptr->next = NULL;
ptr->prev = NULL;
head = ptr;
}
else
{
temp = head;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = ptr;
ptr ->prev=temp;
ptr->next = NULL;
}

   }  
 printf("\nnode inserted\n");  
}   void insertion_specified()   {      struct node *ptr,*temp;      int item,loc,i;      ptr = (struct node *)malloc(sizeof(struct node));      if(ptr == NULL)      {  
   printf("\n OVERFLOW");      }      else      {  
   temp=head;  
   printf("Enter the location");  
   scanf("%d",&loc);  
   for(i=0;i<loc;i++)  
   {  
       temp = temp->next;  
       if(temp == NULL)  
       {  
           printf("\n There are less than %d elements", loc);  
           return;  
       }  
   }  
   printf("Enter value");  
   scanf("%d",&item);  
   ptr->data = item;  
   ptr->next = temp->next;  
   ptr -> prev = temp;  
   temp->next = ptr;  
   temp->next->prev=ptr;  
   printf("\nnode inserted\n");      }   }   void deletion_beginning()   {  
struct node *ptr;  
if(head == NULL)  
{  
    printf("\n UNDERFLOW");  
}  
else if(head->next == NULL)  
{  
    head = NULL;   
    free(head);  
    printf("\nnode deleted\n");  
}  
else  
{  
    ptr = head;  
    head = head -> next;  
    head -> prev = NULL;  
    free(ptr);  
    printf("\nnode deleted\n");  
}  

}
void deletion_last()
{
struct node *ptr;
if(head == NULL)
{
printf(“\n UNDERFLOW”);
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf(“\nnode deleted\n”);
}
else
{
ptr = head;
if(ptr->next != NULL)
{
ptr = ptr -> next;
}
ptr -> prev -> next = NULL;
free(ptr);
printf(“\nnode deleted\n”);
}
}
void deletion_specified()
{
struct node *ptr, *temp;
int val;
printf(“\n Enter the data after which the node is to be deleted : “);
scanf(“%d”, &val);
ptr = head;
while(ptr -> data != val)
ptr = ptr -> next;
if(ptr -> next == NULL)
{
printf(“\nCan’t delete\n”);
}
else if(ptr -> next -> next == NULL)
{
ptr ->next = NULL;
}
else
{
temp = ptr -> next;
ptr -> next = temp -> next;
temp -> next -> prev = ptr;
free(temp);
printf(“\nnode deleted\n”);
}
}
void display()
{
struct node *ptr;
printf(“\n printing values…\n”);
ptr = head;
while(ptr != NULL)
{
printf(“%d\n”,ptr->data);
ptr=ptr->next;
}
}
void search()
{
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
{
printf(“\nEmpty List\n”);
}
else
{
printf(“\nEnter item which you want to search?\n”);
scanf(“%d”,&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf(“\nitem found at location %d “,i+1);
flag=0;
break;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf(“\nItem not found\n”);
}
}

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

WAP in C to implement dynamic implementation of queue of integers with following operation

initialize()
push()
pop()
isempty()
display()

A

include <stdio.h></stdio.h>

#include <stdlib.h></stdlib.h>

// Node structure for linked list
struct Node {
int data;
struct Node* next;
};

// Queue structure
struct Queue {
struct Node* front;
struct Node* rear;
};

// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to initialize the queue
struct Queue* createQueue() {
struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->front = NULL;
queue->rear = NULL;
return queue;
}

// Function to check if the queue is empty
int isEmpty(struct Queue* queue) {
return queue->front == NULL;
}

// Function to insert an element into the queue (enqueue)
void enqueue(struct Queue* queue, int data) {
struct Node* newNode = createNode(data);
if (queue->rear == NULL) {
queue->front = queue->rear = newNode;
return;
}
queue->rear->next = newNode;
queue->rear = newNode;
}

// Function to remove an element from the queue (dequeue)
int dequeue(struct Queue* queue) {
if (isEmpty(queue)) {
printf(“Queue is empty. Cannot dequeue.\n”);
return -1; // Return -1 to indicate queue is empty
}
struct Node* temp = queue->front;
int data = temp->data;
queue->front = queue->front->next;
if (queue->front == NULL) {
queue->rear = NULL;
}
free(temp);
return data;
}

// Function to display the queue
void display(struct Queue* queue) {
if (isEmpty(queue)) {
printf(“Queue is empty.\n”);
return;
}
struct Node* temp = queue->front;
printf(“Queue elements: “);
while (temp != NULL) {
printf(“%d “, temp->data);
temp = temp->next;
}
printf(“\n”);
}

// Main function with menu
int main() {
struct Queue* queue = createQueue();
int choice, data;

while (1) {
    printf("\nMenu:\n");
    printf("1. Enqueue\n");
    printf("2. Dequeue\n");
    printf("3. Display\n");
    printf("4. Check if empty\n");
    printf("5. Exit\n");
    printf("Enter your choice: ");
    scanf("%d", &choice);

    switch (choice) {
        case 1:
            printf("Enter data to enqueue: ");
            scanf("%d", &data);
            enqueue(queue, data);
            break;
        case 2:
            data = dequeue(queue);
            if (data != -1) {
                printf("Dequeued: %d\n", data);
            }
            break;
        case 3:
            display(queue);
            break;
        case 4:
            if (isEmpty(queue)) {
                printf("Queue is empty.\n");
            } else {
                printf("Queue is not empty.\n");
            }
            break;
        case 5:
            printf("Exiting...\n");
            free(queue);
            exit(0);
        default:
            printf("Invalid choice. Please try again.\n");
    }
}

return 0; }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

WAP to implement static queue and perform this operations: init(),
insert(),
display(),
isfull()

A

include <stdio.h></stdio.h>

#include <stdlib.h></stdlib.h>

typedef struct {
int items[MAX];
int front;
int rear;
} StaticQueue;

// Function to initialize the queue
void init(StaticQueue *q) {
q->front = -1;
q->rear = -1;
printf(“Queue initialized.\n”);
}

// Function to check if the queue is full
int isfull(StaticQueue *q) {
return (q->rear + 1) % MAX == q->front;
}

// Function to insert an element into the queue
void insert(StaticQueue *q, int value) {
if (isfull(q)) {
printf(“Queue is full. Cannot insert %d.\n”, value);
return;
}
if (q->front == -1) { // If queue is empty
q->front = 0;
}
q->rear = (q->rear + 1) % MAX;
q->items[q->rear] = value;
printf(“Inserted %d into the queue.\n”, value);
}

// Function to display the elements of the queue
void display(StaticQueue *q) {
if (q->front == -1) {
printf(“Queue is empty.\n”);
return;
}
printf(“Queue elements: “);
int i = q->front;
while (1) {
printf(“%d “, q->items[i]);
if (i == q->rear) {
break;
}
i = (i + 1) % MAX;
}
printf(“\n”);
}

// Main function to drive the menu
int main() {
StaticQueue q;
int choice, value;

while (1) {
    printf("\nMenu:\n");
    printf("1. Initialize Queue\n");
    printf("2. Insert Element\n");
    printf("3. Display Queue\n");
    printf("4. Check if Queue is Full\n");
    printf("5. Exit\n");
    printf("Enter your choice: ");
    scanf("%d", &choice);

    switch (choice) {
        case 1:
            init(&q);
            break;
        case 2:
            printf("Enter value to insert: ");
            scanf("%d", &value);
            insert(&q, value);
            break;
        case 3:
            display(&q);
            break;
        case 4:
            if (isfull(&q)) {
                printf("Queue is full.\n");
            } else {
                printf("Queue is not full.\n");
            }
            break;
        case 5:
            printf("Exiting...\n");
            exit(0);
        default:
            printf("Invalid choice. Please try again.\n");
    }
}

return 0; }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Explain above program

A

StaticQueue Structure: This structure holds the queue items, the front index, and the rear index.

init(): Initializes the queue by setting the front and rear indices to -1.

isfull(): Checks if the queue is full.

insert(): Inserts an element into the queue if it is not full.

display(): Displays the elements in the queue.

Menu-driven Interface: The main() function provides a menu for the user to interact with the queue.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How to Compile and Run:

A

Copy the code into a file named static_queue.c.
Open a terminal and navigate to the directory where the file is saved.
Compile the code using gcc static_queue.c -o static_queue.
Run the program using ./static_queue.
You can then follow the on-screen menu to perform operations on the static queue.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

WAP in C to reverse given string using stack.

Intuition and approach

A

Intuition: Stack is a Last-In-First-Out (LIFO) data structure. If we iterate over the string and push each character from start to end, the stack will contain the string in a reverse way.

Approach:

Take an empty stack
Iterate over the given string from start to end.
In each iteration, push the character at index i to the stack.
After the first loop is completed, set a while loop till the stack is non-empty.
Pop the character at the stack and start re-assigning the string.

17
Q

Code in C to reverse string using stack

A

include <stdio.h></stdio.h>

#include <stdlib.h>
#include <string.h></string.h></stdlib.h>

// Stack structure
typedef struct {
char items[MAX];
int top;
} Stack;

// Function to initialize the stack
void initStack(Stack *s) {
s->top = -1;
}

// Function to push an element onto the stack
void push(Stack *s, char item) {
s->items[++(s->top)] = item;
}

// Function to pop an element from the stack
char pop(Stack *s) {
return s->items[(s->top)–];
}

// Function to reverse a string using stack
void reverseString(char *str) {
Stack s;
initStack(&s);

// Push all characters of the string onto the stack
for (int i = 0; i < strlen(str); i++) {
    push(&s, str[i]);
}

// Pop all characters from the stack and put them back into the string
for (int i = 0; i < strlen(str); i++) {
    str[i] = pop(&s);
} }

int main() {
char str[MAX];

printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

// Remove newline character if present
str[strcspn(str, "\n")] = 0;

reverseString(str);
printf("Reversed string: %s\n", str);

return 0; }
18
Q

WAP in C to reverse given number using stack

A
19
Q

Write a menu driven program in C to perform this operations on Singly linked list:

create()
insert()
display()

A
20
Q

Write a C program to create a binary search tree of integers and perform following operations.
i. Pre-order traversal
ii. In-order traversal
iii. Post-order traversal

A
21
Q

Write a menu driven C program to perform following operations on a Circular Singly linked list

create(),
insert(),
display()

A

include <stdlib.h></stdlib.h>

#include <stdio.h></stdio.h>

struct node
{
int data;
struct node *next;
} *list = NULL, *p, *q;

int no = 0;

void create() {
for (int i = 1; i <= no; i++) {
p = (struct node *)malloc(sizeof(struct node));
printf(“Enter data for node %d: “, i);
scanf(“%d”, &p->data);

    if (list == NULL) {
        list = p;
        p->next = list; // Point to itself to create circularity
        q = p;
    } else {
        q->next = p;
        p->next = list; // Complete the circle
        q = p;
    }
} }

void display() {
if (list == NULL) {
printf(“List is empty\n”);
return;
}

struct node *t = list;
do {
    printf("\t %d", t->data);
    t = t->next;
} while (t != list);
printf("\n"); }

void insert(int pos) {
struct node *p = (struct node *)malloc(sizeof(struct node));
printf(“Enter data for the new node: “);
scanf(“%d”, &p->data);

if (pos == 1) {
    if (list == NULL) {
        list = p;
        p->next = list; // Point to itself to create circularity
    } else {
        p->next = list;

        q = list;
        while (q->next != list) {
            q = q->next;
        }
        q->next = p; // Update the last node's next pointer
        list = p;    // Update the head pointer
    }
} else {
    q = list;
    for (int i = 1; i < pos - 1; i++) {
        q = q->next;
    }
    p->next = q->next;
    q->next = p;
}
no++;
printf("Node inserted\n"); }

void delete(int pos) {
if (list == NULL) {
printf(“List is empty\n”);
return;
}

if (pos == 1) {
    if (list->next == list) {
        printf("Deleted node data: %d\n", list->data);
        free(list);
        list = NULL;
    } else {
        q = list;
        while (q->next != list) {
            q = q->next;
        }
        p = list;
        q->next = list->next;
        list = list->next;
        printf("Deleted node data: %d\n", p->data);
        free(p);
    }
} else {
    q = list;
    for (int i = 1; i < pos - 1; i++) {
        q = q->next;
    }
    p = q->next;
    q->next = p->next;
    printf("Deleted node data: %d\n", p->data);
    free(p);
}
no--; }

int main() {
int ch, pos;

do {
    printf("Enter number of nodes you want: ");
    scanf("%d", &no);
} while (no < 1);

create();

do {
    printf("\n1. Display linked list");
    printf("\n2. Insert node");
    printf("\n3. Delete node");
    printf("\n4. Stop code\n");
    scanf("%d", &ch);

    switch (ch) {
        case 1:
            if (list == NULL)
                printf("Circular linked list is empty\n");
            else
                display();
            break;
        case 2:
            printf("Enter position to insert node: ");
            scanf("%d", &pos);

            if (pos >= 1 && pos <= no + 1)
                insert(pos);
            else
                printf("Position is invalid\n");
            break;
        case 3:
            printf("Enter position to delete node: ");
            scanf("%d", &pos);

            if (pos >= 1 && pos <= no)
                delete(pos);
            else
                printf("Position is invalid\n");
            break;
        case 4:
            exit(0);
    }

} while (ch > 0 && ch < 5);

return 0; }
22
Q

Write a C program to sort given elements using insertion sort

A

include <stdio.h></stdio.h>

void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i]; // The element to be inserted
j = i - 1;

    // Move elements of arr[0..i-1], that are greater than key,
    // to one position ahead of their current position
    while (j >= 0 && arr[j] > key) {
        arr[j + 1] = arr[j];
        j = j - 1;
    }
    arr[j + 1] = key; // Insert the key in the correct position
} }

int main() {
int n, i;

printf("Enter the number of elements: ");
scanf("%d", &n);

int arr[n]; // Declare an array of size n

printf("Enter the elements:\n");
for (i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
}

insertionSort(arr, n); // Call the insertion sort function

printf("Sorted array:\n");
for (i = 0; i < n; i++) {
    printf("%d ", arr[i]);
}
printf("\n");

return 0; }
23
Q

Explain insertion sort

A

Function insertionSort: This function takes an array and its size as parameters. It sorts the array using the insertion sort algorithm:

It iterates through each element starting from the second element.
For each element, it finds the correct position in the sorted part of the array (to the left) and shifts larger elements to the right.
Finally, it inserts the element at its correct position.
Main Function:

It prompts the user to enter the number of elements and the elements themselves.
It calls the insertionSort function to sort the array.
It then prints the sorted array.

24
Q

Write a C program to search given element using recursive binary search algorithm.

A

include <stdio.h></stdio.h>

// Function to perform recursive binary search
int recursiveBinarySearch(int arr[], int left, int right, int target) {
if (right >= left) {
int mid = left + (right - left) / 2; // Calculate mid index

    // Check if the target is present at mid
    if (arr[mid] == target) {
        return mid; // Target found
    }

    // If the target is smaller than mid, search in the left subarray
    if (arr[mid] > target) {
        return recursiveBinarySearch(arr, left, mid - 1, target);
    }

    // If the target is larger than mid, search in the right subarray
    return recursiveBinarySearch(arr, mid + 1, right, target);
}

return -1; // Target not found }

int main() {
int n, i, target;

printf("Enter the number of elements: ");
scanf("%d", &n);

int arr[n]; // Declare an array of size n

printf("Enter the sorted elements:\n");
for (i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
}

printf("Enter the element to search for: ");
scanf("%d", &target);

// Call the recursive binary search function
int result = recursiveBinarySearch(arr, 0, n - 1, target);

if (result != -1) {
    printf("Element %d found at index %d.\n", target, result);
} else {
    printf("Element %d not found in the array.\n", target);
}

return 0; }
25
Q

Extra questions form now. Apart from practicals…

A