Data structre lab(mca)
Data structre lab(mca)
No. charge
10
11
12
13
14
1. Given (4,7,3,2,1,7,9,0) find the location of 7 using Linear and Binary
search and display its first occurrence.
Program Code
01 #include<stdio.h>
02 #include<stdlib.h>
03
04 int A[100], n, key; // Declare an array A with size 100 and variables n and key
05
06 // Function for linear search
07 int Isearch(int a[], int n, int key) {
08 int i = -1;
09 while (i < n) {
10 if (A[++i] == key)
11 return i;
12 }
13 return -1;
14 }
15
16 // Function for binary search
17 int binsearch(int a[], int n, int key) {
18 int first, last, mid, i;
19 first = 0;
20 last = n - 1;
21 while (first <= last) {
22 mid = (first + last) / 2;
23 if (key == A[mid])
24 return mid;
25 else if (key < A[mid])
26 last = mid - 1;
27 else
28 first = mid + 1;
29 }
30 return -1;
31 }
32
33 // Function to accept input
34 void acceptInput() {
35 int i;
36 printf("Enter Number of Elements:");
37 scanf("%d", &n);
38 for (i = 0; i < n; i++) { // Fix the loop condition and use i++ instead of i;
39 printf("Enter Element %d:", i + 1);
40 scanf("%d", &A[i]);
41 }
42 printf("Enter an Element to be Searched: ");
43 scanf("%d", &key);
44 }
45
2|Page
46 // Main function
47 void main() {
48 int ch, flag;
49 while (1) {
50 printf("\n Searching Techniques");
51 printf("\n********");
52 printf("\n 1. Linear Search ");
53 printf("\n 2. Binary Search ");
54 printf("\n 3. Exit");
55 printf("\n Enter your choice: ");
56 scanf("%d", &ch);
57
58 switch (ch) {
59 case 1:
60 acceptInput();
61 flag = Isearch(A, n, key); // Fix the assignment operator and the function call
62 if (flag == -1)
63 printf("\n Search is Unsuccessful.");
64 else
65 printf("\n An Element %d Found at Position: %d", key, flag + 1);
66 break;
67 case 2:
68 printf("\n Enter Elements in Ascending Order for Binary Search\n");
69 acceptInput();
70 flag = binsearch(A, n, key); // Fix the assignment operator and the function call
71 if (flag == -1)
72 printf("%d not found in array (%d,%d);", key, n, key);
73 else
74 printf("An Element %d Found at Position: %d", key, flag + 1);
75 break;
76 case 3:
77 exit(0);
78 }
79 }
80 }
3|Page
Explanation of Program Code
4|Page
Program Output
5|Page
2. Given {5,3,1,6,0,2,4} order the numbers in ascending order using
Quick Sort.
Program Code
01 #include <stdio.h>
02
03 // Function to swap two elements
04 void swap(int *a, int *b) {
05 int temp = *a;
06 *a = *b;
07 *b = temp;
08 }
09
10 // Partition function
11 int partition(int arr[], int low, int high) {
12 int pivot = arr[high]; // Choosing the last element as the pivot
13 int i = low - 1; // Index of the smaller element
14
15 for (int j = low; j < high; j++) {
16 if (arr[j] < pivot) { // If current element is smaller than pivot
17 i++;
18 swap(&arr[i], &arr[j]);
19 }
20 }
21 swap(&arr[i + 1], &arr[high]); // Place the pivot in its correct position
22 return i + 1;
23 }
24
25 // Quick Sort function
26 void quickSort(int arr[], int low, int high) {
27 if (low < high) {
28 int pi = partition(arr, low, high); // Partition index
29
30 // Recursively sort elements before and after partition
31 quickSort(arr, low, pi - 1);
32 quickSort(arr, pi + 1, high);
33 }
34 }
35
36 // Function to print the array
37 void printArray(int arr[], int size) {
38 for (int i = 0; i < size; i++) {
39 printf("%d ", arr[i]);
40 }
41 printf("\n");
42 }
43
44 // Main function
45 int main() {
46 int arr[] = {5, 3, 1, 6, 0, 2, 4};
6|Page
47 int n = sizeof(arr) / sizeof(arr[0]);
48
49 printf("Original array: ");
50 printArray(arr, n);
51
52 quickSort(arr, 0, n - 1);
53
54 printf("Sorted array: ");
55 printArray(arr, n);
56
57 return 0;
58 }
59
7|Page
Explanation of Program Code
8|Page
Program Output
9|Page
3. Perform the Merge sort on the input {75,8,1,16,48,3,7,0} and
display the output in descending order.
Program Code
01 #include <stdio.h>
02
03 // Merge function to combine two subarrays in descending order
04 void merge(int arr[], int left, int mid, int right) {
05 int n1 = mid - left + 1;
06 int n2 = right - mid;
07
08 // Create temporary arrays
09 int L[n1], R[n2];
10
11 // Copy data to temporary arrays L[] and R[]
12 for (int i = 0; i < n1; i++) {
13 L[i] = arr[left + i];
14 }
15 for (int j = 0; j < n2; j++) {
16 R[j] = arr[mid + 1 + j];
17 }
18
19 // Merge the temporary arrays back into arr[] in descending order
20 int i = 0, j = 0, k = left;
21 while (i < n1 && j < n2) {
22 if (L[i] >= R[j]) {
23 arr[k] = L[i];
24 i++;
25 } else {
26 arr[k] = R[j];
27 j++;
28 }
29 k++;
30 }
31
32 // Copy remaining elements of L[], if any
33 while (i < n1) {
34 arr[k] = L[i];
35 i++;
36 k++;
37 }
38
39 // Copy remaining elements of R[], if any
40 while (j < n2) {
41 arr[k] = R[j];
42 j++;
43 k++;
44 }
45 }
46
10 | P a g e
47 // Merge Sort function
48 void mergeSort(int arr[], int left, int right) {
49 if (left < right) {
50 int mid = left + (right - left) / 2;
51
52 // Sort first and second halves
53 mergeSort(arr, left, mid);
54 mergeSort(arr, mid + 1, right);
55
56 // Merge the sorted halves
57 merge(arr, left, mid, right);
58 }
59 }
60
61 // Function to print the array
62 void printArray(int arr[], int size) {
63 for (int i = 0; i < size; i++) {
64 printf("%d ", arr[i]);
65 }
66 printf("\n");
67 }
68
69 // Main function
70 int main() {
71 int arr[] = {75, 8, 1, 16, 48, 3, 7, 0};
72 int n = sizeof(arr) / sizeof(arr[0]);
73
74 printf("Original array: ");
75 printArray(arr, n);
76
77 mergeSort(arr, 0, n - 1);
78
79 printf("Sorted array in descending order: ");
80 printArray(arr, n);
81
82 return 0;
83 }
84
11 | P a g e
Explanation of Program Code
12 | P a g e
Program Output
13 | P a g e
4. Write a program to insert the elements {61,16,8,27} into singly
linked list and delete 8,61,27 from the list. Display your list after each
insertion and deletion.
Program Code
001 #include<stdio.h>
002 #include<stdlib.h>
003 #include<conio.h>
004 #include<ctype.h>
005
006 struct node {
007 int INFO;
008 struct node *LINK;
009 };
010
011 typedef struct node NODE;
012 NODE *start = NULL;
013
014 // Function to create a linked list
015 void create() {
016 char ch;
017 int i = 0;
018 NODE *CURRPTR, *NEWNODE;
019
020 // Allocate memory for the first node
021 CURRPTR = (NODE*)malloc(sizeof(NODE));
022 start = CURRPTR;
023
024 while (1) {
025 printf("\n Enter the node %d ", i + 1);
026 scanf("%d", &CURRPTR->INFO);
027
028 printf("\n Do you wish to add one more node (Y/N): ");
029 ch = getch();
030
031 if (toupper(ch) == 'Y') {
032 // Allocate memory for a new node
033 NEWNODE = (NODE*)malloc(sizeof(NODE));
034 CURRPTR->LINK = NEWNODE;
035 } else {
036 CURRPTR->LINK = NULL;
037 break;
038 }
039
040 CURRPTR = NEWNODE;
041 i++;
042 }
043 }
044
14 | P a g e
045 // Function to display the linked list
046 void display() {
047 NODE *CURRPTR = start;
048
049 if (start == NULL) {
050 printf("\n The Linked list is empty");
051 } else {
052 while (CURRPTR != NULL) {
053 printf("%d->", CURRPTR->INFO);
054 CURRPTR = CURRPTR->LINK;
055 }
056 printf("NULL");
057 }
058 }
059
060 // Function to calculate the length of the linked list
061 int length() {
062 int len = 0;
063 NODE *CURRPTR;
064
065 if (start == NULL) {
066 printf("The linked list is empty \n");
067 return len;
068 }
069
070 CURRPTR = start;
071 while (CURRPTR != NULL) {
072 len++;
073 CURRPTR = CURRPTR->LINK;
074 }
075 return len;
076 }
077
078 // Function to insert a node at the beginning
079 void insert_beg(int item) {
080 NODE *NEWNODE;
081 NEWNODE = (NODE*)malloc(sizeof(NODE));
082 NEWNODE->INFO = item;
083 NEWNODE->LINK = start;
084 start = NEWNODE;
085 }
086
087 // Function to insert a node at the end
088 void insert_end(int item) {
089 NODE *CURRPTR, *NEWNODE;
090
091 if (start == NULL) {
092 NEWNODE = (NODE*)malloc(sizeof(NODE));
093 NEWNODE->INFO = item;
094 NEWNODE->LINK = NULL;
095 start = NEWNODE;
15 | P a g e
096 } else {
097 CURRPTR = start;
098 while (CURRPTR->LINK != NULL) {
099 CURRPTR = CURRPTR->LINK;
100 }
101 NEWNODE = (NODE*)malloc(sizeof(NODE));
102 NEWNODE->INFO = item;
103 CURRPTR->LINK = NEWNODE;
104 NEWNODE->LINK = NULL;
105 }
106 }
107
108 // Function to insert a node at a specified position
109 void insert_pos(int item, int POS) {
110 int i;
111 NODE *CURRPTR = start, *NEWNODE;
112
113 if (POS == 1) {
114 insert_beg(item);
115 } else {
116 for (i = 0; i < POS - 2; i++) {
117 CURRPTR = CURRPTR->LINK;
118 }
119
120 NEWNODE = (NODE*)malloc(sizeof(NODE));
121 NEWNODE->INFO = item;
122 NEWNODE->LINK = CURRPTR->LINK;
123 CURRPTR->LINK = NEWNODE;
124 }
125 }
126
127 // Function to delete the first node
128 void delete_beg() {
129 NODE *CURRPTR;
130
131 if (start == NULL) {
132 printf("\n The linked list is empty \n");
133 return;
134 } else {
135 CURRPTR = start;
136 start = start->LINK;
137 free(CURRPTR);
138 }
139 }
140
141 // Function to delete the last node
142 void delete_end() {
143 NODE *CURRPTR, *PREVPTR;
144
145 if (start == NULL)
146 printf("\n The linked list is empty \n");
16 | P a g e
147 else if (start->LINK == NULL) {
148 start = NULL;
149 return;
150 } else {
151 CURRPTR = start;
152 PREVPTR = NULL;
153
154 while (CURRPTR->LINK != NULL) {
155 PREVPTR = CURRPTR;
156 CURRPTR = CURRPTR->LINK;
157 }
158
159 PREVPTR->LINK = NULL;
160 }
161 }
162
163 // Function to delete a node at a specified position
164 void delete_pos(int POS) {
165 int i;
166 NODE *CURRPTR, *PREVPTR;
167
168 if (POS == 1) {
169 delete_beg();
170 } else {
171 CURRPTR = start;
172 PREVPTR = NULL;
173
174 for (i = 1; i < POS; i++) {
175 PREVPTR = CURRPTR;
176 CURRPTR = CURRPTR->LINK;
177 }
178
179 PREVPTR->LINK = CURRPTR->LINK;
180 free(CURRPTR);
181 }
182 }
183
184 // Function to delete a node with a given item
185 void delete_item(int item) {
186 NODE *CURRPTR = start, *PREVPTR = NULL;
187
188 if (start == NULL) {
189 printf("\n The linked list is empty");
190 return;
191 } else if (start->INFO == item) {
192 start = start->LINK;
193 free(CURRPTR);
194 return;
195 }
196
197 while (CURRPTR != NULL && CURRPTR->INFO != item) {
17 | P a g e
198 PREVPTR = CURRPTR;
199 CURRPTR = CURRPTR->LINK;
200 }
201
202 if (CURRPTR == NULL) {
203 printf("\n The item is not found in the linked list \n");
204 } else {
205 PREVPTR->LINK = CURRPTR->LINK;
206 free(CURRPTR);
207 }
208 }
209
210 // Main function
211 void main() {
212 int ch, item, pos;
213
214 while (1) {
215 printf("\n 1. Create a Linked List ");
216 printf("\n 2. Display ");
217 printf("\n 3. Insert First Node ");
218 printf("\n 4. Insert at the End ");
219 printf("\n 5. Insert at the Specified Position ");
220 printf("\n 6. Delete First Node ");
221 printf("\n 7. Delete Last Node ");
222 printf("\n 8. Delete at the Specified Position ");
223 printf("\n 9. Delete a Node When Item is Given ");
224 printf("\n 10. Exit");
225 printf("\n Enter Your Choice: ");
226 scanf("%d", &ch);
227
228 switch (ch) {
229 case 1:
230 start = NULL;
231 create();
232 break;
233 case 2:
234 display();
235 break;
236 case 3:
237 printf("\n Enter the Item to Insert at the Beginning: ");
238 scanf("%d", &item);
239 printf("\n Linked List before Insertion is: \n");
240 display();
241 insert_beg(item);
242 printf("\n Linked List after Insertion is: \n");
243 display();
244 break;
245 case 4:
246 printf("\n Enter the Item to Insert at the End: ");
247 scanf("%d", &item);
248 printf("\n Linked List before Insertion is: \n");
18 | P a g e
249 display();
250 insert_end(item);
251 printf("\n Linked List after Insertion is: \n");
252 display();
253 break;
254 case 5:
255 printf("\n Enter an Item to Insert at a Certain Position: ");
256 scanf("%d", &item);
257 printf("\n Enter a Valid Position: ");
258 scanf("%d", &pos);
259
260 if ((pos == 0) || (pos > length() + 1)) {
261 printf("\n It is an Invalid Position \n");
262 break;
263 } else {
264 printf("\n Linked List before Insertion is: \n");
265 display();
266 insert_pos(item, pos);
267 printf("\n Linked List after Insertion is: \n");
268 display();
269 break;
270 }
271 case 6:
272 printf("\n Linked List before Deletion is: \n");
273 display();
274 delete_beg();
275 printf("\n Linked List after Deletion is: \n");
276 display();
277 break;
278 case 7:
279 printf("\n Linked List before Deletion is: \n");
280 display();
281 delete_end();
282 printf("\n Linked List after Deletion is: \n");
283 display();
284 break;
285 case 8:
286 printf("\n Enter a Valid Position to Delete: \n");
287 scanf("%d", &pos);
288
289 if ((pos == 0) || (pos > length())) {
290 printf("\n It is an Invalid position \n");
291 break;
292 } else {
293 printf("\n Linked List before Deletion is: \n");
294 display();
295 delete_pos(pos);
296 printf("\n Linked List after Deletion is: \n");
297 display();
298 break;
299 }
19 | P a g e
300 case 9:
301 printf("\n Linked List before Deletion is: \n");
302 display();
303 printf("\n Enter an Item to be Deleted: \n");
304 scanf("%d", &item);
305 delete_item(item);
306 printf("\n Linked list after Deletion is: \n");
307 display();
308 break;
309 case 10:
310 exit(0);
311 }
312 }
313 }
20 | P a g e
Explanation of Program Code
21 | P a g e
Program Output
22 | P a g e
5. Write a program to add 6x^{2}+10x^{2}+0x+5 and 4x^{2}+2x+1
using linked list.
Program Code
001 #include <stdio.h>
002 #include <stdlib.h>
003
004 // Structure to represent a term of a polynomial
005 struct Term {
006 int coefficient;
007 int exponent;
008 struct Term* next;
009 };
010
011 // Function to create a new term with given coefficient and exponent
012 struct Term* createTerm(int coefficient, int exponent) {
013 struct Term* newTerm = (struct Term*)malloc(sizeof(struct Term));
014 newTerm->coefficient = coefficient;
015 newTerm->exponent = exponent;
016 newTerm->next = NULL;
017 return newTerm;
018 }
019
020 // Function to add a term to the polynomial
021 void addTerm(struct Term** poly, int coefficient, int exponent) {
022 struct Term* newTerm = createTerm(coefficient, exponent);
023 if (*poly == NULL) {
024 *poly = newTerm;
025 } else {
026 struct Term* current = *poly;
027 while (current->next != NULL) {
028 current = current->next;
029 }
030 current->next = newTerm;
031 }
032 }
033
034 // Function to display the polynomial
035 void displayPolynomial(struct Term* poly) {
036 struct Term* current = poly;
037 while (current != NULL) {
038 printf("%dx^%d ", current->coefficient, current->exponent);
039 if (current->next != NULL) {
040 printf("+ ");
041 }
042 current = current->next;
043 }
044 printf("\n");
045 }
046
23 | P a g e
047 // Function to add two polynomials
048 struct Term* addPolynomials(struct Term* poly1, struct Term* poly2) {
049 struct Term* result = NULL;
050
051 while (poly1 != NULL && poly2 != NULL) {
052 if (poly1->exponent > poly2->exponent) {
053 addTerm(&result, poly1->coefficient, poly1->exponent);
054 poly1 = poly1->next;
055 } else if (poly1->exponent < poly2->exponent) {
056 addTerm(&result, poly2->coefficient, poly2->exponent);
057 poly2 = poly2->next;
058 } else {
059 int sum = poly1->coefficient + poly2->coefficient;
060 if (sum != 0) {
061 addTerm(&result, sum, poly1->exponent);
062 }
063 poly1 = poly1->next;
064 poly2 = poly2->next;
065 }
066 }
067
068 // Add remaining terms from poly1, if any
069 while (poly1 != NULL) {
070 addTerm(&result, poly1->coefficient, poly1->exponent);
071 poly1 = poly1->next;
072 }
073
074 // Add remaining terms from poly2, if any
075 while (poly2 != NULL) {
076 addTerm(&result, poly2->coefficient, poly2->exponent);
077 poly2 = poly2->next;
078 }
079
080 return result;
081 }
082
083 int main() {
084 // Create polynomial 1: 16x^1 + 10x^2 + 0x + 5
085 struct Term* poly1 = NULL;
086 addTerm(&poly1, 16, 1);
087 addTerm(&poly1, 10, 2);
088 addTerm(&poly1, 0, 0);
089 addTerm(&poly1, 5, 0);
090
091 // Create polynomial 2: 4x^2 + 2x + 1
092 struct Term* poly2 = NULL;
093 addTerm(&poly2, 4, 2);
094 addTerm(&poly2, 2, 1);
095 addTerm(&poly2, 1, 0);
096
097 printf("Polynomial 1: ");
24 | P a g e
098 displayPolynomial(poly1);
099 printf("Polynomial 2: ");
100 displayPolynomial(poly2);
101
102 struct Term* sum = addPolynomials(poly1, poly2);
103 printf("Resultant Polynomial: ");
104 displayPolynomial(sum);
105
106 return 0;
107 }
25 | P a g e
Explanation of Program Code
26 | P a g e
Program Output
27 | P a g e
6. Write a program to push 5,9,34,17,32 into stack and pop 3 times
from the stack, also display the popped numbers.
Program Code
01 #include <stdio.h>
02 #include <stdlib.h>
03
04 #define MAX_SIZE 5
05
06 struct Stack {
07 int top;
08 int items[MAX_SIZE];
09 };
10
11 // Initialize the stack
12 void initializeStack(struct Stack *s) {
13 s->top = -1;
14 }
15
16 // Check if the stack is full
17 int isFull(struct Stack *s) {
18 return s->top == MAX_SIZE - 1;
19 }
20
21 // Check if the stack is empty
22 int isEmpty(struct Stack *s) {
23 return s->top == -1;
24 }
25
26 // Push element onto the stack
27 void push(struct Stack *s, int value) {
28 if (isFull(s)) {
29 printf("Stack is full. Cannot push.\n");
30 return;
31 }
32 s->items[++s->top] = value;
33 printf("Pushed %d into the stack.\n", value);
34 }
35
36 // Pop element from the stack
37 int pop(struct Stack *s) {
38 if (isEmpty(s)) {
39 printf("Stack is empty. Cannot pop.\n");
40 return -1; // Error condition or sentinel value
41 }
42 int popped = s->items[s->top--];
43 return popped;
28 | P a g e
44 }
45
46 int main() {
47 struct Stack stack;
48 initializeStack(&stack);
49
50 // Push elements into the stack
51 push(&stack, 5);
52 push(&stack, 9);
53 push(&stack, 34);
54 push(&stack, 17);
55 push(&stack, 32);
56
57 // Pop elements from the stack three times and display them
58 printf("\nPopped numbers:\n");
59 for (int i = 0; i < 3; ++i) {
60 int popped = pop(&stack);
61 if (popped != -1) {
62 printf("%d\n", popped);
63 }
64 }
65
66 return 0;
67 }
29 | P a g e
Explanation of Program Code
30 | P a g e
Program Output
31 | P a g e
7. Write a recursive program to find GCD of 4,6,8.
Program Code
01 #include<stdio.h>
02 #include<conio.h>
03
04 // Function to find the Greatest Common Divisor (GCD) of two numbers
05 int gcd(int a, int b) {
06 if (b > a)
07 return gcd(b, a); // Swap a and b if b is greater
08 else if (b == 0)
09 return a; // GCD is a when b is 0
10 else
11 return gcd(b, a % b); // Recursive call with remainder
12 }
13
14 // Main function
15 void main() {
16 int a, b, c, res;
17 printf("Enter three numbers: \n");
18 scanf("%d %d %d", &a, &b, &c); // Correct the format specifier and fix the input string
19
20 res = gcd(a, gcd(b, c)); // Calculate GCD of a, b, and c
21
22 printf("\n GCD of %d, %d, and %d is %d \n", a, b, c, res); // Fix the format specifier
23 getch(); // Wait for a key press (conio.h)
24 }
32 | P a g e
Explanation of Program Code
33 | P a g e
Program Output
34 | P a g e
8. Write a program to inert the elements (5,7,0,6,3,9) into circular
queue and delete 6,9 & 5 from it (using linked list implementation).
Program Code:
01 #include <stdio.h>
02 #include <stdlib.h>
03
04 #define MAX_SIZE 6 // Define the maximum size of the circular queue
05
06 // Structure representing the circular queue
07 struct Queue {
08 int front, rear; // Front and rear indices
09 int items[MAX_SIZE]; // Array to store queue elements
10 };
11
12 // Function to initialize the queue
13 void initializeQueue(struct Queue *q) {
14 q->front = q->rear = -1; // Initialize front and rear indices to -1
15 }
16
17 // Function to check if the queue is full
18 int isFull(struct Queue *q) {
19 return ((q->rear + 1) % MAX_SIZE == q->front); // Circular check for full condition
20 }
21
22 // Function to check if the queue is empty
23 int isEmpty(struct Queue *q) {
24 return (q->front == -1); // If front is -1, the queue is empty
25 }
26
27 // Function to insert an element into the queue
28 void enqueue(struct Queue *q, int value) {
29 if (isFull(q)) {
30 printf("Queue is full. Cannot enqueue.\n");
31 return;
32 }
33
34 if (isEmpty(q)) {
35 q->front = q->rear = 0; // Set front and rear to 0 for the first element
36 } else {
37 q->rear = (q->rear + 1) % MAX_SIZE; // Move rear circularly
38 }
39
40 q->items[q->rear] = value; // Insert the value at the rear
41 printf("Inserted %d into the queue.\n", value);
42 }
43
44 // Function to delete an element from the queue
45 void dequeue(struct Queue *q, int value) {
46 if (isEmpty(q)) {
35 | P a g e
47 printf("Queue is empty. Cannot dequeue.\n");
48 return;
49 }
50
51 printf("Deleted %d from the queue.\n", q->items[q->front]);
52
53 if (q->front == q->rear) {
54 q->front = q->rear = -1; // Reset front and rear for the last element
55 } else {
56 q->front = (q->front + 1) % MAX_SIZE; // Move front circularly
57 }
58 }
59
60 // Main function
61 int main() {
62 struct Queue queue;
63 initializeQueue(&queue); // Initialize the circular queue
64
65 // Insert elements into the circular queue
66 enqueue(&queue, 5);
67 enqueue(&queue, 7);
68 enqueue(&queue, 0);
69 enqueue(&queue, 6);
70 enqueue(&queue, 3);
71 enqueue(&queue, 9);
72
73 // Delete an element (e.g., 6) from the queue
74 dequeue(&queue, 6);
75
76 return 0;
77 }
36 | P a g e
Explanation of Program Code
37 | P a g e
Program Output
38 | P a g e
9. Given S1={"Flowers"} S2={"are beautiful"} 1). Find the length of S1
2). Concatenate S1 and S2 3). Extract the substring "low" from S1 4).
Find "are" in S2 and replace it with "is"
Program Code
01 #include <stdio.h>
02 #include <string.h>
03
04 int main() {
05 // Task 1: Find the length of SI
06 const char* S1 = "Flowers";
07 const char* S2 = "are beautiful";
08 int length_S1 = strlen(S1);
09 printf("Length of S1: %d\n", length_S1);
10
11 // Task 2: Concatenate S1 and S2
12 char concatenated[100];
13 strcpy(concatenated, S1);
14 strcat(concatenated, S2);
15 printf("Concatenated string: %s\n", concatenated);
16
17 // Task 3: Extract substring "low" from S1
18 const char* substring = strstr(S1, "low");
19 if (substring != NULL) {
20 char extracted[10];
21 strncpy(extracted, substring, 3); // Extract "low"
22 extracted[3] = '\0';
23 printf("Extracted substring from S1: %s\n", extracted);
24 } else {
25 printf("Substring 'low' not found in S1.\n");
26 }
27
28 // Task 4: Find "are" in S2 and replace it with "_"
29 const char* search = "are";
30 const char* replace = "_";
31 char* found = strstr(S2, search);
32 if (found != NULL) {
33 char result[100];
34 strncpy(result, S2, found - S2); // Copy before "are"
35 result[found - S2] = '\0';
36 strcat(result, replace); // Add replacement
37 strcat(result, found + strlen(search)); // Copy after "are"
38 printf("Updated S2 after replacement: %s\n", result);
39 } else {
40 printf("Substring 'are' not found in S2.\n");
41 }
42
43 return 0;
44 }
39 | P a g e
Explanation of Program Code
40 | P a g e
Program Output
41 | P a g e
10. Write a program to convert an infix expression y/(5^2*z)+2 to its
postfix expression
Program Code
001 #include <stdio.h>
002 #include <stdlib.h>
003 #include <string.h>
004 #include <ctype.h>
005
006 #define MAX_SIZE 100
007
008 // Structure for stack
009 struct Stack {
010 int top;
011 unsigned capacity;
012 char* array;
013 };
014
015 // Create a stack of given capacity
016 struct Stack* createStack(unsigned capacity) {
017 struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
018 stack->capacity = capacity;
019 stack->top = -1;
020 stack->array = (char*)malloc(stack->capacity * sizeof(char));
021 return stack;
022 }
023
024 // Check if the stack is full
025 int isFull(struct Stack* stack) {
026 return stack->top == stack->capacity - 1;
027 }
028
029 // Check if the stack is empty
030 int isEmpty(struct Stack* stack) {
031 return stack->top == -1;
032 }
033
034 // Push element onto the stack
035 void push(struct Stack* stack, char item) {
036 if (isFull(stack)) return;
037 stack->array[++stack->top] = item;
038 }
039
040 // Pop element from the stack
041 char pop(struct Stack* stack) {
042 if (isEmpty(stack)) return '\0';
043 return stack->array[stack->top--];
044 }
045
046 // Get the precedence of operators
42 | P a g e
047 int precedence(char ch) {
048 switch(ch) {
049 case '+':
050 case '-':
051 return 1;
052 case '*':
053 case '/':
054 return 2;
055 case '^':
056 return 3;
057 }
058 return -1;
059 }
060
061 // Convert infix expression to postfix expression
062 void infixToPostfix(char* infix) {
063 struct Stack* stack = createStack(strlen(infix));
064 int i, k;
065 for (i = 0, k = -1; infix[i]; ++i) {
066 if (isalnum(infix[i])) {
067 printf("%c", infix[i]);
068 } else if (infix[i] == '(') {
069 push(stack, infix[i]);
070 } else if (infix[i] == ')') {
071 while (!isEmpty(stack) && stack->array[stack->top] != '(') {
072 printf("%c", pop(stack));
073 }
074 if (!isEmpty(stack) && stack->array[stack->top] != '(') {
075 return;
076 } else {
077 pop(stack);
078 }
079 } else {
080 while (!isEmpty(stack) && precedence(infix[i]) <= precedence(stack->array[stack-
>top])) {
081 printf("%c", pop(stack));
082 }
083 push(stack, infix[i]);
084 }
085 }
086
087 // Pop remaining operators from the stack
088 while (!isEmpty(stack)) {
089 printf("%c", pop(stack));
090 }
091 }
092
093 int main() {
094 char infix[MAX_SIZE] = "x * y /(5^3 * z)+2";
095 printf("Infix expression: %s\n", infix);
096 printf("Postfix expression: ");
43 | P a g e
097 infixToPostfix(infix);
098 printf("\n");
099 return 0;
100 }
44 | P a g e
Explanation of Program Code
45 | P a g e
Program Output
46 | P a g e
11. Write a program to evaluate a postfix expression 5 3+8 2-*.
Program Code
01 #include <stdio.h>
02 #include <stdlib.h>
03 #include <string.h>
04 #include <ctype.h>
05
06 #define MAX_SIZE 100
07
08 // Structure for stack
09 struct Stack {
10 int top;
11 unsigned capacity;
12 int* array;
13 };
14
15 // Create a stack of given capacity
16 struct Stack* createStack(unsigned capacity) {
17 struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
18 stack->capacity = capacity;
19 stack->top = -1;
20 stack->array = (int*)malloc(stack->capacity * sizeof(int));
21 return stack;
22 }
23
24 // Check if the stack is full
25 int isFull(struct Stack* stack) {
26 return stack->top == stack->capacity - 1;
27 }
28
29 // Check if the stack is empty
30 int isEmpty(struct Stack* stack) {
31 return stack->top == -1;
32 }
33
34 // Push element onto the stack
35 void push(struct Stack* stack, int item) {
36 if (isFull(stack))
37 return; // Ignore if the stack is full
38 stack->array[++stack->top] = item;
39 }
40
41 // Pop element from the stack
42 int pop(struct Stack* stack) {
43 if (isEmpty(stack))
44 return -1; // Error condition or sentinel value
45 return stack->array[stack->top--];
47 | P a g e
46 }
47
48 // Perform arithmetic operations
49 int performOperation(char operator, int operand1, int operand2) {
50 switch (operator) {
51 case '+':
52 return operand1 + operand2;
53 case '-':
54 return operand1 - operand2;
55 case '*':
56 return operand1 * operand2;
57 case '/':
58 return operand1 / operand2;
59 }
60 return 0; // Default, in case of an invalid operator
61 }
62
63 // Evaluate postfix expression
64 int evaluatePostfix(char* postfix) {
65 struct Stack* stack = createStack(strlen(postfix));
66 int i;
67 for (i = 0; postfix[i]; ++i) {
68 if (isdigit(postfix[i])) {
69 push(stack, postfix[i] - '0');
70 } else {
71 int operand2 = pop(stack);
72 int operand1 = pop(stack);
73 int result = performOperation(postfix[i], operand1, operand2);
74 push(stack, result);
75 }
76 }
77 return pop(stack);
78 }
79
80 int main() {
81 char postfix[MAX_SIZE] = "53+82-*";
82 printf("Postfix expression: %s\n", postfix);
83 int result = evaluatePostfix(postfix);
84 printf("Result of evaluation: %d\n", result);
85 return 0;
86 }
48 | P a g e
Explanation of Program Code
49 | P a g e
Program Output
50 | P a g e
12. Write a program to create a binary tree with the elements
{18,15,40,50,30,17,41} after creation insert 45 and 19 into tree and
delete 15,17 and 41 from tree. Display the tree on each insertion and
deletion operation
Program Code
001 #include <stdlib.h>
002 #include <stdio.h>
003
004 struct Node {
005 int data;
006 struct Node* left;
007 struct Node* right;
008 };
009
010 // Create a new node
011 struct Node* createNode(int data) {
012 struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
013 newNode->data = data;
014 newNode->left = NULL;
015 newNode->right = NULL;
016 return newNode;
017 }
018
019 // Insert a node into the binary tree
020 struct Node* insertNode(struct Node* root, int data) {
021 if (root == NULL) {
022 return createNode(data);
023 }
024 if (data < root->data) {
025 root->left = insertNode(root->left, data);
026 } else if (data > root->data) {
027 root->right = insertNode(root->right, data);
028 }
029 return root;
030 }
031 // Find the minimum value node in a subtree
032 struct Node* findMinNode(struct Node* node) {
033 struct Node* current = node;
034 while (current && current->left != NULL) {
035 current = current->left;
036 }
037 return current;
038 }
039 // Delete a node from the binary tree
040 struct Node* deleteNode(struct Node* root, int data) {
51 | P a g e
041 if (root == NULL) {
042 return root;
043 }
044 if (data < root->data) {
045 root->left = deleteNode(root->left, data);
046 } else if (data > root->data) {
047 root->right = deleteNode(root->right, data);
048 } else {
049 // Node to be deleted found
050 // Node with only one child or no child
051 if (root->left == NULL) {
052 struct Node* temp = root->right;
053 free(root);
054 return temp;
055 } else if (root->right == NULL) {
056 struct Node* temp = root->left;
057 free(root);
058 return temp;
059 }
060 // Node with two children: Get the inorder successor (smallest in the right subtree)
061 struct Node* temp = findMinNode(root->right);
062
063 // Copy the inorder successor's data to this node
064 root->data = temp->data;
065
066 // Delete the inorder successor
067 root->right = deleteNode(root->right, temp->data);
068 }
069 return root;
070 }
071
072 // Inorder traversal to display the tree
073 void inorderTraversal(struct Node* root) {
074 if (root != NULL) {
075 inorderTraversal(root->left);
076 printf("%d ", root->data);
077 inorderTraversal(root->right);
078 }
079 }
080 int main() {
081 struct Node* root = NULL;
082 // Inserting elements into the binary tree
083 root = insertNode(root, 18);
084 root = insertNode(root, 15);
085 root = insertNode(root, 40);
086 root = insertNode(root, 50);
087 root = insertNode(root, 10);
088 root = insertNode(root, 17);
089 root = insertNode(root, 41);
090 // Displaying the tree before insertion and deletion operations
091 printf("Tree before insertion and deletion: ");
52 | P a g e
092 inorderTraversal(root);
093 printf("\n");
094 // Inserting 45 and 19 into the tree
095 root = insertNode(root, 45);
096 root = insertNode(root, 19);
097 // Displaying the tree after insertions
098 printf("Tree after insertion: ");
099 inorderTraversal(root);
100 printf("\n");
101 // Deleting 15, 17, and 41 from the tree
102 root = deleteNode(root, 15);
103 root = deleteNode(root, 17);
104 root = deleteNode(root, 41);
105 // Displaying the tree after deletions
106 printf("Tree after deletions: ");
107 inorderTraversal(root);
108 printf("\n");
109 return 0;
110 }
53 | P a g e
Explanation of Program Code
54 | P a g e
Program Output
55 | P a g e
13. Write a program to create binary search tree with the elements
{2,5,1,3,9,0,6} and perform inorder, preorder and post order
traversal.
Program Code
01 #include <stdio.h>
02 #include <stdlib.h>
03
04 // Node structure for a binary tree
05 struct Node {
06 int data;
07 struct Node* left;
08 struct Node* right;
09 };
10
11 // Function to create a new node
12 struct Node* createNode(int data) {
13 struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
14 newNode->data = data;
15 newNode->left = NULL;
16 newNode->right = NULL;
17 return newNode;
18 }
19
20 // Function to insert a node into the binary search tree
21 struct Node* insertNode(struct Node* root, int data) {
22 if (root == NULL) {
23 return createNode(data);
24 }
25 if (data < root->data) {
26 root->left = insertNode(root->left, data);
27 } else if (data > root->data) {
28 root->right = insertNode(root->right, data);
29 }
30 return root;
31 }
32
33 // Inorder traversal
34 void inorderTraversal(struct Node* root) {
35 if (root != NULL) {
36 inorderTraversal(root->left);
37 printf("%d ", root->data);
38 inorderTraversal(root->right);
39 }
40 }
41
42 // Preorder traversal
56 | P a g e
43 void preorderTraversal(struct Node* root) {
44 if (root != NULL) {
45 printf("%d ", root->data);
46 preorderTraversal(root->left);
47 preorderTraversal(root->right);
48 }
49 }
50
51 // Postorder traversal
52 void postorderTraversal(struct Node* root) {
53 if (root != NULL) {
54 postorderTraversal(root->left);
55 postorderTraversal(root->right);
56 printf("%d ", root->data);
57 }
58 }
59
60 int main() {
61 struct Node* root = NULL;
62
63 // Inserting elements into the binary search tree
64 root = insertNode(root, 2);
65 root = insertNode(root, 5);
66 root = insertNode(root, 1);
67 root = insertNode(root, 1);
68 root = insertNode(root, 9);
69 root = insertNode(root, 0);
70 root = insertNode(root, 61);
71
72 // Displaying the tree traversals
73 printf("Inorder traversal: ");
74 inorderTraversal(root);
75 printf("\n");
76
77 printf("Preorder traversal: ");
78 preorderTraversal(root);
79 printf("\n");
80
81 printf("Postorder traversal: ");
82 postorderTraversal(root);
83 printf("\n");
84
85 return 0;
86 }
57 | P a g e
Explanation of Program Code
58 | P a g e
Program Output
59 | P a g e
14. Write a program to Sort the following elements using heap sort
{9,16,32,8,4,1,5,8,0}
Program Code
01 #include <stdio.h>
02
03 // Function to perform heapify operation
04 void heapify(int arr[], int n, int i) {
05 int largest = i; // Initialize largest as root
06 int left = 2 * i + 1; // Left child
07 int right = 2 * i + 2; // Right child
08
09 // If left child is larger than root
10 if (left < n && arr[left] > arr[largest]) {
11 largest = left;
12 }
13
14 // If right child is larger than largest so far
15 if (right < n && arr[right] > arr[largest]) {
16 largest = right;
17 }
18
19 // If largest is not root
20 if (largest != i) {
21 int temp = arr[i];
22 arr[i] = arr[largest];
23 arr[largest] = temp;
24
25 // Recursively heapify the affected sub-tree
26 heapify(arr, n, largest);
27 }
28 }
29
30 // Function to perform heap sort
31 void heapSort(int arr[], int n) {
32 // Build heap (rearrange array)
33 for (int i = n / 2 - 1; i >= 0; i--) {
34 heapify(arr, n, i);
35 }
36
37 // Extract elements from heap one by one
38 for (int i = n - 1; i >= 0; i--) {
39 // Move current root to end
40 int temp = arr[0];
41 arr[0] = arr[i];
42 arr[i] = temp;
43
60 | P a g e
44 // Call max heapify on the reduced heap
45 heapify(arr, i, 0);
46 }
47 }
48
49 // Function to print an array
50 void printArray(int arr[], int n) {
51 for (int i = 0; i < n; i++) {
52 printf("%d ", arr[i]);
53 }
54 printf("\n");
55 }
56
57 int main() {
58 int arr[] = {916, 12, 8, 4, 1, 5, 80};
59 int n = sizeof(arr) / sizeof(arr[0]);
60
61 printf("Original array: ");
62 printArray(arr, n);
63
64 heapSort(arr, n);
65
66 printf("Sorted array using Heap Sort: ");
67 printArray(arr, n);
68
69 return 0;
70 }
61 | P a g e
Explanation of Program Code
62 | P a g e
Program Output
63 | P a g e
64 | P a g e
65 | P a g e