DS Lab Report (1)
DS Lab Report (1)
Output:
Algorithm:
1.Define and initialize integer arrays for matrix A, B and resultant matrix Prod with maximum
size MAX x MAX.
2.Input the number of rows and columns for matrix A using scanf() function.
3.Using nested loops, input the values for each element of matrix A.
4.Input the number of rows and columns for matrix B using scanf() function.
5.Using nested loops, input the values for each element of matrix B.
6.If the number of columns of matrix A is not equal to the number of rows of matrix B, then print
an error message indicating that multiplication between matrices A and B is not possible.
Otherwise, proceed to step 7.
7.Using nested loops, calculate the product of matrices A and B by performing dot product of
each row of matrix A with each column of matrix B. Store the result in the corresponding
element of the resultant matrix Prod.
8.Print the resultant matrix Prod using nested loops.
9.End the program.
4. Use a for loop to search for the element to be deleted in the array. If the element is found,
proceed with the following steps:
a. Use another for loop to shift the elements after the deleted element to the left by one
position.
b. Decrement the size of the array.
c. Exit the loop.
5. If the element is not found, print an error message.
6. Define another function printArray to print the elements of an array, which takes two
parameters:
a. An array arr[] of integers.
b. An integer size that represents the size of the array.
7. Inside the printArray function, use a for loop to print each element of the array.
8. Define the main function.
9. Inside the main function, declare an array arr[] of integers with size MAX_SIZE and an
integer variable size to store the size of the array.
10. Get user input for the size of the array and elements of the array using scanf() function.
11. Print the original array using printArray function.
12. Get user input for the element to be deleted using scanf() function.
13. Call the deleteElement function to delete the element from the array.
14. Print the updated array using printArray function.
15. Return 0 to exit the program.
2.c) Linear Search inserting the searched value in the same array
Code:
#include <stdio.h>
int main() {
int n, searchValue, insertIndex;
printf("Enter the size of the array: ")
scanf("%d", &n);
int arr[n+1];
printf("Enter the elements of the array:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);}
printf("Enter the value to search: ");
scanf("%d", &searchValue);
// Perform linear search
for (int i = 0; i < n; i++) {
if (arr[i] == searchValue) {
printf("%d found at index %d.\n", searchValue, i);
insertIndex = i;
break;
}
if (i == n-1) {
printf("%d not found in the array.\n", searchValue);
return 0;
}
}
// Insert searched value at correct position
for (int i = n-1; i >= insertIndex; i--) {
arr[i+1] = arr[i];}
arr[insertIndex] = searchValue;
n++;
// Print the updated array
printf("The updated array is:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]); }
return 0;
}
Output:
Algorithm:
Here's the algorithm for the given code:
1. Start
2. Declare integer variables n, searchValue, and insertIndex.
3. Print "Enter the size of the array: "
4. Read n from user input
5. Declare an integer array arr of size n+1.
6. Print "Enter the elements of the array:"
7. Read n integers into arr using a for loop.
8. Print "Enter the value to search: "
9. Read searchValue from user input.
10. Perform linear search through the array arr using a for loop.
a. If arr[i] is equal to searchValue, print "searchValue found at index i", set insertIndex to i,
and break the loop.
b. If i equals n-1, print "searchValue not found in the array." and return 0.
11. Using another for loop, shift the elements in arr from the insertIndex to the right by 1.
12. Insert the searched value at the correct position (insertIndex) in arr.
13. Increment n by 1.
14. Print "The updated array is:".
15. Using another for loop, print the updated array arr.
16. End.
Output:
Algorithm:
Algorithm for Binary Search in C:
1. Start the program
2. Declare integer variables n, ITEM, BEG, END, MID, LOC.
3. Print a message to prompt the user to enter the number of elements to be sorted and read the
input value into the variable n.
4. Declare an integer array of size n and read n elements of the array.
5. Print the entered array.
6. Print a message to prompt the user to enter the value to search and read the input value into the
variable ITEM.
7. Set BEG=0, END=n-1 and MID=(BEG+END)/2.
8. Set LOC=MID.
9. Use a while loop to perform the binary search until the ITEM is found or the BEG is greater
than END.
10. If ITEM is less than the middle element of the array, set END=MID-1.
11. Else, set BEG=MID+1.
12. Recalculate the MID.
13. If the MID element is equal to ITEM, set LOC=MID.
14. Print the index of the ITEM in the array as LOC+1.
15. End the program.
3.a) Bubble sort using Array
Code:
#include<stdio.h>
int main()
{
int DATA [6]={77,42,35,12,101,5};
int TEMP;
for(int k=0;k<5;k++)
{
//int PTR=1;
for(int PTR=0;PTR<6-k-1;PTR++)
{
if(DATA[PTR]>DATA[PTR+1])
{
TEMP=DATA[PTR];
DATA[PTR]=DATA[PTR+1];
DATA[PTR+1]=TEMP;
}
}
for(int i=0;i<6;i++)
{
printf("%d \n",DATA[i]);
}
return 0;
}
Algorithm:
Algorithm for Binary Search in C:
1. Start the program
2. Declare integer variables n, ITEM, BEG, END, MID, LOC.
3. Print a message to prompt the user to enter the number of elements to be sorted and read the
input value into the variable n.
4. Declare an integer array of size n and read n elements of the array.
5. Print the entered array.
6. Print a message to prompt the user to enter the value to search and read the input value into the
variable ITEM.
7. Set BEG=0, END=n-1 and MID=(BEG+END)/2.
8. Set LOC=MID.
9. Use a while loop to perform the binary search until the ITEM is found or the BEG is greater
than END.
10. If ITEM is less than the middle element of the array, set END=MID-1.
11. Else, set BEG=MID+1.
12. Recalculate the MID.
13. If the MID element is equal to ITEM, set LOC=MID.
14. Print the index of the ITEM in the array as LOC+1.
15. End the program.
Output:
Output:
Algorithm:
1. Read the size of the array from the user
2. Declare an integer array of that size
3. Read the elements of the array from the user
4. Declare two pointers of type int, current and next
5. For i = 0 to size-2 do
For j = 0 to size-i-2 do
Set current to the address of the ith element of the array
Set next to the address of the (i+1)th element of the array
If the value pointed to by current is greater than the value pointed to by next, then
Swap their values using a temporary variable
Move both pointers to the next element
End For
End For
6. Print the sorted array
4.Take input & Print name, id,section,cgpa of 3 students using structure,
pointer
Code:
#include <stdio.h>
#include <stdlib.h>
#define MAX_NAME_LENGTH 50
typedef struct {
char name[MAX_NAME_LENGTH];
int id;
char section;
float cgpa;
} Student;
int main() {
int i;
Student *ta[3];
// Allocate memory for each TA
for (i = 0; i < 3; i++) {
ta[i] = (Student *) malloc(sizeof(Student));
}
// Take input for each TA
for (i = 0; i < 3; i++) {
printf("Enter name for TA %d: ", i+1);
scanf("%s", ta[i]->name);
printf("Enter ID for TA %d: ", i+1);
scanf("%d", &ta[i]->id);
printf("Enter section for TA %d: ", i+1);
scanf(" %c", &ta[i]->section);
printf("Enter CGPA for TA %d: ", i+1);
scanf("%f", &ta[i]->cgpa);
}
// Print details of each TA
for (i = 0; i < 3; i++) {
printf("\nDetails of TA %d:\n", i+1);
printf("Name: %s\n", ta[i]->name);
printf("ID: %d\n", ta[i]->id);
printf("Section: %c\n", ta[i]->section);
printf("CGPA: %.2f\n", ta[i]->cgpa);
}
// Free memory allocated for each TA
for (i = 0; i < 3; i++) {
free(ta[i]);
}
return 0;
}
Output:
Algorithm:
1. Declare a struct Student to hold information about each TA.
2. Declare a variable i to use as loop counter.
3. Declare an array of 3 pointers to struct Student called ta.
4. Use a for loop to allocate memory for each TA by iterating from 0 to 2:
a. Use the malloc() function to allocate memory for a new Student struct and cast the return
value to a pointer of type Student.
b. Assign the returned pointer to ta[i].
5. Use another for loop to take input for each TA by iterating from 0 to 2:
a. Use printf() to prompt the user to enter the name of TA[i], and use scanf() to read it into the
name member of ta[i].
b. Use printf() to prompt the user to enter the ID of TA[i], and use scanf() to read it into the id
member of ta[i].
c. Use printf() to prompt the user to enter the section of TA[i], and use scanf() to read it into
the section member of ta[i].
d. Use printf() to prompt the user to enter the CGPA of TA[i], and use scanf() to read it into
the cgpa member of ta[i].
6. Use another for loop to print the details of each TA by iterating from 0 to 2:
a. Use printf() to print the header "Details of TA i:".
b. Use printf() to print the name, id, section, and cgpa of ta[i] using appropriate formatting.
7. Use another for loop to free the memory allocated for each TA by iterating from 0 to 2:
a. Use the free() function to release the memory allocated for ta[i].
8. Return 0 to indicate successful execution of the program.
Code:
#include <stdio.h>
// Define the structure for student
struct student {
char name[50];
int id;
char section;
float cgpa;
};
int main() {
// Declare an array of 3 students
struct student students[3];
// Read in information for each student using a loop
for (int i = 0; i < 3; i++) {
printf("Enter name for student %d: ", i+1);
scanf("%s", students[i].name);
printf("Enter ID for student %d: ", i+1);
scanf("%d", &students[i].id);
printf("Enter section for student %d: ", i+1);
scanf(" %c", &students[i].section);
printf("Enter CGPA for student %d: ", i+1);
scanf("%f", &students[i].cgpa);
printf("\n");
}
// Print out the information for each studen…
for (int i = 0; i < 3; i++) {
struct student *ptr = &students[i]; // pointer to the current student
printf("Information for student %d:\n", i+1);
printf("Name: %s\n", ptr->name);
printf("ID: %d\n", ptr->id);
printf("Section: %c\n", ptr->section);
printf("CGPA: %.2f\n", ptr->cgpa);
printf("\n");
}
return 0;
}
Algorithm:
1. Start
2. Define a structure called 'student' with four members: name, id, section, cgpa
3. Declare an array of three elements of the structure 'student'
4. Using a loop, read in information for each student:
a. Prompt user to enter name for student 'i'
b. Read in name for student 'i'
c. Prompt user to enter ID for student 'i'
d. Read in ID for student 'i'
e. Prompt user to enter section for student 'i'
f. Read in section for student 'i'
g. Prompt user to enter CGPA for student 'i'
h. Read in CGPA for student 'i'
5. Using another loop, print out the information for each student:
a. Declare a pointer to a structure called 'ptr' and set it to point to the current student
b. Print the information for the current student using the pointer:
i. Print the name
ii. Print the ID
iii. Print the section
iv. Print the CGPA
6.End
Output :
5.a) Insertion of a node in the middle of a linked list
Code:
#include <stdio.h>
#include <stdlib.h>
// Define the structure of each node in the linked list
struct Node {
int data; // The data contained in the node
struct Node* next; // A pointer to the next node in the list
};
// Create a function to insert a node in the middle of the linked list
void insertNode(struct Node* head, int data, int position) {
// Create a new node with the given data
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
// Find the node before the position where we want to insert the new node
struct Node* currentNode = head;
for (int i = 0; i < position - 1; i++) {
currentNode = currentNode->next;
}
// Save a pointer to the node that comes after the insertion point
struct Node* nextNode = currentNode->next;
// Insert the new node between the two existing nodes
currentNode->next = newNode;
newNode->next = nextNode;
}
int main() {
// Create an empty linked list
struct Node* head = NULL;
struct Node* tail = NULL;
// Ask the user to enter the number of nodes and the data for each node
int numNodes, nodeData;
printf("Enter the number of nodes: ");
scanf("%d", &numNodes);
for (int i = 0; i < numNodes; i++) {
printf("Enter the data for node %d: ", i+1);
scanf("%d", &nodeData);
// Create a new node with the entered data
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = nodeData;
newNode->next = NULL;
// If the list is empty, set the new node as the head
if (head == NULL) {
head = newNode;
tail = newNode;
}
// Otherwise, add the new node to the end of the list
else {
tail->next = newNode;
tail = newNode;
}
}
// Ask the user to enter the data and position for the new node
int newData, position;
printf("\nEnter the data for the new node: ");
scanf("%d", &newData);
printf("Enter the position for the new node: ");
scanf("%d", &position);
// Insert the new node in the middle of the linked list
if (position <= 1) {// If the user wants to insert the new node at the beginning of the list,
// simply add it to the front
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = newData;
newNode->next = head;
head = newNode;
}
else {
// Otherwise, insert the new node in the middle
insertNode(head, newData, position);}
// Print the updated linked list
printf("\nUpdated Linked List: ");
struct Node* currentNode = head;
while (currentNode != NULL) {
printf("%d ", currentNode->data);
currentNode = currentNode->next;
}
return 0;
}
Output:
Algorithm:
Here's an algorithm for the given code:
1. Create a structure for a node in the linked list, containing an integer data and a pointer to the
next node.
2. Define a function insertNode() which takes a pointer to the head of the linked list, data to be
inserted, and position at which it is to be inserted.
3. Inside insertNode(), create a new node with the given data.
4. Traverse the linked list using a currentNode pointer to reach the node just before the position
where we want to insert the new node.
5. Save a pointer to the node that comes after the insertion point.
6. Set the next pointer of currentNode to the new node and the next pointer of newNode to
nextNode.
7. In the main function, create an empty linked list with head and tail pointers as NULL.
8. Read the number of nodes from the user and add them to the linked list one by one using a for
loop.
9. Ask the user for the data and position of the new node to be inserted.
10. If the position is less than or equal to 1, create a new node and make it the new head of the
linked list.
11. Otherwise, call the insertNode() function with the head of the linked list, data, and position as
arguments.
12. Traverse the linked list using a currentNode pointer and print the data of each node.
Output:
Algorithm:
1. Create a struct Node with integer data and a pointer to the next Node
2. Define a function deleteNode with parameters head_ref and key
3. Declare two Node pointers: temp and prev
4. Set temp to the value of head_ref
5. If temp is not NULL and temp's data is equal to key, set head_ref to temp's next and free temp,
then return
6. While temp is not NULL and temp's data is not equal to key, set prev to temp and temp to
temp's next
7. If temp is NULL, return
8. Set prev's next to temp's next and free temp
9. Define a function insertNode with parameters head_ref and data
10. Declare a Node pointer new_node and allocate memory for it
11. Set new_node's data to data and its next to NULL
12. If head_ref is NULL, set head_ref to new_node and return
13. Declare a Node pointer last_node and set it to head_ref
14. While last_node's next is not NULL, set last_node to last_node's next
15. Set last_node's next to new_node
16. Define a function printList with parameter node
17. While node is not NULL, print node's data and set node to node's next
18. Print a new line
19. Define the main function
20. Declare a Node pointer head and set it to NULL
21. Get user input for the number of nodes and set it to num_nodes
22. Print "Enter the values for the nodes: "
23. For i = 0 to num_nodes-1 do the following:
a. Get user input for the value and set it to value
b. Call insertNode with parameters &head and value
24. Print "Original linked list: "
25. Call printList with parameter head
26. Get user input for the key and set it to key
27. Call deleteNode with parameters &head and key
28. Print "Updated linked list: "
29. Call printList with parameter head
30. Return 0
5.Quick Sort:
Code:
#include <stdio.h>
// function to swap elements
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
// function to find the partition position
int partition(int array[], int low, int high) {
// select the rightmost element as pivot
int pivot = array[high];
// pointer for greater element
int i = (low - 1);
// traverse each element of the array
// compare them with the pivot
for (int j = low; j < high; j++) {
if (array[j] <= pivot) {
// if element smaller than pivot is found
// swap it with the greater element pointed by i
i++;
// swap element at i with element at j
swap(&array[i], &array[j]);
}
}
// swap the pivot element with the greater element at i
swap(&array[i + 1], &array[high]);
// return the partition point
return (i + 1);
}
void quickSort(int array[], int low, int high) {
if (low < high) {
// find the pivot element such that
// elements smaller than pivot are on left of pivot
// elements greater than pivot are on right of pivot
int pi = partition(array, low, high);
// recursive call on the left of pivot
quickSort(array, low, pi - 1);
// recursive call on the right of pivot
quickSort(array, pi + 1, high);
}
}
// function to print array elements
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}
// main function
int main() {
int data[] = {8, 7, 2, 1, 0, 9, 6};
int n = sizeof(data) / sizeof(data[0]);
printf("Unsorted Array\n");
printArray(data, n);
// perform quicksort on data
quickSort(data, 0, n - 1);
printf("Sorted array in ascending order: \n");
printArray(data, n);
}
Output:
Algorithm:
Input:
- An integer array "array" of size n.
- Two integer indices "low" and "high" representing the lower and upper bounds of the subarray
to be sorted.
Output:
- The sorted array "array" in non-decreasing order.
1. Define a function named "swap" which takes two integer pointers as input and swaps their
values.
1.1. Set a temporary variable "t" equal to the value pointed by the first input pointer.
1.2. Set the value pointed by the first input pointer equal to the value pointed by the second
input pointer.
1.3. Set the value pointed by the second input pointer equal to the temporary variable "t".
2. Define a function named "partition" which takes an integer array "array", and two integer
indices "low" and "high" as input, and returns an integer.
2.1. Set the pivot element as the value at index "high" of the array.
2.2. Set a pointer "i" to "low" - 1.
2.3. For each element of the array from index "low" to index "high" - 1:
2.3.1. If the element at index j is less than or equal to the pivot element:
2.3.1.1. Increment the value of "i" by 1.
2.3.1.2. Call the "swap" function with arguments "&array[i]" and "&array[j]".
2.4. Call the "swap" function with arguments "&array[i+1]" and "&array[high]".
2.5. Return the value (i+1).
3. Define a function named "quickSort" which takes an integer array "array", and two integer
indices "low" and "high" as input.
3.1. If the value of "low" is less than the value of "high":
3.1.1. Call the "partition" function with arguments "array", "low", and "high", and store the
result in a variable named "pi".
3.1.2. Call the "quickSort" function with arguments "array", "low", and "pi-1".
3.1.3. Call the "quickSort" function with arguments "array", "pi+1", and "high".
4. Define a function named "printArray" which takes an integer array "array" and an integer
"size" as input and prints the elements of the array separated by a space.
4.1. For each element of the array from index 0 to index "size" - 1:
4.1.1. Print the element followed by a space.
4.2. Print a newline character.
5. Define the main function.
5.1. Declare an integer array named "data" and initialize it with some values.
5.2. Declare an integer variable named "n" and set it equal to the size of the array "data".
5.3. Call the "printArray" function with arguments "data" and "n" to print the unsorted array.
5.4. Call the "quickSort" function with arguments "data", 0, and "n-1" to sort the array.
5.5. Call the "printArray" function with arguments "data" and "n" to print the sorted array.
6.Insertion Sort:
Code:
#include <stdio.h>
void insertionSort(int array[], int n) {
int i, j, key;
for (i = 1; i < n; i++) {
key = array[i];
j = i - 1;
/* Move elements of array[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && array[j] > key) {
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = key;
}
}
int main() {
int n, i;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int array[n];
printf("Enter the %d elements of the array: ", n);
for (i = 0; i < n; i++) {
scanf("%d", &array[i]);
}
insertionSort(array, n);
printf("Sorted array: ");
for (i = 0; i < n; i++) {
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
Output:
Algorithm:
InsertionSort(A)
1. for j = 2 to A.length
2. key = A[j]
3. // Insert A[j] into the sorted sequence A[1..j-1]
4. i=j-1
5. while i > 0 and A[i] > key
6. A[i+1] = A[i]
7. i=i-1
8. A[i+1] = key
In this algorithm, A is an array of n elements to be sorted. The for loop starting at line 1 iterates
over all the elements of the array, starting from the second element, because the first element is
already considered sorted.
At each iteration, the algorithm selects the key element from the array, which is the element to be
inserted in the sorted sequence A[1..j-1].
The while loop starting at line 5 scans the sorted sequence from right to left, shifting the
elements one position to the right until it finds the correct position to insert the key element.
Finally, the key element is inserted into its correct position in the sorted sequence by assigning it
to A[i+1] at line 8.
Algorithm:
1. Initialize an array queue with maximum size MAX_SIZE, front = -1 and rear = -1
2. Define a function is_empty() to check if the queue is empty or not. Return 1 if empty, 0
otherwise.
3. Define a function is_full() to check if the queue is full or not. Return 1 if full, 0 otherwise.
4. Define a function enqueue() to insert an element into the queue. The function takes an integer
data
as argument.
5. Check if the queue is full using is_full(). If the queue is full, print "Queue Overflow!" and
return.
6. If the queue is not full, check if the front of the queue is -1. If it is, set it to 0.
7. Increment rear and add the data to the queue at the rear index.
8. Print "data enqueued to queue".
9. Define a function dequeue() to remove an element from the queue.
10. Check if the queue is empty using is_empty(). If the queue is empty, print "Queue
Underflow!"
and exit.
11. Get the data at the front of the queue and store it in a variable data.
12. If the front of the queue is the same as the rear, set both to -1.
13. Otherwise, increment front by 1.
14. Print "data dequeued from queue" and return the data.
15. In the main function, call the enqueue() and dequeue() functions as required.
Output:
7.b)Circular Queue:
Code:
#include<stdio.h>
int queue[10];
int front=-1,rear=-1;
int isfull(int size){
if((front==rear+1) || (front==0&&rear==size-1))
return 1;
else
return 0;
}
int isempty(){
if(front==-1){
return 1;
}
else{
return 0;
}
}
void enqueue(int data,int size){
if(isfull(size)){
printf("queue overflow!\n");
}
else{
if(front==-1){
front=0;
}
rear=(rear+1)%size;
queue[rear]=data;
}
}
int dequeue(int size){
if(isempty(size)){
printf("queue is empty\n");
}
else{
int element=queue[front];
if(front==rear){
front=-1;
rear=-1;
}
else{
front=(front+1)%size;
}
return(element);
}
}
void print(int size){
int i;
if(isempty()){
printf("queue is empty\n");
}
else{
printf("front: %d\n",front);
printf("elements:\n");
for(i=front;i!=rear;i=(i+1)%size){
printf("%d\n",queue[i]);
}
printf("%d\n",queue[i]);
printf("rear: %d\n",rear);
}
}
int main(){
int n,d;
printf("enter the size: ");
scanf("%d",&n);
printf("enter the elements\n");
for(int i=0;i<n;i++){
scanf("%d",&d);
enqueue(d,n);
}
print(n);
printf("How many elements u want to pop?\n");
int p;
scanf("%d",&p);
for(int i=0;i<p;i++){
int el=dequeue(n);
printf("Popped element: %d\n",el);
print(n);
}
enqueue(0,n);
print(n);
}
Algorithm:
Here's the algorithm for the given circular queue implementation:
1. Declare a global array 'queue' of size 10 and two integer variables 'front' and 'rear' initialized
to -1.
2. Define a function named 'isfull' that takes the queue size as an input parameter and returns 1 if
the queue is full and 0 if it's not.
3. Inside the 'isfull' function, check if the queue is full by comparing the 'front' and 'rear' pointers.
If the 'front' pointer is equal to 'rear+1' or 'front' is equal to 0 and 'rear' is equal to 'size-1', return
1. Otherwise, return 0.
4. Define a function named 'isempty' that takes no input parameters and returns 1 if the queue is
empty and 0 if it's not.
5. Inside the 'isempty' function, check if the queue is empty by checking if the 'front' pointer is
equal to -1. If it is, return 1. Otherwise, return 0.
6. Define a function named 'enqueue' that takes an integer 'data' and the queue size as input
parameters and returns nothing.
7. Inside the 'enqueue' function, check if the queue is full using the 'isfull' function. If it is, print a
message saying "queue overflow!". Otherwise, if the 'front' pointer is equal to -1, set it to 0.
8. Increment the 'rear' pointer using the formula '(rear+1)%size' to add the new 'data' element to
the rear of the queue.
9. Update the value of the 'queue' array at the 'rear' index to 'data'.
10. Define a function named 'dequeue' that takes the queue size as an input parameter and returns
an integer element.
11. Inside the 'dequeue' function, check if the queue is empty using the 'isempty' function. If it is,
print a message saying "queue is empty". Otherwise, store the element at the 'front' index of the
queue in a variable named 'element'.
12. If the 'front' pointer is equal to the 'rear' pointer, set both 'front' and 'rear' to -1. Otherwise,
increment the 'front' pointer using the formula '(front+1)%size'.
13. Return the 'element' variable.
14. Define a function named 'print' that takes the queue size as an input parameter and returns
nothing.
15. Inside the 'print' function, check if the queue is empty using the 'isempty' function. If it is,
print a message saying "queue is empty". Otherwise, print the value of 'front'.
16. Print all the elements in the queue by iterating from the 'front' pointer to the 'rear' pointer
using the formula '(i+1)%size' until the loop reaches the 'rear' pointer.
17. Print the 'rear' pointer.
18. Inside the 'main' function, prompt the user to enter the queue size and read it using 'scanf'.
19. Prompt the user to enter the queue elements one by one and read them using 'scanf' inside a
for loop that iterates 'n' times.
20. Call the 'print' function to display the initial state of the queue.
21. Prompt the user to enter the number of elements they want to pop and read it using 'scanf'.
22. Call the 'dequeue' function 'p' times inside a for loop that iterates 'p' times. Display the
popped element using 'printf'.
23. Call the 'print' function after each pop to display the updated state
Output:
8.a)Stack Push
Code:
#include <stdio.h>
#define N 100 // setting the capacity globally
int push(int arr[], int top, int maxstk,int item);
int main()
{
int arr[N] = {11,32,22,44,55};
int size = 5; // initailly the size of the array
printf("stk at the beginning: ");
for (int i = 0; i < size; ++i)
{
printf("%d ",arr[i]);
}
// 1st push , adding 66 in the stk
size = push(arr,size,100,66);
// the push function returns the new value of size
printf("\n updated size %d\n",size);
printf("stk after one push:");
for (int i = 0; i < size; ++i)
{
printf("%d ",arr[i]);
}
// 2nd push, adding 67 in the stk
size = push(arr,size,100,67);
printf("\n updated size %d\n",size);
printf("stk after two push: ");
for (int i = 0; i < size; ++i)
{
printf("%d ",arr[i]);
}
// 3rd push, adding 68 in the stk
size = push(arr,size,100,68);
printf("\n updated size %d\n",size);
printf("stk after three push: ");
for (int i = 0; i < size; ++i)
{
printf("%d ",arr[i]);
}
return 0;
}
// the push method takes an array , the index of next top ele
int push(int arr[], int top, int maxstk,int item){
if (top == maxstk) // checks if the stk is full or not
{
printf("\noverflow\n");
return maxstk;
}else{
arr[top] = item; // sets the item to the top
top = top+1; // updates the value of top
return top; // returns the value of top that that it can be use as the new size of the updated stk
}
}
Output:
Algorithm:
Here's the algorithm for the given code:
1. Initialize an integer array arr with the capacity of N (100 in this case) and populate it with
some values.
2. Initialize an integer variable size with the initial size of the array.
3. Print the values in the array using a for loop.
4. Call the push function with the array, size, maximum stack size (100 in this case), and an item
(66) to add it to the top of the stack.
5. Update the size variable with the value returned by the push function.
6. Print the values in the updated array using a for loop.
7. Repeat steps 4-6 with two more items (67 and 68) to add to the top of the stack.
8. Exit the program.
Function push:
1. Takes an integer array arr, integer top, integer maxstk, and integer item as input.
2. Check if the stack is full by comparing top to maxstk. If top == maxstk, print an error message
and return the value of maxstk.
3. If the stack is not full, set the value of arr[top] to the value of the item parameter and
increment the value of top by 1.
4. Return the updated value of top.
Algorithm:
here is an algorithm for the given code:
1. Define a function `pop` that takes an integer array, the current top index and an integer
variable `item` to store the popped value.
2. Inside the `pop` function, check if the current top index is equal to zero. If it is, print
"UnderFlow" and return 0.
3. If the top index is not zero, assign the value at the current top index of the array to the `item`
variable and decrement the value of the top index by 1.
4. Print "Poped" and the value of the `item` variable.
5. Return the updated value of the top index.
6. In the `main` function, initialize an integer array `arr` and set its values.
7. Initialize an integer variable `size` to the size of the array.
8. Print the initial contents of the stack.
9. Call the `pop` function with the integer array, the current value of `size` and the value to be
popped. Store the updated value of `size` in `size`.
10. Print the updated value of `size`.
11. Print the contents of the stack after the first pop.
12. Call the `pop` function again with the updated values of `arr`, `size` and the value to be
popped. Store the updated value of `size` in `size`.
13. Print the updated value of `size`.
14. Print the contents of the stack after the second pop.
15. Call the `pop` function again with the updated values of `arr`, `size` and the value to be
popped. Store the updated value of `size` in `size`.
16. Print the updated value of `size`.
17. Print the contents of the stack after the third pop.
18. End of program.
Output:
9. Tree Implementation
Code:
#include <stdio.h>
#include <math.h>
#include <string.h>
int main() {
int n;
printf("Enter the total number of values: ");
scanf("%d", &n);
long long int p = pow(2, n);
int arr[p+1], parent = 0;
memset(arr, -1, sizeof(arr));
for(int i = 0; i < n; i++) {
if(i == 0) {
printf("Enter value of the root: ");
scanf("%d", &arr[i]);
parent = i;
} else {
char pos[10];
printf("Enter left/right position: ");
scanf("%s", pos);
printf("Enter parent position: ");
scanf("%d", &parent);
if(strcmp(pos, "left") == 0) {
printf("Enter value: ");
scanf("%d", &arr[2*parent-1]);
} else if(strcmp(pos, "right") == 0) {
printf("Enter value: ");
scanf("%d", &arr[2*parent]);
} else {
printf("Invalid position\n");
break;
}
}
}
for(long long int i = 0; i < p + 1; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output:
Algorithm:
1. Start the program
2. Declare integer variables 'n', 'parent' and long long integer variable 'p'
3. Prompt the user to enter the total number of values and store it in 'n'
4. Calculate the value of 'p' as 2 raised to the power of 'n'
5. Declare an integer array 'arr' of size 'p+1'
6. Initialize all the elements of the 'arr' with -1 using memset() function
7. Use a for loop to iterate from 0 to 'n'-1
8. Check if the current iteration index 'i' is 0 or not
a. If 'i' is 0, prompt the user to enter the value of the root and store it in 'arr[0]'
and set 'parent' to 0
b. Else, prompt the user to enter the left/right position and parent position
c. Check if the entered position is 'left'
i. If 'left', prompt the user to enter the value and store it in the '2*parent-1'th index of 'arr'
ii. Else, check if the entered position is 'right'
1. If 'right', prompt the user to enter the value and store it in the '2*parent'th index of 'arr'
2. Else, print 'Invalid position' and break from the loop
d. Update 'parent' to the entered parent position
9. Use a for loop to iterate from 0 to 'p+1'-1
a. Print the value of 'arr[i]'
10. End the program
10.Binary Tree Implementation
Code:
#include <stdio.h>
#include <stdlib.h>
// Define a structure for a node in the tree
struct node {
int key;
struct node* left;
struct node* right;
};
// Define a function to create a new node
struct node* newNode(int key) {
struct node* node = (struct node*)malloc(sizeof(struct node));
node->key = key;
node->left = NULL;
node->right = NULL;
return node;
}
// Define a function to insert a node into the tree
struct node* insert(struct node* node, int key) {
// If the tree is empty, create a new node and return it
if (node == NULL) {
return newNode(key);
}
// If the key is less than the node's key, insert it into the left subtree
if (key < node->key) {
node->left = insert(node->left, key);
}
// If the key is greater than the node's key, insert it into the right subtree
else if (key > node->key) {
node->right = insert(node->right, key);
}
// If the key already exists in the tree, return the same node
return node;
}
// Define a function to search for a node in the tree
struct node* search(struct node* node, int key) {
// If the tree is empty or the key is found at the root, return the root
if (node == NULL || node->key == key) {
return node;
}
// If the key is less than the node's key, search in the left subtree
if (key < node->key) {
return search(node->left, key);
}
// If the key is greater than the node's key, search in the right subtree
else {
return search(node->right, key);
}
}
// Define a function to print the inorder traversal of the tree
void inorderTraversal(struct node* node) {
if (node != NULL) {
inorderTraversal(node->left);
printf("%d ", node->key);
inorderTraversal(node->right);
}
}
Output:
Algorithm:
1. Define a struct for a node in the tree with a key, a left child, and a right child.
2. Define a function to create a new node with a given key.
a. Allocate memory for a new node.
b. Set the node's key to the given key.
c. Set the node's left and right children to NULL.
d. Return the new node.
3. Define a function to insert a new node with a given key into the tree.
a. If the tree is empty, create a new node with the given key and return it.
b. If the key is less than the current node's key, recursively insert it into the left subtree.
c. If the key is greater than the current node's key, recursively insert it into the right subtree.
d. If the key already exists in the tree, return the same node.
4. Define a function to search for a node with a given key in the tree.
a. If the tree is empty or the key is found at the root, return the root.
b. If the key is less than the current node's key, recursively search in the left subtree.
c. If the key is greater than the current node's key, recursively search in the right subtree.
5. Define a function to print the inorder traversal of the tree.
a. If the node is not NULL, recursively print the inorder traversal of the left subtree.
b. Print the node's key.
c. If the node is not NULL, recursively print the inorder traversal of the right subtree.
6. In the main function:
a. Create an empty tree.
b. Prompt the user to input values to be inserted into the tree.
c. Insert each value into the tree using the insert function.
d. Print the inorder traversal of the tree using the inorderTraversal function.
e. Prompt the user to search for a node in the tree.
f. Search for the node using the search function.
g. If the node is found, print its key. If not, print a message indicating it was not found.