Lab 7jo
Lab 7jo
Lab 7jo
Exercise 1:(2m)
Implement a C program to find the sum of elements in a one-dimensional array.
objective:
The objective of this program is to calculate the sum of elements in a one-dimensional array.
*It allows the user to enter the size of the array and then input the elements of the array.
*It calculates the sum of the elements and prints it out.
Algorithm:
Step 1:start
Step 2: Declare variables and the initialise the array
Step 3: Input the size of the array and print a message asking the user to enter the size of the array.
Step 4: Input array elements
Declare an array of size to store user-defined values.
Step 5: Calculate the sum of array elements
Step 6: print the sum
Step 7:stop
code:
#include<stdio.h>
int main()
{
int arr[100], size, i, sum = 0;
printf("Enter array size\n");
scanf("%d",&size);
printf("Enter array elements\n");
for(i = 0; i < size; i++)
scanf("%d",&arr[i]);
for(i = 0; i < size; i++)
sum = sum + arr[i];
printf("Sum of the array = %d\n",sum);
return 0;
}
Output:
Exercise 2:(2m)
Write a C program to multiply two matrices using arrays.
objective: The objective of this program is to multiply two matrices A and B of dimensions specified by the
user, and print the resulting matrix C.
*It prompts the user to input the dimensions and elements of matrices A and B, performs matrix
multiplication, and displays the result.
Algorithm:
Step 1:start
Step 2: Declare variables for matrix dimensions, matrix A, matrix B, and matrix C.
Step 3. Input the number of rows and columns for matrices A and B.
Step 4. Input the values for matrix A and matrix B.
Step 5. Perform matrix multiplication and store the result in matrix C.
Step 6. print the resulting matrix
code:
#include<stdio.h>
int main() {
int m, n, i, j;
printf("Enter the number of rows and columns: "); scanf("%d
%d", &m, &n);
int a[m][n], b[m][n], c[m][n];
printf("Enter the values of matrix A:\
n");
for(i = 0; i < m; i++)
{ for(j = 0; j < n; j++)
{
printf("Enter the element [%d,%d]: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
}
printf("Enter the values of matrix B:\n");
for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) {
printf("Enter the element [%d,%d]: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}
}
for(i = 0; i < m; i++) {
for(j = 0; j < n; j++) { c[i]
[j]=0;
for(int k = 0; k < n; ++k) { c[i]
[j] += (a[i][k] * b[k][j]);
}
printf("%d\t",c[i][j]);
}
printf("\n");
}
return 0;}
Output:
Exercise 3:(2m)
Implement a C program to find the largest element in a one-dimensional array.
objective: The objective of the provided C program is to find the largest element in a one-dimensional
array.
*It prompts the user to input the size of the array and its elements, and then it iterates through the array to
determine the largest element.
*It displays the largest element found.
Algorithm:
Step 1:start
Step 2. Declare variables for the array, its size, and a variable to store the largest element.
Step 3. Input the size of the array and the array elements.
Step 4. Initialize a variable `big` to the first element of the array.
Step 5. Iterate through the array to find the largest element.
Step 6. Print the largest element found.
Step 7.stop
code:
#include <stdio.h>
int main() {
int arr[100], size, i,big;
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("Enter %d integers:\n", size);
for (i = 0; i < size; i++)
{ scanf("%d", &arr[i]);
}
big = arr[0];
for (i = 1; i < size; i++) {
if (arr[i] > big) {
big = arr[i];}
}
printf("The largest element in the array is: %d\n", big)
return 0;
}
Output:
Exercise 4:(2m)
Write a C program to sort elements in an array using bubble sort.
objective: The objective of the provided code is to implement the bubble sort algorithm to sort elements in
an integer array in ascending order.
*The program allows the user to input values for the array elements, performs the sorting process using
nested loops, and finally prints the sorted array.
Algorithm:
Step 1:start
Step 2. Initialize an integer array arr of size 5 and a variable n to 4.
Step 3. Input values for the array elements.
Step 4. Implement a bubble sort algorithm to sort the array in ascending order.
Step 5. Print the sorted array.
Step 6. End.
code:
#include<stdio.h>
int main()
{
int temp,j,arr[5];
printf(“enter the value of
n”); scanf(“%d”,&n);
for(int i=0;i<n;i++)
{
printf("Enter the value of arr[%d]:",i);
scanf("%d",&arr[i]);
}
for(int i=1;i<n;i++)
{
for(int j=0;j<n-i;j++)
{
if(arr[j] > arr[j+1])
{int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}printf("Sorted array is: \n");
for(int i=0;i<n;i++)
{
printf("%d ",arr[i]);
}
return 0;}
Output:
Exercise 5:(2m)
Explain the concept of Big-O notation and analyze the time complexity of your sorting algorithm.
objective:
*The objective is to analyze the time complexity of the Bubble Sort algorithm. This analysis involves
understanding how the number of comparisons and swaps scale with the input size `n`.
*In the worst-case scenario, Bubble Sort requires `(O(n^2))` comparisons and swaps. This analysis
disregards constant factors and lower-order terms, focusing solely on the dominant term `n^2` to express the
time complexity.
Answer: Asymptotic notation is the mathematical way of representing the Time
complexity. For a given function f(n) , we denote by O(g(n)) the set of functions
We use O-notation to give an asymptotic upper bound of a function, to within a constant factor
f (n) : there exist positive constants c and n0 s.t.
O(g(n))
0 f (n) cg (n) for all n n 0
Big-O notation is a mathematical notation used in computer science to describe the upper bound of the time
or space complexity of an algorithm
*In Big-O notation, we express the time complexity of an algorithm as a function of the input size `n`,
ignoring constant factors and lower order terms.
The sorting algorith is Bubble sort .
To analyze the time complexity of bubble sort:
- In the worst-case scenario, bubble sort would require (O(n^2)) comparisons and swaps, where (n) is
the number of elements in the array.
- In each pass, it compares adjacent elements and possibly swaps them if they are out of order. For an array
of size (n), it takes (n-1) comparisons in the first pass, (n-2) comparisons in the second pass, and so on until
the last pass where it takes only one comparison.
- Therefore, the total number of comparisons in the worst case can be approximated by the sum of the
first (n-1) positive integers, which is n(n-1)/2 leading to (O(n^2)) comparisons.
- Since each comparison and swap operation is constant time, the time complexity of bubble sort is (O(n^2)).
Graph:
Explanation:
• O(n) means the execution time grows linearly with the input size (number of elements n).
• As n increases, the number of loop iterations increases proportionally, impacting execution time.
Conclusion: This is the concept of big-O notation and time complexity.
Exercise 1:(3m)
Implement a C program to dynamically resize an array to accommodate additional elements.
objective:
Below is a C program that demonstrates dynamically resizing an array to accommodate additional elements.
* This program starts with a fixed-size array and then dynamically resizes it when additional elements need
to be added.
Algorithm:
Step 1:start
Step 2. Declare necessary variables for array, size, and additional elements.
Step 3. Allocate memory dynamically for the initial array using `malloc`.
Step 4. Input values for the initial array.
Step 5. Prompt the user for the number of additional elements and resize the array using `realloc`.
Step 6. Input values for the additional elements and print the resized array.
Step 7.stop
code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* dynamicarray;
int initialsize, newsize;
printf("Enter the number of elements in the initial array: ");
scanf("%d", &initialsize);
dynamicarray = (int*)malloc(initialsize * sizeof(int));
if (dynamicarray == NULL) {
printf("Memory allocation failed.\n");
return 0;
}
for (int i = 0; i < initialsize; i++)
{ scanf("%d", &dynamicarray[i]);
}
printf("Enter the new size for the array: ");
scanf("%d", &newsize);
dynamicarray = (int*)realloc(newsize * sizeof(int));
if (dynamicarray == NULL) {
printf("Memory reallocation failed.\n");
return 1;
}
for(int i = initialsize; i < newsize; i++)
{ scanf("%d", &dynamicarray[i]);
}
printf("Elements of the resized array are:\n");
for (int i = 0; i < newsize; i++) {
printf("%d\n", dynamicarray[i]);
}
return 0;
}
Output:
Conclusion:Hence the code is verified and executed successfully.
Exercise 2:(3m)
Write a C program to implement a stack using a dynamic array.
Ans) objective: The objective of the provided code is to implement basic stack operations (push, pop,
display) using an array-based approach.
*The program allows the user to interactively perform these operations on a stack with a maximum size
specified at the beginning of the execution.
* The user can push elements onto the stack, pop elements from the stack, display the current contents of the
stack, and exit the program.
Algorithm:
Step 1:start
Start 2. Define the stack data structure and its operations.
Step 3. Implement the push operation to add elements to the stack.
Step 4. Implement the pop operation to remove elements from the stack.
Step 5. Implement the display operation to show the elements of the stack.
Step 6. Implement the main function to interact with the user and perform stack operations based on user
input.
Step 7.stop
code:
#include <stdio.h>
#include <stdlib.h>
int *stack;
int top = -1;
int size;
void push();
void pop();
void
display();
int main() {
int option;
if (stack == NULL) {
printf("Memory allocation failed. Exiting program.\n");
return -1;
}
printf("Stack implementation. Press 1 to continue.\n");
while (1) {
printf("Choose option: 1) Push 2) Pop 3) Display 4) Exit\n");
scanf("%d", &option);
switch (option) {
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
free(stack); return
0; default:
printf("Invalid option. Please try again.\n");
}
}
}
void push() {
if (top == size - 1)
printf("Stack is full!\n");
else {
int value;
printf("Enter the value: ");
scanf("%d", &value);
top++;
stack[top] = value;
printf("Value is pushed successfully.\n");
}
}
void pop() {
if (top == -1)
printf("Stack is empty!\n");
else {
top--;
printf("Value is popped successfully.\n");
}
}
void display()
{ if (top ==
-1)
printf("Stack is empty!\n");
else {
printf("Stack contents:\n");
for (int i = 0; i <= top; i++)
{
printf("%d ", stack[i]);
}
}
printf("\n");
}
}
Output:
:
Conclusion: Hence the code verified and executed successfully
Exercise 3:(4m)
Implement a C program to reverse elements in an array dynamically.
objective: The objective of the provided C program is to reverse the elements in an array dynamically.
*It dynamically allocates memory for an array of a given size, takes input for the elements of the array from
the user, reverses the elements in the array and prints it.
Algorithm:
Step 1.start
Step 2. Declare necessary variables for array size and dynamic memory allocation.
Step 3. Allocate memory dynamically for the array in the main function.
Step 4. Input values for the array elements.
Step 5. Define a function to reverse the array elements.
Step 6. Call the function to reverse the array and print the reversed array.
Step 7.stop
code:
#include <stdio.h>
#include <stdlib.h>
int main()
{ int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
int *arr = (int *)malloc(size * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 0;
}
printf("Enter %d integers:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
printf("Original array: ");
for (int i = 0; i < size; i++)
{ printf("%d ", arr[i]);
}
printf("\n");
for (int i = 0; i < size / 2; i++) {
int temp = arr[i];
arr[i] = arr[size - i - 1];
arr[size - i - 1] = temp;
}
printf("Reversed array: ");
for (int i = 0; i < size; i++)
{ printf("%d ", arr[i]);
}
printf("\n");
free(arr);
return 0;
}
Output:
Exercise 1:(2m)
Implement a C program to create a singly linked list and display its elements.
Objective:
The objective of the provided C code is to implement a singly linked list data structure.
*It allows users to input elements, display the linked list, and deallocate memory properly to prevent
memory leaks.
Algorithm:
Step 1.start
Step 2. Define a structure to represent a node in a linked list.
Step 3. Implement a function to create a new node.
Step 4. Implement a function to insert a new node at the end of the linked list.
Step 5. Implement a function to display the elements of the linked list.
Step 6. Implement the main function to interact with the user, create a linked list, display its elements, and
free memory.
Step 7.stop
code:
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node* next;
};
int main() {
struct node *temp, *start, *p;
int n, element, i;
printf("Enter the number of nodes in the list: ");
scanf("%d", &n);
temp = (struct node *)malloc(sizeof(struct node));
printf("Enter the value of first node: ");
scanf("%d", &element);
temp->data = element;
temp->next = NULL;
start = temp;
p = temp;
for (i = 2; i <= n; i++) {
temp = (struct node*)malloc(sizeof(struct node));
printf("Enter the value of %d node: ", i);
scanf("%d", &element);
temp->data = element;
temp->next = NULL;
p->next = temp;
p = p->next;
}if (start == NULL)
{ printf("List is empty\
n");
} else {
temp = start;
while (temp != NULL) {
printf("%d----->", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
return 0;
}
Output:
Exercise 2:(2m)
Write a C program to insert an element at the beginning and end of a singly linked list.
Objective:
This code aim is to demonstrate the implementation of a singly linked list. It provides functions to insert
nodes at the beginning and end of the list based on user input.
*The program prompts the user to specify the number of nodes to be inserted at the beginning and end
*it then reads data for each node accordingly. After insertion, it prints the final linked list.
Algorithm:
Step 1:start
Step 2. Define a structure to represent a node in a linked list.
Step 3. Implement a function to create a new node.
Step 4. Implement a function to insert a new node at the beginning of the linked list.
Step 5. Implement a function to insert a new node at the end of the linked list.
Step 6. Implement the main function to interact with the user, insert nodes at the beginning and end, and
print the final list.
Step 7.stop
code:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
int main() {
struct Node* head = NULL;
int n, data;
return 0;
}
Output:
Conclusion:Hence the code is verified and executed successfully
Exercise 3:(4m)
Implement a C program to delete a node from a singly linked list.
Objective:
This code demonstrates the implementation of a singly linked list with functionalities to insert nodes at the
beginning, display the list, and delete a node based on user input. *The program prompts the user to specify
the number of elements and their values to create the initial linked list. It then allows the user to input an
element to be deleted. *After deletion, it prints the updated linked list.
Algorithm:
Step 1.start
Step 2. Define a structure to represent a node in a linked list.
Step 3. Implement a function to insert a new node at the beginning of the linked list.
Step 4. Implement a function to display the elements of the linked list.
Step 5. Implement a function to delete a node with a given value from the linked list.
Step 6. Implement the main function to interact with the user, create a linked list, delete a node, and print the
final list.
Step 7.stop
Code:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
current = head;
prev = NULL;
if (current == NULL) {
printf("Element %d not found in the list.\n", value);
return head;
}
prev->next = current->next;
free(current);
return head;
}
int main() {
struct Node* head = NULL;
int n, value;
return 0;
}
Output:
Exercise 4:(4m)
Write a C program to reverse a singly linked list.
Objective:
This code aims to demonstrate the implementation of a singly linked list with functionalities to insert
nodes at the beginning, display the list, and reverse the order of elements.
* The program prompts the user to specify the number of elements and their values to create the
initial linked list.
* After displaying the initial list, it reverses the order of elements and prints the reversed list.
Algorithm:
Step 1.start
Step 2. Define a structure to represent a node in a linked list.
Step 3. Implement a function to insert a new node at the beginning of the linked list.
Step 4. Implement a function to display the elements of the linked list.
Step 5. Implement a function to reverse the linked list.
Step 6. Implement the main function to interact with the user, create a linked list, reverse it, and print the
final list.
Step 7.stop
Code:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
return prev;
}
int main() {
struct Node* head = NULL;
int n, value;
return 0;
}
Output:
Exercise 1:(2m)
Implement a C program to create a doubly linked list and display its elements.
Objective:
The objective of this code is to implement a doubly linked list data structure.
*It provides functionality to insert nodes at the end of the list based on user input and display the elements of
the doubly linked list.
*The program prompts the user to specify the number of elements and their values to create the doubly
linked list.
*After creating the list, it displays the elements in order.
Algorithm:
Step 1.start
Step 2. Define a structure to represent a node in a doubly linked list.
Step 3. Implement a function to insert a new node at the end of the doubly linked list.
Step 4. Implement a function to display the elements of the doubly linked list.
Step 5. Implement the main function to interact with the user, create a doubly linked list by inserting nodes
at the end, and print the final list.
Step 6.stop
Code:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
if (head == NULL)
{ newNode->prev =
NULL; return newNode;
}
temp->next = newNode;
newNode->prev = temp;
return head;
}
return 0;
}
Output:
Exercise 2:(2m)
Write a C program to insert an element at the beginning and end of a doubly linked list.
Objective:
This code aims to demonstrate the implementation of a doubly linked list.
*It provides functions to insert nodes at the beginning and end of the list based on user input.
*After insertion, it prints the final doubly linked list.
Algorithm:
Step 1.start
Step 2. Define a structure to represent a node in a doubly linked list.
Step 3. Implement a function to create a new node with the given data.
Step 4. Implement a function to insert a new node at the beginning of the doubly linked list.
Step 5. Implement a function to insert a new node at the end of the doubly linked list.
Step 6. Implement the main function to interact with the user, create a doubly linked list by inserting nodes
at the beginning and end, and print the final list.
Step 7.stop
Code:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
int main() {
struct Node* head = NULL;
int n, data;
return 0;
}
Output:
Exercise 3:(4m)
Implement a C program to delete a node from a doubly linked list.
Objective:
The objective of this code is to demonstrate the implementation of a doubly linked list .
*with functions to insert nodes at the beginning and delete a specific node based on user input.
* After deletion, it prints the updated doubly linked list.
Algorithm:
Step 1.start
Step 2. Define a structure to represent a node in a doubly linked list.
Step 3. Implement a function to insert a new node at the beginning of the doubly linked list.
Step 4. Implement a function to display the elements of the doubly linked list.
Step 5. Implement a function to delete a node with a given value from the doubly linked list.
Step 6. Implement the main function to interact with the user, create a doubly linked list by inserting nodes
at the beginning, delete a node with a given value, and print the final list.
Step 7.stop
Code:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
if (head != NULL) {
head->prev = newNode;
}
return newNode;
}
current = head;
prev = NULL;
if (current == NULL) {
printf("Element %d not found in the list.\n", value);
return head;
}
if (prev != NULL) {
prev->next = current->next;
if (current->next != NULL)
{
current->next->prev = prev;
}
} else {
head = current->next;
if (current->next != NULL)
{ current->next->prev =
NULL;
}
}
free(current);
return head;
}
int main() {
struct Node* head = NULL;
int n, value;
return 0;
}
Output:
Exercise 4:(4m)
Write a C program to reverse a doubly linked list.
Ans)
Objective:
*The objective of this C code is to demonstrate the implementation of a doubly linked list with
functionalities to insert nodes at the end and reverse the order of elements.
*After creating the list, it reverses the order of elements and prints the reversed doubly linked list.
Algorithm:
Step 1.start
Step 2. Define a structure to represent a node in a doubly linked list.
Step 3. Implement a function to insert a new node at the end of the doubly linked list.
Step 4. Implement a function to display the elements of the doubly linked list.
Step 5. Implement a function to reverse the doubly linked list.
Step 6. Implement the main function to interact with the user, create a doubly linked list by inserting nodes
at the end, reverse the list, and print the final list.
Step 7.stop
code:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
if (head == NULL)
{ newNode->prev =
NULL; return newNode;
}
temp->next = newNode;
newNode->prev = temp;
return head;
}
if (temp != NULL)
{ head = temp-
>prev;
}
return head;
}
int main() {
struct Node* head = NULL;
int n, value;
head = reverseList(head);
return 0;
}
Output:
Exercise 1:(2m)
Implement a C program to create a circular linked list and display its elements.
Ans)
Objective:
The objective of this code is to implement a circular linked list.
* Allows the user to input the number of elements in the circular linked list and the data for each element.
* Inserts each element at the end of the circular linked list.
* Displays the circular linked list once all elements have been inserted.
Algorithm:
Step 1.start
Step 2. Define a structure for the node of the circular linked list.
Step 3. Implement a function `insertEnd()` to insert a new node at the end of the circular linked list.
Step 4. Implement a function displayList() to display the elements of the circular linked list.
Step 5. Declare a variable last to represent the last node of the circular linked list and initialize it to NULL.
Step 6. Return 0 to indicate successful execution.
Step 7.stop
code:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* insertEnd(struct Node* last, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
if (last == NULL) {
newNode->next = newNode;
last = newNode;
} else {
newNode->next = last->next;
last->next = newNode;
last = newNode;
}
return last;
}
void displayList(struct Node* last) {
if (last == NULL) {
printf("List is empty.\n");
return;
}
do
{ printf("%d ", temp->data);
temp = temp->next;
} while (temp != last->next); // Stop when we reach the first node
again
printf("\n");
}
int main() {
struct Node* last = NULL;
int n, data;
return 0;
}
Output:
Exercise 2:(2m)
Write a C program to insert an element at the beginning and end of a circular linked list.
Ans) objective:
The objective of this code is to implement operations on a circular linked list. Specifically, the code aims to:
* Allow the user to create a circular linked list by inserting elements at the end.
* Implement a function to insert a new element at the beginning of the circular linked list.
Algorithm:
Step 1.start
Step 2. Define a structure named Node with two fields
Step 3. Implement a function insertBeginning() to insert a new node at the beginning of the circular linked
list.
Step 4. Implement a function `insertEnd()` to insert a new node at the end of the circular linked list.
Step 5. Implement a function `displayList()` to display the elements of the circular linked list. This function
takes the last node of the list last as a parameter.
Step 5 - Declare prompt and print a variable `last` to represent the last node of the circular linked list and
initialize it to `NULL`.
Step 6. End
code:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* insertBeginning(struct Node* last, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
if (last == NULL) {
newNode->next = newNode;
last = newNode;
} else {
newNode->next = last->next;
last->next = newNode;
}
return last;
}
struct Node* insertEnd(struct Node* last, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
if (last == NULL) {
newNode->next = newNode;
last = newNode;
} else {
newNode->next = last->next;
last->next = newNode;
last = newNode;
}
return last;
}
void displayList(struct Node* last) {
if (last == NULL) {
printf("List is empty.\n");
return;
}
do
{ printf("%d ", temp->data);
temp = temp->next;
} while (temp != last->next);
printf("\n");
}
int main() {
struct Node* last = NULL;
int n, data;
return 0;
}
Output:
Exercise 3:(4m)
Implement a C program to delete a node from a circular linked list.
objective:
The objective of this code is to implement operations on a circular linked list.
* It allows the user to create a circular linked list by inserting elements at the end.
* It enables the user to delete a node with a given key from the circular linked list.
Algorithm:
step 1.start
step 2. Define a structure to represent each node in the circular linked list. It contains two fields
step 3. Implement a function `insertEnd` to insert a new node at the end of the circular linked list..
step 4. Then it takes the last node of the list last and the key to be deleted key and traverses the list to find
the node with the specified key,.
Step 5. Implement a function displayList to display the elements of the circular linked list. This function
takes the last node of the list last as a parameter.
Step 6: Print the circular linked list again after deletion.
Step 7.end
code:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* insertEnd(struct Node* last, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
if (last == NULL) {
newNode->next = newNode;
last = newNode;
} else {
newNode->next = last->next;
last->next = newNode;
last = newNode;
}
return last;
}
struct Node* deleteNode(struct Node* last, int key) {
if (last == NULL) {
printf("List is empty. Cannot delete.\n");
return last;
}
free(current);
}
do
{ printf("%d ", temp->data);
temp = temp->next;
} while (temp != last->next);
printf("\n");
}
int main() {
struct Node* last = NULL;
int n, data, key;
return 0;
}
Output
Conclusion:Hence the code is verified and executed successfully
Exercise 4:(4m)
Write a C program to reverse a circular linked list.
Objective:
The objective of this code is to create and manipulate a circular linked list.
* Allow the user to create a circular linked list by inputting data for each node.
* Implement a function to reverse the circular linked list.
Algorithm:
Step 1:start
Step 2. Declare variables head, newnode, temp, and tail of type struct node*.
*Traverse the circular linked list starting from head until reaching tail.
Step 3. Declare variables pre, current, and nextnode of type struct node*.
Step 4. Call the create_list() function to create the circular linked list.
Step 5. end
code:
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *head,*newnode,*temp,*tail;
void create_list(){
head=0;
int choice =1;
while(choice){
newnode=(struct node*)malloc(sizeof(struct node));
printf("Enter the data:");
scanf("%d",&newnode->data);
if(head==0){
head=temp=newnode;
}
else{
temp->next=newnode;
temp=newnode;
}
printf("Enter 1 to continue:");
scanf("%d",&choice);
}
tail=temp;
temp->next=head;
}
void display_list(){
temp=head;
while(temp->next!=head)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("%d",temp->data);
}
void reverse(){
current=head;
nextnode=current->next;
while(current!=tail)
{ pre=current;
current=nextnode;
nextnode=current->next;
current->next=pre;
}
head=tail;
nextnode->next=tail;
tail=nextnode;
}
int main()
{
create_list();
reverse();
display_list();
return 0;
}
Output:
Exercise-1(3M):
1. Implement a C program to evaluate a postfix expression using a stack.
Objective:
To evaluate postfix expression using stack operation.
Algorithm:
Step-1:Start.
Step-2:Initialize an empty stack to store operands.
Step-3:Read the postfix expression character by character.
Step-4:If the character is a digit (operand), convert it to an integer and push it onto the stack.
Step-5:If the character is an operator (+, -, *, /, %), pop the top two elements from the stack (let’s call them
op2 and op1).
Step-6:Perform the operation corresponding to the operator:
For addition: push(op1 + op2)
For subtraction: push(op1 - op2)
For multiplication: push(op1 * op2)
For division: push(op1 / op2)
For modulo: push(op1 % op2)
Step-7:Continue this process until you have processed all characters in the
expression. Step-8:The final result will be the top element of the stack.
Step-9:Print the result.
Step-10:Stop.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include<string.h>
#define max 100
int stack[max];
int top = -1;
void push(int i)
{
if (top == max - 1)
{ printf("STACK OVEFLOW!\n");
exit(1);
}
stack[++top] = i;
}
int pop() {
if (top == -1) {
printf("STACK UNDERFLOW!\n");
exit(1); }
return
stack[top--];
}
1|Page
2|Page
void eval(char* exp) {
for (int i = 0; exp[i]; ++i) {
if (isdigit(exp[i]))
push(exp[i] - '0'); // Convert char to int
else {
int op2 = pop();
int op1 = pop();
switch (exp[i])
{
case '+': push(op1 + op2);
break; case '-': push(op1 -
op2); break; case '*': push(op1
* op2); break; case '/':
push(op1 / op2); break; case
'%': push(op1 % op2); break;
}
}
}
printf("\n%d\n",pop());
}
int main() {
char exp[max];
printf("--POSTFIX EXPRESSION--\n");
gets(exp);
eval(exp);
return 0;
}
Output:
3|Page
4|Page
Exercise-2(3M):
2. Write a C program to reverse a string using a stack.
Objective:
To revrese a string using stack operations.
Algorithm:
Step-1:Start
Step-2:Initialize an empty
stack. Step-3:Read the input
string.
Step-4:Push each character of the string onto the stack.
Step-5:Pop characters from the stack and store them back in the string, starting from the 0th
index. Step-6:The resulting string will be the reversed version of the original string.
Step-7:Stop
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 100
int top = -1;
char
stack[MAX];
void push(char item) {
if (top == MAX - 1) {
printf("STACK OVERFLOW\n");exit(1);}
else {
stack[++top] = item;}
}
char pop() {
if (top == -1) {
printf("STACK UNDERFLOW\n");exit(1);
} else {
return stack[top--];}
}
int main() {
char str[MAX];
unsigned int
i;
printf("--STRING--\n");
gets(str);// Push characters of the string onto the stack
for (i = 0; i < strlen(str); i++) {
push(str[i]);
}// Pop characters from the stack and store in the string
for (i = 0; i < strlen(str); i++) {
str[i] = pop();}
printf("--REVERSED STRING--\n%s\n", str);
return 0;}
Output:
5|Page
Conclusion: Hence this program is executed successfully.
6|Page
Exercise-3(4M):
3. Implement a C program to check for balanced parentheses using a stack.
Objective:
To check for balanced parentheses using a stack.
Algorithm:
Step-1:Start.
Step-2:Initialize an empty stack.
Step-3:Read the input expression containing
parentheses. Step-4:For each character in the expression:
If it is an opening parenthesis (‘(’, ‘{’, or ‘[’), push it onto the stack.
If it is a closing parenthesis (‘)’, ‘}’, or ‘]’):
If the stack is empty, report that the expression is unbalanced.
Otherwise, pop the top element from the stack.
If the popped element does not match the current closing parenthesis, report that the expression is
unbalanced.
Step-5:After processing all characters, if the stack is empty, the expression is balanced; otherwise, it is
unbalanced.
Step-6:Stop.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 30
char pop() {
if (top == -1) {
printf("STACK UNDERFLOW \n");
exit(1);
} else {
return stack[top--];
}
}
7|Page
8|Page
int match(char a, char b) {
if ((a == '(' && b == ')') || (a == '{' && b == '}') || (a == '[' &&
b == ']'))
return 1;
return 0;
}
9|Page
Output:
Prepared by:
Name: Chandra johith
Reg. No.: AV.SC.U4AIE23104
Date of Experiment:
Date of Submission:
Submission Delay:
Marks Obtained (10):
10 | P a g
e
11 | P a g
e
12 | P a g
e
Lab 7: Queue
Implementation Exercise-
1(3M):
1. Implement a C program to implement a queue using arrays.
Objective:
To implement Queue using an Array.
Algorithm:
Step-1: Start
Step-2: Define a maximum size (MAX_SIZE) for the queue.
Step-3: Initialize an array (queue) to store the elements of the queue.
Step-4:Initialize two variables, front and rear, to keep track of the front and rear indices of the queue,
respectively. Set both front and rear to -1 initially, indicating an empty queue.
Step-5:Enqueue Function
1. Check if the queue is full (rear == MAX_SIZE -
1). If the queue is full, print an error message.
2. Check if the queue is empty (front == -1 && rear == -1).
If the queue is empty, set both front and rear to 0, and insert the new element at index 0 of the queue.
3. If the queue is not empty, increment the rear index and insert the new element at the new rear index.
Step-6:Dequeue Function
1. Check if the queue is empty (front == -1 && rear == -
1). If the queue is empty, print an error message.
2. Check if there is only one element in the queue (front == rear).
If there is only one element, remove it by setting both front and rear to -1.
3. If the queue has multiple elements, increment the front index and print the dequeued element.
Step-7:Display Function
1. Check if the queue is empty (front == -1 && rear == -1).
If the queue is empty, print a message indicating that the queue is empty.
2. If the queue is not empty, print all the elements of the queue by traversing from the front index to the
rear index.
Step-8:Size Operation:
1. Check if the queue is empty (front == -1 && rear == -
1). If the queue is empty, print the size as 0.
2. If the queue is not empty, print the size as (rear + 1).
Step-9:Main Function:
1. Initialize a loop to display a menu for performing queue operations.
2. Prompt the user to enter their choice of operation.
3. Based on the user's choice, perform the corresponding function(enqueue, dequeue, display, or size).
4. If the user chooses to exit, break out of the loop and terminate the program.
5. If an invalid choice is entered, print an error message.
Step-10:Stop
Code:
#include <stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#define MAX_SIZE 100
int queue[MAX_SIZE];
1|Page
int front = -1, rear = -1;
2|Page
void enqueue(int x) {
if (rear == MAX_SIZE - 1)
{ printf("Error: Queue is full\
n");
} else if (front == -1 && rear == -1)
{ front = rear = 0;
queue[rear] = x;
} else {
rear++;
queue[rear] = x;}
}
void display() {
if (front == -1 && rear == -1)
{ printf("Queue is empty\n");
} else {
printf("Queue elements are: ");
for (int i = front; i <= rear; i++) {
printf("%d ", queue[i]);}
printf("\n");}
}
void dequeue() {
int removedValue = queue[front];
if (front==-1 && rear==-1) {
printf("QUEUE IS EMPTY CANNOT DEQUEUE!\n");}
else if(front == rear)
{ front = rear = -1;}
else {
front++;
printf("\n%d DEQUEUED SUCCESSFULLY!\n", removedValue);}
}
int main() {
int choice, value;
while (1) {
printf("\n--QUEUE OPERATIONS:--\n");
printf(" 1.ENQUEUE\n 2.DEQUEUE\n 3.DISPLAY\n 4.SIZE\n
5.EIXT\n");
printf("\n--ENTER YOUR CHOICE:\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("\nENTER VALUE:\n");
scanf("%d", &value);
enqueue(value);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
3|Page
4|Page
if(front==-1 && rear==-1){ printf("\
nSIZE OF QUEUE : 0\n");} else{
printf("\nSIZE OF QUEUE : %d\n",rear);}
break;
case 5:
printf("\nEXITING PROGRAM!\n");
return 0;
default:
printf("\nINVALID CHOICE!\nTRY AGAIN!\n");
}
}
return 0;}
Output:
Exercise-2(3M):
2. Write a C program to implement a circular queue.
Objective:
To implement a circular queue.
Algorithm:
Step-1: Start
Step-2: Prompt the user to enter the maximum size of the queue
Step-3: Dynamically allocate memory for the queue array using malloc
Step-4: Display the menu of queue operations (Enqueue, Dequeue,
Exit) Step-5: Prompt the user to enter their choice
Step-6: If the user's choice is 1 (Enqueue):
Prompt the user to enter the value to enqueue
Call the enqueue function with the user-entered value
If the queue is full:
Print "Queue is full!!!" with a special character
Return
Else:
If the front pointer is -1 (queue is initially empty):
Set the front pointer to 0
Update the rear pointer using the formula: rear = (rear + 1) % max_size
Store the user-entered value at the rear position of the queue
Print "Enqueued: [value]"
Step-7: If the user's choice is 2 (Dequeue):
Call the dequeue function
If the queue is empty:
Print "Queue is empty!!!" with a special character
Return -1
5|Page
Else:
Store the front value of the queue in a variable
If the front and rear pointers are equal (only one element in the queue):
Set both front and rear pointers to -1
Else:
Update the front pointer using the formula: front = (front + 1) % max_size
Return the dequeued value
If the dequeued value is not -1 (empty queue):
Print "Dequeued: [value]"
Step-8: If the user's choice is 3
(Exit): Print "Exiting..."
Step-9:If the user's choice is invalid:
Print "Invalid choice." with a special character
Step-10: Repeat steps 5-9 until the user chooses to exit (choice 3)
Step-11: Free the dynamically allocated memory for the queue
array Step-12:Stop
Code:
#include <stdio.h>
#include <stdlib.h>
int c=30;
int *queue;
int max_size,front=-1,rear=-1;
void dequeue()
{ int value;
if (front==-1&&rear==-1) { printf("\n\n
%cQueue is empty!!!\n",c);}
else if (front == rear) {
printf("Dequeued: %d\n",queue[front]);
front = -1;
rear = -1;
} else {
printf("Dequeued: %d\n",queue[front]);
front = (front + 1) % max_size;}}
void dis(){
int i=front;
6|Page
if (front==-1&&rear==-1) { printf("\n\n
%cQueue is empty!!!\n",c);}
else if(front==0 && rear==0)
{ printf("\n--Queue--\n");
printf("%d\n",queue[front]);}
else{
printf("\n--Queue--\n");
while(i!=rear){
printf("%d\n",queue[i]);
i=(i+1)%max_size;
// alternate if(i==rear){printf("%d\n",queue[i]);}
} printf("%d\n",queue[i]);}}
int main() {
int choice, value;
printf("Enter the maximum size of the circular queue: ");
scanf("%d", &max_size);
queue = (int *)malloc(max_size * sizeof(int));
printf("\nEnter values of circular queue\n");
for(int i=0;i<max_size;i++){
scanf("%d",&value);
enqueue(value);
}
do {
printf("\n--Queue Operations--\n");
printf("1. Enqueue\n2. Dequeue\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the value to enqueue: ");
scanf("%d", &value);
enqueue(value);
break;
case 2:
dequeue();
break;
case 3:
dis();
break;
case 4:
printf("\n\nExiting...\n");
break;
default:
printf("%cInvalid choice!\n",c);
}
} while (choice != 4);
free(queue);
return 0;}
Output:
7|Page
Conclusion: Hence this program is executed successfully.
Exercise-3(4M):
3. Implement a C program to reverse the elements of a queue.
Objective:
To reverse the elements of a queue.
Algorithm:
Step-1: Start.
Step-2:Declare and initialize an array queue with a maximum size of MAX_SIZE (100)
Step-3:Declare and initialize front and rear pointers with -1
Step-4:Define the enqueue function:
If the rear pointer is at the last position of the queue (MAX_SIZE - 1):
Print "QUEUE IS FULL!"
Return
If the front pointer is -1 (queue is initially empty):
Set the front pointer to 0
Increment the rear pointer
Store the value at the rear position of the queue
Step-5:Define the dequeue function:
If the front pointer is -1 (queue is empty):
Print "QUEUE IS EMPTY!"
Return -1
Store the value at the front position of the queue in a variable
If the front and rear pointers are equal (only one element in the queue):
Set both front and rear pointers to -1
Else:
Increment the front pointer
Return the dequeued value
Step-6:Define the reverseQueue function:
Declare a temporary array temp of size MAX_SIZE
Initialize a variable j to 0
While the front pointer is not -1 (queue is not empty):
Dequeue an element from the queue and store it in
temp[j] Increment j
Initialize a variable i with j - 1
Iterate from i to 0 in reverse order:
Enqueue the value from temp[i] into the queue
Step-7:In the main function:
Print a prompt to enter queue elements
Read input values and enqueue them into the queue until -1 is entered
Print the original queue by dequeuing all elements
Reset the front and rear pointers to -1
Print a prompt to enter queue elements again
Read input values and enqueue them into the queue until -1 is entered
8|Page
Call the reverseQueue function to reverse the elements of the queue
Print the reversed queue by dequeuing all elements
Step-8:Stop
Code:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
int queue[MAX_SIZE];
int front = -1, rear = -1;
void enqueue(int value) {
if (rear == MAX_SIZE - 1)
{ printf("QUEUE IS FULL!\n");
return;
}
if (front == -1)
{ front = 0;
}
queue[++rear] = value;
}
int dequeue() {
if (front == -1) {
printf("QUEUE IS EMPTY!\n");
return -1;
}
int value = queue[front];
if (front == rear) {
front = rear = -1;
} else {
front++;
}
return value;
}
void reverseQueue()
{ int
temp[MAX_SIZE]; int
j = 0;
while (front != -1)
{ temp[j++] =
dequeue();
}
for (int i = j - 1; i >= 0; i--) {
enqueue(temp[i]);
}
}
int main() {
int choice, value;
printf("ENTER QUEUE ELEMENTS(enter -1 to stop):\n");
while (1) {
scanf("%d", &value);
if (value == -1)
9|Page
break;
enqueue(value);
10 | P a g
e
}
printf("\nORIGINAL QUEUE: ");
while (front != -1)
{ printf("%d ",
dequeue());
}
// Reset front and rear
front = rear = -1;
printf("\nENTER QUEUE ELEMENTS AGAIN(enter -1 to stop):\n");
while (1) {
scanf("%d", &value);
if (value == -1)
break;
enqueue(value);
}
reverseQueue(); printf("\
nREVERSED QUEUE: ");
while (front != -1)
{ printf("%d ",
dequeue());
}
return 0;}
Output:
Prepared by:
Name: Chandra johith
Reg. No.: AV.SC.U4AIE23104
Date of Experiment:
Date of Submission:
Submission Delay:
Marks Obtained (10):
11 | P a g
e
12 | P a g
e
13 | P a g
14 | P a g
15 | P a g