DSpractical 3to9
DSpractical 3to9
SET A
Q1)Write a C program to accept and sort n elements in ascending order by using merge sort.
ANS:-
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
i = 0;
j = 0;
k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
2) Write a C program to accept and sort n elements in ascending order by using quick sort.
ANS:- #include <stdio.h>
#include <stdlib.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;}
int partition(int arr[], int low, int high) { int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
} } swap(&arr[i + 1], &arr[high]);
return i + 1;}
void quickSort(int arr[], int low, int high) {
if (low < high) { int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);} }
int main() { int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]); }
quickSort(arr, 0, n - 1);
printf("Sorted array in ascending order:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
SET B
1) Write a C program to create a string array with months (accept atleast 6 month) and sort
them using Quick sort.
ANS:-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char** a, char** b) {
char* temp = *a;
*a = *b;
*b = temp;
}
int partition(char* arr[], int low, int high) {
char* pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (strcmp(arr[j], pivot) < 0) {
i++;
swap(&arr[i], &arr[j]);
}}
swap(&arr[i + 1], &arr[high]);
return i + 1;
}
void quickSort(char* arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}}
int main() {
int n;
printf("Enter the number of months (at least 6): ");
scanf("%d", &n);
if (n < 6) {
printf("Please enter at least 6 months.\n");
return 1;}
char* months[n];
printf("Enter the months:\n");
for (int i = 0; i < n; i++) {
months[i] = (char*)malloc(20 * sizeof(char));
scanf("%s", months[i]);
}
quickSort(months, 0, n - 1);
printf("Sorted months:\n");
for (int i = 0; i < n; i++) {
printf("%s\n", months[i]); }
for (int i = 0; i < n; i++) {
free(months[i]); }
return 0;
}
Q2)Write a C program to create a string array with atlaest 5 elements which contains word
ending with ‘at’ and ‘an’ sound and sort them using Merge sort.
ANS:-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void merge(char* arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
char* L[n1];
char* R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
i = 0;
j = 0;
k = left;
while (i < n1 && j < n2) {
if (strcmp(L[i], R[j]) <= 0) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(char* arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
return 0;
}
SET C1) Write a C program to read the data from the file “person.txt” which contains personno,
name and personage and sort the data on age in ascending order using merge Sort.
ANS:- file "person.txt" (assuming it's in a specific format), containing person numbers, names, and
ages, and then sorts the data based on age
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Person {
int personNo;
char name[50];
int age;};
void merge(struct Person arr[], int left, int mid, int right) {
int i, j, k;
SET C1) Write a C program to read the data from the file “person.txt” which contains personno,
name and personage and sort the data on age in ascending order using merge Sort.
ANS:- file "person.txt" (assuming it's in a specific format), containing person numbers, names, and
ages, and then sorts the data based on age
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Person {
int personNo;
char name[50];
int age;};
void merge(struct Person arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
struct Person L[n1];
struct Person R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
i = 0,j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i].age <= R[j].age) {
arr[k] = L[i];
i++; } else { arr[k] = R[j];
j++;}
k++;}
while (i < n1) {
arr[k] = L[i];
i++;
k++; }
while (j < n2) {
arr[k] = R[j];
j++;
k++;}}
void mergeSort(struct Person arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right); }}
int main() { int n;
FILE* file = fopen("person.txt", "r");
if (file == NULL) { printf("Error opening the file.\n");
return 1;}
fscanf(file, "%d", &n);
struct Person people[n];
for (int i = 0; i < n; i++) {
fscanf(file, "%d %s %d", &people[i].personNo, people[i].name, &people[i].age);}
fclose(file);
mergeSort(people, 0, n - 1);
printf("Sorted data based on age in ascending order:\n");
for (int i = 0; i < n; i++) {
printf("Person No: %d, Name: %s, Age: %d\n", people[i].personNo, people[i].name,
people[i].age);}
return 0;}
---------------------------------------------------------------------------------------------------------------------
ASSIGNMENT - 4
SET A
1) Write a C program to accept n elements from user store it in an array. Accept a value from
the user and use linear/Sequential search method to check whether the value is present in
array or not. Display proper message.
ANS:-
#include <stdio.h>
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int searchValue;
printf("Enter the value to search for: ");
scanf("%d", &searchValue);
int found = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == searchValue) {
found = 1;
break; // Value found, no need to continue searching}
}
if (found) {
printf("Value %d is present in the array.\n", searchValue);
} else {
printf("Value %d is not present in the array.\n", searchValue);
}
return 0;
}
2) Write a C program to accept n elements from user store it in an array. Accept a value from
the user and use binary search method to check whether the value is present in array or not.
Display proper message. (Students should accept sorted array and use Recursive function).
ANS:-
#include <stdio.h>
int binarySearch(int arr[], int left, int right, int target) {
if (right >= left) {
int mid = left + (right - left) / 2;
if (arr[mid] == target)
return 1;
if (arr[mid] > target)
return binarySearch(arr, left, mid - 1, target);
return binarySearch(arr, mid + 1, right, target);
}
return 0;
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements in sorted order:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int searchValue;
printf("Enter the value to search for: ");
scanf("%d", &searchValue);
// Perform binary search
int found = binarySearch(arr, 0, n - 1, searchValue);
if (found) {
printf("Value %d is present in the array.\n", searchValue);
} else {
printf("Value %d is not present in the array.\n", searchValue);
}
return 0;
}
SET B:
1) Write a ‘C’ program to accept the names of cities and store them in array. Accept the city
name from user and use linear search algorithm to check whether the city is present in array
or not.
#include <stdio.h>
#include <string.h>
#define MAX_CITIES 100
#define MAX_CITY_NAME 50
int main() {
char cities[MAX_CITIES][MAX_CITY_NAME];
int n;
printf("Enter the number of cities: ");
scanf("%d", &n);
while (getchar() != '\n');
printf("Enter %d city names:\n", n);
for (int i = 0; i < n; i++) {
fgets(cities[i], MAX_CITY_NAME, stdin);
cities[i][strcspn(cities[i], "\n")] = '\0'; // Remove the newline character
}
char searchCity[MAX_CITY_NAME];
printf("Enter the city name to search for: ");
fgets(searchCity, MAX_CITY_NAME, stdin);
searchCity[strcspn(searchCity, "\n")] = '\0';
int found = 0; // Flag to indicate whether the city is found
for (int i = 0; i < n; i++) {
if (strcmp(cities[i], searchCity) == 0) {
found = 1;
break;}
}
if (found) {
printf("City %s is present in the array.\n", searchCity);
} else {
printf("City %s is not present in the array.\n", searchCity);
}
return 0;
}
2) Write a C program to accept n elements from user store it in an array. Accept a value from
the user and use recursive binary search method to check whether the value is present in
array or not. Display proper message. (use any sorting method to sort the array)
ANS:-#include <stdio.h>
// Recursive binary search function
int recursiveBinarySearch(int arr[], int left, int right, int target) {
if (right >= left) {
int mid = left + (right - left) / 2;
if (arr[mid] == target)
return 1;
if (arr[mid] > target)
return recursiveBinarySearch(arr, left, mid - 1, target);
return recursiveBinarySearch(arr, mid + 1, right, target); }
return 0;
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;}
}
}
int searchValue;
printf("Enter the value to search for: ");
scanf("%d", &searchValue);
int found = recursiveBinarySearch(arr, 0, n - 1, searchValue);
if (found) {
printf("Value %d is present in the array.\n", searchValue);
} else {
printf("Value %d is not present in the array.\n", searchValue);
}
return 0;
}
SET C
1) Write a C program to read the data from file 'student.txt' containing names of 10 students
and their roll no. Accept a name of the student from user and use Binary search algorithm
to check whether the name is present in the file and output the roll no, otherwise output
“Student name not in the list”.
ANS:-#include <stdio.h>
#include <string.h>
#define MAX_STUDENT_NAME 50
#define MAX_ROLL_NUMBER 10
#define MAX_STUDENTS 10
int binarySearch(char names[][MAX_STUDENT_NAME], char searchName[], int rollNumbers[],
int left, int right) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (strcmp(names[mid], searchName) == 0)
return rollNumbers[mid];
if (strcmp(names[mid], searchName) < 0)
left = mid + 1;
else
right = mid - 1;
}
return -1; // Not found
}
int main() {
char studentNames[MAX_STUDENTS][MAX_STUDENT_NAME];
int rollNumbers[MAX_STUDENTS];
int n = 0; // Number of students in the file
FILE *file = fopen("student.txt", "r");
if (file == NULL) {
printf("Failed to open the file.\n");
return 1; // Return with error code
}
hile (fscanf(file, "%s %d", studentNames[n], &rollNumbers[n]) != EOF) {
n++;
}
fclose(file);
char searchName[MAX_STUDENT_NAME];
printf("Enter the student name to search for: ");
scanf("%s", searchName);
int foundRollNumber = binarySearch(studentNames, searchName, rollNumbers, 0, n - 1);
if (foundRollNumber != -1) {
printf("Roll number for student %s is %d.\n", searchName, foundRollNumber);
} else {
printf("Student name %s not in the list.\n", searchName);
}
return 0;
}
ASSIGNMENT 5
SET A:
1) Write a C program to implement a singly linked list with Create and Display operation.
ANS:-
#include <stdio.h>
#include <stdlib.h>
// Define the structure for a singly linked list node
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to insert a node at the end of the linked list
void insertEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
// Function to display the linked list
void display(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL; // Initialize an empty linked list
2) Write a C program to implement a Circular Singly linked list with Create and Display
operation.
ANS:-#include <stdio.h>
#include <stdlib.h>
// Define the structure for a circular singly linked list node
struct Node {
int data;
struct Node* next;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insertEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
newNode->next = *head;
return;
}
struct Node* current = *head;
while (current->next != *head) {
current = current->next;
}
current->next = newNode;
newNode->next = *head;
}
// Function to display the circular linked list
void display(struct Node* head) {
if (head == NULL) {
printf("Circular Linked List is empty.\n");
return;
}
struct Node* current = head;
do {
printf("%d -> ", current->data);
current = current->next;
} while (current != head);
printf("HEAD (Back to start)\n");
}
int main() {
struct Node* head = NULL; // Initialize an empty circular linked list
insertEnd(&head, 10);
insertEnd(&head, 20);
insertEnd(&head, 30);
insertEnd(&head, 40);
insertEnd(&head, 50);
printf("Circular Linked List: ");
display(head);
return 0;
}
SET B:
1 Write a Menu driven program in C to implement the following functions:
i) To search the number in the list. If the number is present display the Position of
node .If number not present print the message “Number not Found”
ii) To swap mth and nth element of linked list.
iii) To delete node from specific position of linked list.
ANS:-#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next; };
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed!\n");
exit(1);}
newNode->data = data;
newNode->next = NULL;
return newNode;}
void insertEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return; }
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;}
current->next = newNode;
}
void display(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next; }
printf("NULL\n");}
void searchAndDisplayPosition(struct Node* head, int number) {
int position = 1;
struct Node* current = head;
while (current != NULL) {
if (current->data == number) {
printf("Number found at position: %d\n", position);
return; }
position++;
current = current->next; }
printf("Number not Found\n");
}
void swapNodes(struct Node** head, int m, int n) {
if (m == n) return;
struct Node* prevM = NULL;
struct Node* currentM = *head;
while (currentM && currentM->data != m) {
prevM = currentM;
currentM = currentM->next; }
struct Node* prevN = NULL;
struct Node* currentN = *head;
while (currentN && currentN->data != n) {
prevN = currentN;
currentN = currentN->next;
}
if (currentM == NULL || currentN == NULL) {
printf("Invalid swap\n");
return;}
if (prevM != NULL) {
prevM->next = currentN;
} else {
*head = currentN; }
if (prevN != NULL) {
prevN->next = currentM;
} else {
*head = currentM;
}
struct Node* temp = currentN->next;
currentN->next = currentM->next;
currentM->next = temp;
}
void deleteFromPosition(struct Node** head, int position) {
if (*head == NULL) {
printf("List is empty.\n");
return;
}
struct Node* current = *head;
struct Node* prev = NULL;
int currentPosition = 1;
while (current != NULL && currentPosition < position) {
prev = current;
current = current->next;
currentPosition++;}
if (current == NULL) {
printf("Position not found in the list.\n");
return; }
if (prev == NULL) {
*head = current->next;
} else {
prev->next = current->next;}
free(current);
printf("Node at position %d deleted successfully.\n", position);
}
int main() {
struct Node* head = NULL; // Initialize an empty linked list
int choice, data, number, m, n, position;
while (1) {
printf("\nMenu:\n");
printf("1. Insert Element\n2. Display List\n 3. Search Number and Display Position\n 4. Swap
mth and nth Elements\n 5. Delete Node from Specific Position\n 6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter data to insert: ");
scanf("%d", &data);
insertEnd(&head, data);
break;
case 2:
printf("Linked List: ");
display(head);
break;
case 3:
printf("Enter the number to search: ");
scanf("%d", &number);
searchAndDisplayPosition(head, number);
break;
case 4:
printf("Enter the values of m and n: ");
scanf("%d %d", &m, &n);
swapNodes(&head, m, n);
break;
case 5:
printf("Enter the position to delete: ");
scanf("%d", &position);
deleteFromPosition(&head, position);
break;
case 6:
printf("Exiting the program.\n");
exit(0);
default:
printf("Invalid choice. Please select a valid option.\n");
}
}
return 0;
}
4) Write a ‘C’ program to create doubly link list and display nodes having odd value.
ANS:-#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* prev;
struct Node* next; };
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
void insertEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* current = *head;
while (current->next != NULL) {
current = current->next; }
current->next = newNode;
newNode->prev = current;
}
void displayOddNodes(struct Node* head) {
printf("Nodes with odd values: ");
struct Node* current = head;
while (current != NULL) {
if (current->data % 2 != 0) {
printf("%d <-> ", current->data);
}
current = current->next;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL; // Initialize an empty doubly linked list
// Insert elements into the doubly linked list
insertEnd(&head, 10);
insertEnd(&head, 21);
insertEnd(&head, 30);
insertEnd(&head, 45);
insertEnd(&head, 50);
// Display nodes with odd values
displayOddNodes(head);
return 0;
}
SET C:
1) Write a C program to find intersection of two singly linked lists.
ANS:-
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next; };
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insertEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
struct Node* findIntersection(struct Node* head1, struct Node* head2) {
struct Node* current1 = head1;
struct Node* current2 = head2;
int len1 = 0, len2 = 0;
// Find the lengths of both linked lists
while (current1 != NULL) {
len1++;
current1 = current1->next;
}
while (current2 != NULL) {
len2++;
current2 = current2->next;}
current1 = head1;
current2 = head2;
int diff = abs(len1 - len2);
if (len1 > len2) {
for (int i = 0; i < diff; i++) {
current1 = current1->next; }
} else {
for (int i = 0; i < diff; i++) {
current2 = current2->next; }
}
while (current1 != NULL && current2 != NULL) {
if (current1 == current2) {
return current1;}
current1 = current1->next;
current2 = current2→next; }
return NULL; // No intersection point found
}
int main() {
struct Node* list1 = NULL;
struct Node* list2 = NULL;
insertEnd(&list1, 10);
insertEnd(&list1, 20);
insertEnd(&list1, 30);
insertEnd(&list2, 40);
insertEnd(&list2, 50);
struct Node* intersectionNode = createNode(60);
list1->next->next->next = intersectionNode;
list2->next->next = intersectionNode;
struct Node* intersection = findIntersection(list1, list2);
if (intersection != NULL) {
printf("Intersection point: %d\n", intersection->data);
} else {
printf("No intersection point found.\n");
}
return 0;}
ASSIGNMENT 6
SET A:
1) Write a C program to implement Static implementation of stack of integers with following
operation:
-Initialize(), push(), pop(), isempty(), isfull(), display()
ANS:-
#include <stdio.h>
#define MAX_SIZE 10
struct Stack {
int arr[MAX_SIZE];
int top; };
void Initialize(struct Stack *stack) {
stack->top = -1;
}
void push(struct Stack *stack, int value) {
if (stack->top == MAX_SIZE - 1) {
printf("Stack is full. Cannot push.\n");
return;
}
stack->arr[++stack->top] = value;
}
int pop(struct Stack *stack) {
if (stack->top == -1) {
printf("Stack is empty. Cannot pop.\n");
return -1; // Return a sentinel value
}
return stack->arr[stack->top--];
}
int isEmpty(struct Stack *stack) {
return stack->top == -1;
}
int isFull(struct Stack *stack) {
return stack->top == MAX_SIZE - 1;
}
void display(struct Stack *stack) {
if (isEmpty(stack)) {
printf("Stack is empty.\n");
return;
}
printf("Stack elements:\n");
for (int i = stack->top; i >= 0; i--) {
printf("%d\n", stack->arr[i]);
}
}
int main() {
struct Stack stack;
Initialize(&stack);
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
printf("Stack is full? %s\n", isFull(&stack) ? "Yes" : "No");
printf("Stack is empty? %s\n", isEmpty(&stack) ? "Yes" : "No");
display(&stack);
printf("Popped: %d\n", pop(&stack));
printf("Popped: %d\n", pop(&stack));
printf("Popped: %d\n", pop(&stack));
printf("Popped: %d\n", pop(&stack)); // Trying to pop from an empty stack
return 0;
}
……………..………..
SET B :
1) Write a ‘C’ program which accepts the string and check whether the string is Palindrome or
not using stack. (Use Static/Dynamic implementation of Stack).
ANS:-STATIC
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
struct Stack {
char arr[MAX_SIZE];
int top;
};
void Initialize(struct Stack *stack) {
stack->top = -1;
}
void push(struct Stack *stack, char value) {
if (stack->top == MAX_SIZE - 1) {
printf("Stack is full.\n");
return;}
stack->arr[++stack->top] = value;
}
char pop(struct Stack *stack) {
if (stack->top == -1) {
printf("Stack is empty.\n");
return '\0';}
return stack->arr[stack->top--];
}
int isEmpty(struct Stack *stack) {
return stack->top == -1;}
int isPalindrome(char *str) {
struct Stack stack;
Initialize(&stack);
int len = strlen(str);
for (int i = 0; i < len; i++) {
push(&stack, str[i]); }
for (int i = 0; i < len; i++) {
if (pop(&stack) != str[i]) {
return 0; // Not a palindrome}
}
return 1; // Palindrome
}
int main() {
char input[100];
printf("Enter a string: ");
scanf("%s", input);
if (isPalindrome(input)) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
return 0;
}
2) Write a ‘C’ program to read a postfix expression, evaluate it and display the result. (Use
Static/Dynamic implementation of Stack).
ANS:-STATIC
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#define MAX_SIZE 100
struct Stack {
int arr[MAX_SIZE];
int top;};
void Initialize(struct Stack *stack) {
stack->top = -1;}
void push(struct Stack *stack, int value) {
if (stack->top == MAX_SIZE - 1) {
printf("Stack is full.\n");
return; }
stack->arr[++stack->top] = value;}
int pop(struct Stack *stack) {
if (stack->top == -1) {
printf("Stack is empty.\n");
return -1; }
return stack->arr[stack->top--];}
int evaluatePostfix(char *postfix) {
struct Stack stack;
Initialize(&stack);
int len = strlen(postfix);
for (int i = 0; i < len; i++) {
if (isdigit(postfix[i])) {
push(&stack, postfix[i] - '0');
} else {
int operand2 = pop(&stack);
int operand1 = pop(&stack);
switch (postfix[i]) {
case '+':
push(&stack, operand1 + operand2);
break;
case '-':
push(&stack, operand1 - operand2);
break;
case '*':
push(&stack, operand1 * operand2);
break;
case '/':
push(&stack, operand1 / operand2);
break; }
}
}
return pop(&stack);
}
int main() {
char postfix[100];
printf("Enter a postfix expression: ");
scanf("%s", postfix);
int result = evaluatePostfix(postfix);
printf("Result: %d\n", result);
return 0;
}
SET C:
1) Write a program to check whether the contents of two stacks are identical.
ANS:-
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
struct Stack {
int arr[MAX_SIZE];
int top;};
void Initialize(struct Stack *stack) {
stack->top = -1;}
void push(struct Stack *stack, int value) {
if (stack->top == MAX_SIZE - 1) {
printf("Stack is full.\n");
return; }
stack->arr[++stack->top] = value;}
int pop(struct Stack *stack) {
if (stack->top == -1) {
printf("Stack is empty.\n");
return -1; }
return stack->arr[stack->top--];}
int isEmpty(struct Stack *stack) {
return stack->top == -1;}
int isIdentical(struct Stack *stack1, struct Stack *stack2) {
if (stack1->top != stack2->top) {
return 0; }
for (int i = 0; i <= stack1->top; i++) {
if (stack1->arr[i] != stack2->arr[i]) {
return 0; }
}
return 1;
}
int main() {
struct Stack stack1, stack2;
Initialize(&stack1);
Initialize(&stack2);
push(&stack1, 10);
push(&stack1, 20);
push(&stack1, 30);
push(&stack2, 10);
push(&stack2, 20);
push(&stack2, 30);
if (isIdentical(&stack1, &stack2)) {
printf("Stacks are identical.\n");
} else {
printf("Stacks are not identical.\n");
}
return 0;
}
ASSIGNMENT 7
SET A:
1) Write a C program to Implement Static implementation of Queue of integers with
following operation:
-Initialize(), insert(), delete(), isempty(), isfull(), display(), peek()
ANS:-
#include <stdio.h>
#include <stdbool.h>
#define MAX_SIZE 10
struct Queue {
int data[MAX_SIZE];
int front, rear;};
2) Write a program to reverse the elements of a queue (Use Static implementation of Queue)
ANS:-
#include <stdio.h>
#include <stdbool.h>
#define MAX_SIZE 10
// Structure for the queue
struct Queue {
int data[MAX_SIZE];
int front, rear;};
// Initialize the queue
void Initialize(struct Queue *queue) {
queue->front = -1;
queue->rear = -1;}
bool IsEmpty(struct Queue *queue) {
return (queue->front == -1);
}
// Check if the queue is full
bool IsFull(struct Queue *queue) {
return ((queue->rear + 1) % MAX_SIZE == queue->front);}
void Insert(struct Queue *queue, int value) {
if (IsFull(queue)) {
printf("Queue is full. Cannot insert.\n");
return;}
if (IsEmpty(queue)) {
queue->front = 0;
queue->rear = 0;
} else {
queue->rear = (queue->rear + 1) % MAX_SIZE;
}
queue->data[queue->rear] = value;
}
void Delete(struct Queue *queue) {
if (IsEmpty(queue)) {
printf("Queue is empty. Cannot delete.\n");
return; }
if (queue->front == queue->rear) {
queue->front = -1;
queue->rear = -1;
} else {
queue->front = (queue->front + 1) % MAX_SIZE; }
}
void ReverseQueue(struct Queue *queue) {
if (IsEmpty(queue)) {
printf("Queue is empty. Cannot reverse.\n");
return; }
int stack[MAX_SIZE];
int top = -1;
int i = queue->front;
while (i != queue->rear) {
stack[++top] = queue->data[i];
i = (i + 1) % MAX_SIZE; }
stack[++top] = queue->data[i];
i = queue->front;
while (top >= 0) {
queue->data[i] = stack[top--];
i = (i + 1) % MAX_SIZE;}
}
void Display(struct Queue *queue) {
if (IsEmpty(queue)) {
printf("Queue is empty.\n");
return;
}
int i = queue->front;
while (i != queue->rear) {
printf("%d ", queue->data[i]);
i = (i + 1) % MAX_SIZE; }
printf("%d\n", queue->data[i]);
}
int main() {
struct Queue queue;
Initialize(&queue);
Insert(&queue, 10);
Insert(&queue, 20);
Insert(&queue, 30);
Insert(&queue, 40);
printf("Original Queue: ");
Display(&queue);
ReverseQueue(&queue);
printf("Reversed Queue: ");
Display(&queue);
return 0;
}
SET B:
1) Write a C program to Implement Dynamic implementation of Queue of integers with
following operation:
-Initialize(), insert(), delete(), isempty(), display(), peek()
ANS:-
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct QueueNode {
int data;
struct QueueNode *next;};
struct Queue {
struct QueueNode *front;
struct QueueNode *rear;};
void Initialize(struct Queue *queue) {
queue->front = NULL;
queue->rear = NULL;
}
bool IsEmpty(struct Queue *queue) {
return (queue->front == NULL);}
void Insert(struct Queue *queue, int value) {
struct QueueNode *newNode = (struct QueueNode *)malloc(sizeof(struct QueueNode));
if (newNode == NULL) {
printf("Memory allocation failed. Cannot insert.\n");
return; }
newNode->data = value;
newNode->next = NULL;
if (IsEmpty(queue)) {
queue->front = newNode;
queue->rear = newNode;
} else {
queue->rear->next = newNode;
queue->rear = newNode; }
}
void Delete(struct Queue *queue) {
if (IsEmpty(queue)) {
printf("Queue is empty. Cannot delete.\n");
return;}
struct QueueNode *temp = queue->front;
queue->front = queue->front->next;
free(temp);
if (queue->front == NULL) {
queue->rear = NULL; }
}
void Display(struct Queue *queue) {
if (IsEmpty(queue)) {
printf("Queue is empty.\n");
return; }
struct QueueNode *current = queue->front;
while (current != NULL) {
printf("%d ", current->data);
current = current->next; }
printf("\n");
}
int Peek(struct Queue *queue) {
if (IsEmpty(queue)) {
printf("Queue is empty.\n");
return -1; }
return queue->front->data;
}
int main() {
struct Queue queue;
Initialize(&queue);
Insert(&queue, 10);
Insert(&queue, 20);
Insert(&queue, 30);
printf("Queue: ");
Display(&queue);
struct QueueNode {
int data;
struct QueueNode *next;
};
struct Queue {
struct QueueNode *front;
struct QueueNode *rear;};
void Initialize(struct Queue *queue) {
queue->front = NULL;
queue->rear = NULL;}
bool IsEmpty(struct Queue *queue) {
return (queue->front == NULL);}
void Insert(struct Queue *queue, int value) {
struct QueueNode *newNode = (struct QueueNode *)malloc(sizeof(struct QueueNode));
if (newNode == NULL) {
printf("Memory allocation failed. Cannot insert.\n");
return;}
newNode->data = value;
newNode->next = NULL;
if (IsEmpty(queue)) {
queue->front = newNode;
queue->rear = newNode;
} else {
queue->rear->next = newNode;
queue->rear = newNode;
}
}
void Delete(struct Queue *queue) {
if (IsEmpty(queue)) {
printf("Queue is empty. Cannot delete.\n");
return;}
struct QueueNode *temp = queue->front;
queue->front = queue->front->next;
free(temp);
if (queue->front == NULL) {
queue->rear = NULL; }
}
void ReverseQueue(struct Queue *queue) {
if (IsEmpty(queue)) {
return; }
int data = queue->front->data;
Delete(queue);
ReverseQueue(queue);
Insert(queue, data);
}
……..
ASSIGNMENT 8
SET A:
1) Write C programs to implement create and display operation for binary tree.
ANS:-
#include <stdio.h>
#include <stdlib.h>
// Structure for a binary tree node
struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;};
struct TreeNode* createNode(int data) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;}
2) Write C programs to implement create and display operation for binary search tree.
ANS:-
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;};
struct TreeNode* createNode(int data) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct TreeNode* insert(struct TreeNode* root, int data) {
if (root == NULL) {
root = createNode(data);
} else if (data <= root->data) {
root->left = insert(root->left, data);
} else {
root->right = insert(root->right, data);}
return root;
}
void inorderTraversal(struct TreeNode* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right); }
}
int main() {
struct TreeNode* root = NULL;
int values[] = {5, 3, 8, 1, 4, 7, 9};
for (int i = 0; i < sizeof(values) / sizeof(values[0]); i++) {
root = insert(root, values[i]);
}
printf("Inorder traversal of the binary search tree: ");
inorderTraversal(root);
printf("\n");
return 0;
}
SET B:
1) Write a C Program to implement the following functions on Binary Search Tree
- To insert a new element in the tree.
- To search an element in tree and give the proper message.
ANS:-
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;};
struct TreeNode* createNode(int data) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;}
struct TreeNode* insert(struct TreeNode* root, int data) {
if (root == NULL) {
root = createNode(data);
} else if (data < root->data) {
root->left = insert(root->left, data);
} else if (data > root->data) {
root->right = insert(root->right, data); }
return root;
}
struct TreeNode* search(struct TreeNode* root, int key) {
if (root == NULL || root->data == key) {
return root; }
if (key < root->data) {
return search(root->left, key); }
return search(root->right, key);}
int main() {
struct TreeNode* root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
int searchKey = 60;
struct TreeNode* result = search(root, searchKey);
if (result != NULL) {
printf("%d found in the tree.\n", searchKey);
} else {
printf("%d not found in the tree.\n", searchKey); }
return 0;
}
SET C:
1) Write C programs to create and display the elements using Inorder traversal.
ANS:-
#include <stdio.h>
#include <stdlib.h>
// Structure for a binary tree node
struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;};
struct TreeNode* createNode(int data) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;}
struct TreeNode* insert(struct TreeNode* root, int data) {
if (root == NULL) {
root = createNode(data);
} else if (data < root->data) {
root->left = insert(root->left, data);
} else if (data > root->data) {
root->right = insert(root->right, data); }
return root;
}
void inorderTraversal(struct TreeNode* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
}
int main() {
struct TreeNode* root = NULL;
// Insert elements into the binary tree
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
printf("Inorder traversal of the binary tree: ");
inorderTraversal(root);
printf("\n");
return 0;
}
ASSIGNMENT 9
SET A:
1) Write a C program to read a graph as adjacency matrix and display the adjacency matrix.
ANS:-
#include <stdio.h>
int main() {
int vertices;
int graph[MAX_SIZE][MAX_SIZE];
readGraph(graph, vertices);
displayGraph(graph, vertices);
return 0;
}
SET B:
1) Write a C program to convert adjacency matrix into adjacency list. Display the adjacency
list.
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
struct Node {
int vertex;
struct Node* next;};
struct Node* createNode(int vertex) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->vertex = vertex;
newNode->next = NULL;
return newNode;}
void addEdge(struct Node** adjList, int src, int dest) {
struct Node* newNode = createNode(dest);
newNode->next = adjList[src];
adjList[src] = newNode;}
void convertToAdjList(int graph[MAX_SIZE][MAX_SIZE], int vertices, struct Node** adjList) {
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
if (graph[i][j] == 1) {
addEdge(adjList, i, j);}
}
}
}
void displayAdjList(struct Node** adjList, int vertices) {
printf("Adjacency List:\n");
for (int i = 0; i < vertices; i++) {
printf("Vertex %d:", i);
struct Node* current = adjList[i];
while (current != NULL) {
printf(" %d", current->vertex);
current = current->next; }
printf("\n");}
}
int main() {
int vertices;
int graph[MAX_SIZE][MAX_SIZE];
struct Node* adjList[MAX_SIZE] = {NULL};
printf("Enter the number of vertices: ");
scanf("%d", &vertices);
if (vertices <= 0 || vertices > MAX_SIZE) {
printf("Invalid number of vertices.\n");
return 1; }
printf("Enter the adjacency matrix:\n");
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
scanf("%d", &graph[i][j]); }}
convertToAdjList(graph, vertices, adjList);
displayAdjList(adjList, vertices);
return 0;}
n
2) Write a C program to traverse graph by using BFS.
ANS:-
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// Queue structure for BFS traversal
struct Queue {
int items[MAX_SIZE];
int front;
int rear;};
struct Queue* createQueue() {
struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->front = -1;
queue->rear = -1;
return queue;}
int isEmpty(struct Queue* queue) {
return queue->front == -1;}
void enqueue(struct Queue* queue, int item) {
if (queue->rear == MAX_SIZE - 1) {
printf("Queue is full.\n");
} else {
if (queue->front == -1) {
queue->front = 0; }
queue->rear++;
queue->items[queue->rear] = item; }
}
int dequeue(struct Queue* queue) {
int item;
if (isEmpty(queue)) {
printf("Queue is empty.\n");
item = -1;
} else {
item = queue->items[queue->front];
queue->front++;
if (queue->front > queue->rear) {
queue->front = queue->rear = -1; }
}
return item;
}
void BFS(int graph[MAX_SIZE][MAX_SIZE], int vertices, int startVertex) {
struct Queue* queue = createQueue();
int visited[MAX_SIZE] = {0};
printf("BFS traversal starting from vertex %d: ", startVertex);
visited[startVertex] = 1; // Mark the start vertex as visited
enqueue(queue, startVertex);
while (!isEmpty(queue)) {
int currentVertex = dequeue(queue);
printf("%d ", currentVertex);
for (int i = 0; i < vertices; i++) {
if (graph[currentVertex][i] == 1 && !visited[i]) {
enqueue(queue, i);
visited[i] = 1;}
}
}
printf("\n");
}
int main() {
int vertices;
int graph[MAX_SIZE][MAX_SIZE];
int startVertex;
printf("Enter the number of vertices: ");
scanf("%d", &vertices);
if (vertices <= 0 || vertices > MAX_SIZE) {
printf("Invalid number of vertices.\n");
return 1;
}
printf("Enter the adjacency matrix:\n");
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
scanf("%d", &graph[i][j]);
}
}
printf("Enter the starting vertex for BFS: ");
scanf("%d", &startVertex);
BFS(graph, vertices, startVertex);
return 0;
}
SET C:
1) Implement a program to read a graph as adjacency matrix. Find the transpose of the matrix
for display accepted adjacency Matrix and Adjacency Matrix and List of transpose of the
matrix.
ANS:-
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// Function to read a graph as an adjacency matrix
void readGraph(int graph[MAX_SIZE][MAX_SIZE], int vertices) {
printf("Enter the adjacency matrix:\n");
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
scanf("%d", &graph[i][j]);
}
}
}
void transposeMatrix(int matrix[MAX_SIZE][MAX_SIZE], int vertices, int transpose[MAX_SIZE]
[MAX_SIZE]) {
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
transpose[j][i] = matrix[i][j];
}
}
}
void displayMatrix(int matrix[MAX_SIZE][MAX_SIZE], int vertices) {
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int vertices;
int adjacencyMatrix[MAX_SIZE][MAX_SIZE];
int transposeMatrix[MAX_SIZE][MAX_SIZE];
printf("Enter the number of vertices: ");
scanf("%d", &vertices);
if (vertices <= 0 || vertices > MAX_SIZE) {
printf("Invalid number of vertices.\n");
return 1;
}
readGraph(adjacencyMatrix, vertices);
printf("\nAdjacency Matrix:\n");
displayMatrix(adjacencyMatrix, vertices);