0% found this document useful (0 votes)
4 views41 pages

Assignment 15 To 24 Dsa

The document outlines several programming assignments in C, including implementations of stack, GCD calculation, Fibonacci series, circular queue using arrays, and circular queue using linked lists. Each assignment includes a problem statement, algorithm steps, and source code. The assignments focus on fundamental data structures and recursion techniques.

Uploaded by

kaustavdey71
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views41 pages

Assignment 15 To 24 Dsa

The document outlines several programming assignments in C, including implementations of stack, GCD calculation, Fibonacci series, circular queue using arrays, and circular queue using linked lists. Each assignment includes a problem statement, algorithm steps, and source code. The assignments focus on fundamental data structures and recursion techniques.

Uploaded by

kaustavdey71
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

ASSIGNMENT 12

PROBLEM: Implement push and pop operations in Stack using array.


ALGORITHM:
Step 1: Initialize the Stack
1. Define a constant `MAX` for the maximum size of the stack.
2. Declare an array `stack[MAX]` to store the elements.
3. Initialize a variable `top` to `-1`, which represents an empty stack.
Step 2: Algorithm for Push Operation
1. Input the element to be pushed into the stack (`value`).
2. Check if the stack is full:
- If `top == MAX - 1`, display "Stack Overflow" and terminate the operation.
3. If the stack is not full:
- Increment the `top` pointer (`top = top + 1`).
- Assign the value to `stack[top]`.
4. Display a success message indicating the value has been pushed.
Step 3: Algorithm for Pop Operation
1. Check if the stack is empty:
- If `top == -1`, display "Stack Underflow" and terminate the operation.
2. If the stack is not empty:
- Retrieve the value at `stack[top]` for display purposes.
- Decrement the `top` pointer (`top = top - 1`).
3. Display a success message indicating the value that was popped.
Step 4: Menu and User Input Handling
1. Display a menu with options:
- Option 1: Push
- Option 2: Pop
- Option 3: Exit
2. Input the user’s choice.
3. Perform the operation based on the choice:
- If the choice is `1`, call the Push operation.
- If the choice is `2`, call the Pop operation.
- If the choice is `3`, display "Exiting" and terminate the program.
- For invalid inputs, display "Invalid choice" and prompt the user again.
Step 5: Repeat Until Exit
1. The program continues to display the menu and perform operations until the user chooses to
exit SOURCE CODE:
#include <stdio.h>
#define MAX 100 // Define the maximum size of the stack
int stack[MAX];
int top = -1; // Initialize stack top as -1 (empty stack)
// Function to push an element onto the stack
void push(int value) {
if (top == MAX - 1) {
printf("Stack Overflow! Cannot push %d\n", value);
} else {
top++;
stack[top] = value;
printf("%d pushed to the stack\n", value);
}
}
// Function to pop an element from the stack
void pop() {
if (top == -1) {
printf("Stack Underflow! No elements to pop\n");
} else {
printf("%d popped from the stack\n", stack[top]);
top--;
}
}
//Test the push and pop operations
int main() {
int choice, value;
while (1) {
printf("\nStack Operations:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to push: ");
scanf("%d", &value);
push(value);
break;
case 2:
pop();
break;
case 3:
printf("Exiting...\n");
return 0;
default:
printf("Invalid choice! Please try again\n");
}
}
}

OUTPUT:
ASSIGNMENT 13
PROBLEM : Write a program in C to find the GCD of the numbers using recursion.
ALGORITHM:
1.Start
2. Input two positive integers, `num1` and `num2`.
3. Call the recursive function `gcd(a, b)`:
Base Case: If `b == 0`, return `a` (the GCD is found).
Recursive Case: If `b != 0`, call the function again with `gcd(b, a % b)`.
4. The recursive calls continue until `b` becomes 0.
5. Return the value of `a` as the GCD
6. Display the GCD result.
7. Stop

SOURCE CODE:
#include <stdio.h>
// Function to calculate the GCD using recursion
int gcd(int a, int b) {
if (b == 0) // Base case: if the second number is 0, return the first number
return a;
return gcd(b, a % b); // Recursive call: gcd(b, a % b)
}
int main() {
int num1, num2;
// Prompt the user to input two numbers
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
// Call the gcd function and display the result
printf("GCD of %d and %d is: %d\n", num1, num2, gcd(num1, num2));
return 0;
}
OUTPUT:

ASSIGNMENT 14
PROBLEM: Write a program in C to find the Fibonacci series using recursion give the size of the series
as user input.
ALGORITHM:
1. Start.
2. Input `n`, the size of the Fibonacci series, from the user.
3. Check for valid input:
- If `n <= 0`, display a message: "The size must be greater than 0" and terminate the program.
4. Define the recursive function `fibonacci(n)`:
- Base Case:
- If `n == 0`, return `0`.
- If `n == 1`, return `1`.
- Recursive Case:
- Return `fibonacci(n - 1) + fibonacci(n - 2)`.
5. Generate the Fibonacci series:
- Use a loop from `i = 0` to `i < n`:
- Call the `fibonacci(i)` function to compute the `i`-th Fibonacci number.
- Print the result.
6. End.
SOURCE CODE:
#include <stdio.h>
// Recursive function to calculate the nth Fibonacci number
int fibonacci(int n) {
if (n == 0)
return 0; // Base case: 0th Fibonacci number is 0
if (n == 1)
return 1; // Base case: 1st Fibonacci number is 1
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive call
}

int main() {
int n;
// Input the size of the Fibonacci series
printf("Enter the size of the Fibonacci series: ");
scanf("%d", &n);
if (n <= 0) {
printf("The size must be greater than 0.\n");
return 0;
}
// Display the Fibonacci series
printf("Fibonacci series up to %d terms:\n", n);
for (int i = 0; i < n; i++) {
printf("%d ", fibonacci(i)); // Call the recursive function
}
printf("\n");
return 0;
}
OUTPUT:
ASSIGNMENT 18
PROBLEM: Write a c program to show the operations of a circular queue implemented as an array.
ALGORITHM:
1. Initialization
1. Define constants:
- `MAX`: Maximum size of the circular queue.
2. Declare the variables:
- `queue[MAX]`: Array to store queue elements.
- `front` and `rear` are set to `-1` initially, representing an empty queue.
2. Enqueue Operation
1. Input the element to be inserted (`value`).
2. Check if the queue is full:
- If `(front == 0 && rear == MAX - 1)` OR `(front == rear + 1)`, display "Queue Overflow" and
terminate the operation.
3. If the queue is not full:
- If the queue is empty (`front == -1`):
- Set `front = 0` and `rear = 0`.
- Else if `rear == MAX - 1` (last position of the array), wrap around:
- Set `rear = 0`.
- Otherwise, increment `rear` by `1` (`rear = rear + 1`).
- Insert the element at `queue[rear]`.
4. Display a success message indicating the element was enqueued.
3. Dequeue Operation
1. Check if the queue is empty:
- If `front == -1`, display "Queue Underflow" and terminate the operation.
2. If the queue is not empty:
- Retrieve the element at `queue[front]` for display.
- If `front == rear` (only one element in the queue):
- Set `front = -1` and `rear = -1` (queue becomes empty).
- Else if `front == MAX - 1` (last position of the array), wrap around:
- Set `front = 0`.
- Otherwise, increment `front` by `1` (`front = front + 1`).
3. Display a success message indicating the element that was dequeued
4. Display Operation
1. Check if the queue is empty:
- If `front == -1`, display "Queue is empty."
2. If the queue is not empty:
- If `rear >= front` (no wrapping):
- Traverse from `front` to `rear` and display the elements.
- If `rear < front` (wrapping occurred):
- Traverse from `front` to `MAX - 1` and display the elements.
- Traverse from `0` to `rear` and display the elements.
5. Main Program (Menu-Driven)
1. Repeat the following steps until the user chooses to exit:
- Display the menu:
1. Enqueue
2. Dequeue
3. Display
4. Exit
- Input the user's choice.
- Perform the respective operation based on the choice:
- Call `enqueue()` for inserting an element.
- Call `dequeue()` for deleting an element.
- Call `display()` for showing the queue contents.
- Exit if the user chooses option 4.
- If an invalid choice is entered, display an error message.

SOURCE CODE:
#include <stdio.h>
#define MAX 5 // Define the maximum size of the circular queue
int queue[MAX];
int front = -1, rear = -1;
// Function to check if the queue is full
int isFull() {
return (front == 0 && rear == MAX - 1) || (front == rear + 1);
}
// Function to check if the queue is empty
int isEmpty() {
return front == -1;
}
// Function to insert an element into the circular queue
void enqueue(int value) {
if (isFull()) {
printf("Queue Overflow! Cannot insert %d\n", value);
return;
}
if (isEmpty()) { // First element being inserted
front = rear = 0;
} else if (rear == MAX - 1 && front != 0) { // Wrap around
rear = 0;
} else { // Normal case
rear++;
}
queue[rear] = value;
printf("%d inserted into the queue\n", value);
}
// Function to delete an element from the circular queue
void dequeue() {
if (isEmpty()) {
printf("Queue Underflow! No elements to delete\n");
return;
}
printf("%d deleted from the queue\n", queue[front]);
if (front == rear) { // Queue becomes empty
front = rear = -1;
} else if (front == MAX - 1) { // Wrap around
front = 0;
} else { // Normal case
front++;
}
}
// Function to display the elements of the queue
void display() {
if (isEmpty()) {
printf("Queue is empty\n");
return;
}
printf("Queue elements: ");
if (rear >= front) { // No wrapping
for (int i = front; i <= rear; i++) {
printf("%d ", queue[i]);
}
} else { // Wrapping occurred
for (int i = front; i < MAX; i++) {
printf("%d ", queue[i]);
}
for (int i = 0; i <= rear; i++) {
printf("%d ", queue[i]);
}
}
printf("\n");
}
int main() {
int choice, value;
while (1) {
printf("\nCircular Queue Operations:\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to insert: ");
scanf("%d", &value);
enqueue(value);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
printf("Exiting...\n");
return 0;
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}
OUTPUT:
ASSIGNMENT 19
PROBLEM: Write a c program to show the operations of a circular queue implemented as a linked-list.
ALGORITHM:
1.Initialization:
1. Create a structure for a `Node` with two fields:
- `data`: Stores the element.
- `next`: Points to the next node.
2. Initialize two global pointers:
- `front` (initially set to `NULL`): Points to the front of the queue.
- `rear` (initially set to `NULL`): Points to the rear of the queue
2. Menu-Driven Interface:
1. Display the menu options to the user:
- Option 1: Enqueue an element.
- Option 2: Dequeue an element.
- Option 3: Display the queue elements.
- Option 4: Exit the program.
2. Use a `while` loop to continuously accept user choices until "Exit" is selected.
3.Enqueue Operation (Option 1):
- Input: The element to add (user-provided).
- Steps:
1. Allocate memory for a new node using `malloc`.
2. Assign the input value to the `data` field of the new node.
3. Check if the queue is empty (`front == NULL`):
- Set both `front` and `rear` to point to the new node.
- Point the `next` of the new node to itself (circular link).
4. If the queue is not empty:
- Set `rear->next` to point to the new node.
- Update `rear` to point to the new node.
- Set `rear->next` to `front` to maintain circularity.
5. Display a message confirming the value was enqueued.
4. Dequeue Operation (Option 2):
- Input: None (deletion is always from the front).
-Steps:
1. Check if the queue is empty (`front == NULL`):
- Print a message indicating that the queue is empty.
- Exit the operation.
2. If there is only one node in the queue (`front == rear`):
- Free the memory of the node.
- Set both `front` and `rear` to `NULL`.
3. If there are multiple nodes:
- Store the `front` node in a temporary pointer.
- Move the `front` pointer to the next node (`front->next`).
- Update `rear->next` to point to the new `front`.
- Free the memory of the removed node.
4. Display a message confirming the value that was dequeued.
5. Display Operation(Option 3):
- Input: None (simply traverses and displays elements).
- Steps:
1. Check if the queue is empty (`front == NULL`):
- Print a message indicating the queue is empty.
- Exit the operation.
2. If the queue is not empty:
- Start from the `front` node.
- Traverse through the queue using a `do-while` loop.
- Print the `data` of each node until you return to the `front`.
3. Display all the elements in the queue.
6. Exit Operation (Option 4):
- Input: User selects "Exit".
-Steps:
1. Print a message indicating the program is exiting.
2. Terminate the program using `exit(0)`.
Flow of the Program:
1. The program initializes the queue with `front = NULL` and `rear = NULL`.
2. The user selects an operation from the menu.
3. Depending on the selected operation, the corresponding function (`enqueue`, `dequeue`, or `display`)
is called.
4. The menu is displayed repeatedly until the user chooses to exit.
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
// Define the structure for a node in the circular queue
struct Node {
int data;
struct Node* next;
};
// Initialize front and rear pointers
struct Node* front = NULL;
struct Node* rear = NULL;
// Enqueue operation: Adds an element to the queue
void enqueue(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
return;
}
newNode->data = value;
newNode->next = NULL;
if (front == NULL) { // If the queue is empty
front = rear = newNode;
rear->next = front; // Point to itself to make it circular
} else {
rear->next = newNode;
rear = newNode;
rear->next = front; // Maintain circular link
}
printf("Enqueued: %d\n", value);
}
// Dequeue operation: Removes an element from the queue
void dequeue() {
if (front == NULL) { // If the queue is empty
printf("Queue is empty! Cannot dequeue.\n");
return;
}
struct Node* temp = front;
if (front == rear) { // If there's only one element
front = rear = NULL;
} else {
front = front->next;
rear->next = front; // Maintain circular link
}
printf("Dequeued: %d\n", temp->data);
free(temp);
}
// Display operation: Shows the elements in the queue
void display() {
if (front == NULL) { // If the queue is empty
printf("Queue is empty!\n");
return;
}
struct Node* temp = front;
printf("Queue elements: ");
do {
printf("%d ", temp->data);
temp = temp->next;
} while (temp != front);
printf("\n");
}
int main() {
int choice, value;
while (1) {
printf("\nCircular Queue Operations:\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display\n");
printf("4. 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:
display();
break;
case 4:
printf("Exiting...\n");
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}

OUTPUT:
ASSIGNMENT 20
PROBLEM: Write a C program to create and perform different operations on double ended queues
using linked list implementations.
ALGORITHM:
Double-Ended Queue Using Linked List**
1. Node Structure:
- Each node contains:
- `data`: The value to store.
- `prev`: A pointer to the previous node.
- `next`: A pointer to the next node.
2. Initialization:
- Initialize two global pointers:
- `front`: Points to the first node of the deque (initially `NULL`).
- `rear`: Points to the last node of the deque (initially `NULL`).
3. Insert at the Front:
- Input: The value to insert.
- Steps:
1. Create a new node and assign the value to its `data`.
2. Set `newNode->prev` to `NULL` and `newNode->next` to the current `front`.
3. If the deque is empty (`front == NULL`):
- Set both `front` and `rear` to the new node.
4. Otherwise:
- Set `front->prev` to `newNode`.
- Update `front` to `newNode`.
5. Display a message confirming the insertion.

4. Insert at the Rear:


- Input: The value to insert.
- Steps:
1. Create a new node and assign the value to its `data`.
2. Set `newNode->next` to `NULL` and `newNode->prev` to the current `rear`.
3. If the deque is empty (`rear == NULL`):
- Set both `front` and `rear` to the new node.
4. Otherwise:
- Set `rear->next` to `newNode`.
- Update `rear` to `newNode`.
5. Display a message confirming the insertion.
5. Delete from the Front:
- Input: None.
- Steps:
1. If the deque is empty (`front == NULL`):
- Print a message indicating that the deque is empty.
- Exit the operation.
2. Otherwise:
- Store the current `front` in a temporary pointer.
- If there’s only one node (`front == rear`):
- Set both `front` and `rear` to `NULL`.
- Otherwise:
- Update `front` to `front->next`.
- Set `front->prev` to `NULL`.
- Free the memory of the temporary node.
3. Display a message confirming the deletion.
6. Delete from the Rear:
-Input: None.
- Steps:
1. If the deque is empty (`rear == NULL`):
- Print a message indicating that the deque is empty.
- Exit the operation.
2. Otherwise:
- Store the current `rear` in a temporary pointer.
- If there’s only one node (`front == rear`):
- Set both `front` and `rear` to `NULL`.
- Otherwise:
- Update `rear` to `rear->prev`.
- Set `rear->next` to `NULL`.
- Free the memory of the temporary node.
3. Display a message confirming the deletion.

7. Display the Deque:


- Input: None.
- Steps:
1. If the deque is empty (`front == NULL`):
- Print a message indicating that the deque is empty.
- Exit the operation.
2. Otherwise:
- Start from the `front` node.
- Traverse the deque using a `while` loop until the `rear` node is reached.
- Print each node’s `data`.
8. Menu-Driven Interface:
-Steps:
1. Display the menu options:
- Insert at Front
- Insert at Rear
- Delete from Front
- Delete from Rear
- Display
- Exit
2. Accept the user’s choice.
3. Based on the choice:
- Call the corresponding operation function.
- Display appropriate messages.
4. Repeat until the user selects "Exit".
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
// Define the structure for a node
struct Node {
int data;
struct Node* prev;
struct Node* next;
};

// Initialize front and rear pointers


struct Node* front = NULL;
struct Node* rear = NULL;
// Function to insert an element at the front
void insertFront(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
return;
}
newNode->data = value;
newNode->prev = NULL;
newNode->next = front;
if (front == NULL) { // If the deque is empty
front = rear = newNode;
} else {
front->prev = newNode;
front = newNode;
}
printf("Inserted %d at the front.\n", value);
}
// Function to insert an element at the rear
void insertRear(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
return;
}
newNode->data = value;
newNode->next = NULL;
newNode->prev = rear;
if (rear == NULL) { // If the deque is empty
front = rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
}
printf("Inserted %d at the rear.\n", value);
}
// Function to delete an element from the front
void deleteFront() {
if (front == NULL) { // If the deque is empty
printf("Deque is empty! Cannot delete from the front.\n");
return;
struct Node* temp = front;
printf("Deleted %d from the front.\n", front->data);

if (front == rear) { // If there's only one element


front = rear = NULL;
} else {
front = front->next;
front->prev = NULL;
}
free(temp);
}
void deleteRear() {
if (rear == NULL) { // If the deque is empty
printf("Deque is empty! Cannot delete from the rear.\n");
return;
}
struct Node* temp = rear;
printf("Deleted %d from the rear.\n", rear->data);
if (front == rear) { // If there's only one element
front = rear = NULL;
} else {
rear = rear->prev;
rear->next = NULL;
}
free(temp);
}
void display() {
if (front == NULL) { // If the deque is empty
printf("Deque is empty!\n");
return;
}
struct Node* temp = front;
printf("Deque elements: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
int choice, value;
while (1) {
printf("\nDouble-Ended Queue Operations:\n");
printf("1. Insert at Front\n");
printf("2. Insert at Rear\n");
printf("3. Delete from Front\n");
printf("4. Delete from Rear\n");
printf("5. Display\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice)
switch (choice) {
case 1:
printf("Enter the value to insert at front: ");
scanf("%d", &value);
insertFront(value);
break;
case 2:
printf("Enter the value to insert at rear: ");
scanf("%d", &value);
insertRear(value);
break;
case 3:
deleteFront();
break;
case 4:
deleteRear();
break;
case 5:
display();
break;
case 6:
printf("Exiting...\n");
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}

OUTPUT:
ASSIGNMENT 17
PROBLEM: Write a C program to evaluate a postfix expression using a Stack.
ALGORITHM:
1. Initialize the Stack:
- Create an empty stack to store operands.
2. Iterate Through the Expression:
- Start reading the postfix expression character by character.
3. Check Each Character:
- If the character is a digit (operand):
- Push it onto the stack.
- If the character is an operator (+, -, *, /):
- Pop the top two elements from the stack.
- Perform the operation using the two popped elements:
- Let `operand2` be the first element popped.
- Let `operand1` be the second element popped.
- Apply the operation (`operand1 operator operand2`).
- Push the result of the operation back onto the stack.
4.Handle Invalid Input:
- If any character is not a valid digit or operator, terminate the program with an error message.
5. Continue Until End of Expression:
- Repeat the process for all characters in the postfix expression.
6. Final Result:
- After processing the entire expression, the result will be the only value left in the stack.
- Pop this value and output it as the final result.

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX 100
// Stack structure
typedef struct {
int data[MAX];
int top;
} Stack;
// Stack operations
void push(Stack *stack, int value) {
stack->data[++(stack->top)] = value;
}
int pop(Stack *stack) {
return stack->data[(stack->top)--];
}
// Function to evaluate postfix expression
int evaluatePostfix(char *expression) {
Stack stack;
stack.top = -1;
char *e = expression;
while (*e != '\0') {
if (isdigit(*e)) {
// Push the numeric value onto the stack
push(&stack, *e - '0');
} else {
// Pop two operands and apply the operator
int operand2 = pop(&stack);
int operand1 = pop(&stack);
switch (*e) {
case '+':
push(&stack, operand1 + operand2);
break;
case '-':
push(&stack, operand1 - operand2);
break;
case '*':
push(&stack, operand1 * operand2);
break;
case '/':
push(&stack, operand1 / operand2);
break;
default:
printf("Invalid operator: %c\n", *e);
exit(1);
}
}
e++;
}
return pop(&stack);
}
int main() {
char expression[MAX];
printf("Enter the postfix expression (e.g., 53+82-*): ");
fgets(expression, MAX, stdin);
expression[strcspn(expression, "\n")] = '\0'; // Remove newline character
int result = evaluatePostfix(expression);
printf("The result is: %d\n", result);
return 0;
}

OUTPUT:
ASSIGNMENT 15
PROBLEM: Write a C program to convert a infix expression into its postfix equivalent using a stack.
ALGORITHM:
Scan the symbols of the expression from left to right and for each symbol, do the following
Step 1:If symbol is an operand
Print that symbol onto the screen
Step 2:If symbol is a left paranthesis
Push it on the stack
Step 3:If symbol is a right paranthesis
Pop all the operators from the stack uopto the first left parenthesis and print them on the screen.
Discard the left and right parenthesis.
Step 4:If symbol is an operator
If the precedence of the operators in the stack are greater than or equal to the current operator then
pop the operators out of the stack and print them onto the screen and push the current operator
onto the stack .
Else
push the current operator onto the stack.

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX 100 // Maximum stack size
// Stack structure
char stack[MAX];
int top = -1;
// Function to push an element onto the stack
void push(char c) {
if (top == MAX - 1) {
printf("Stack Overflow\n");
} else {
stack[++top] = c;
}
}
// Function to pop an element from the stack
char pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
} else {
return stack[top--];
}
}
// Function to return the precedence of operators
int precedence(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
if (op == '^') return 3;
return 0;
}
// Function to check if a character is an operator
int is_operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';
}
// Function to convert infix to postfix
void infix_to_postfix(char* infix, char* postfix) {
int i = 0, j = 0;
char symbol, temp;
while ((symbol = infix[i++]) != '\0') {
if (isalnum(symbol)) { // Operand
postfix[j++] = symbol;
} else if (symbol == '(') { // Left parenthesis
push(symbol);
} else if (symbol == ')') { // Right parenthesis
while ((temp = pop()) != '(') {
postfix[j++] = temp;
}
} else if (is_operator(symbol)) { // Operator
while (top != -1 && precedence(stack[top]) >= precedence(symbol)) {
postfix[j++] = pop();
}
push(symbol);
}
}
// Pop all remaining operators from the stack
while (top != -1) {
postfix[j++] = pop();
}
postfix[j] = '\0'; // Null-terminate the postfix expression
}
// Main function
int main() {
char infix[MAX], postfix[MAX];
printf("Enter the infix expression: ");
scanf("%s", infix);
infix_to_postfix(infix, postfix);
printf("Postfix Expression: %s\n", postfix);
return 0;
}

OUTPUT:
ASSIGNMENT 21
PROBLEM: Write a C program to convert prefix expression to its equivalent postfix expression using
stack.
ALGORITHM:
1. Initialize a stack to store intermediate results.
2. Traverse the prefix expression from right to left (starting from the last character):
- If the current character is an operand (a letter or digit):
- Push the operand onto the stack.
- If the current character is an operator (`+`, `-`, `*`, `/`, etc.):
1. Pop the top two elements from the stack (these are the two operands for the operator).
2. Concatenate the two operands in the following order: `<operand1><operand2><operator>`.
3. Push the resulting expression back onto the stack.
3. After the traversal is complete, the stack will contain one element, which is the final postfix
expression.
4. Pop and return the final postfix expression from the stack.

SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 100
// Stack structure
typedef struct Stack {
char items[MAX][MAX];
int top;
} Stack;
// Initialize stack
void initStack(Stack* stack) {
stack->top = -1;
}

// Check if the stack is empty


int isEmpty(Stack* stack) {
return stack->top == -1;
// Push an element onto the stack
void push(Stack* stack, char* item) {
if (stack->top < MAX - 1) {
strcpy(stack->items[++stack->top], item);
}
}
// Pop an element from the stack
void pop(Stack* stack, char* item) {
if (!isEmpty(stack)) {
strcpy(item, stack->items[stack->top--]);
}
}
// Get the top element of the stack
void peek(Stack* stack, char* item) {
if (!isEmpty(stack)) {
strcpy(item, stack->items[stack->top]);
}
}
// Check if a character is an operator
int isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
// Function to convert prefix to postfix
void prefixToPostfix(char* prefix, char* postfix) {
Stack stack;
initStack(&stack);
int length = strlen(prefix);
// Iterate from right to left
for (int i = length - 1; i >= 0; i--) {
if (isalnum(prefix[i])) {
// If the character is an operand
char operand[2] = {prefix[i], '\0'};
push(&stack, operand);
} else if (isOperator(prefix[i])) {
// If the character is an operator
char operand1[MAX], operand2[MAX], temp[MAX];
pop(&stack, operand1);
pop(&stack, operand2);
sprintf(temp, "%s%s%c", operand1, operand2, prefix[i]);
push(&stack, temp);
}
}
// Final postfix expression
pop(&stack, postfix);
}
int main() {
char prefix[MAX], postfix[MAX];
printf("Enter the prefix expression: ");
scanf("%s", prefix);
prefixToPostfix(prefix, postfix);
printf("The equivalent postfix expression is: %s\n", postfix);
return 0;
}

OUTPUT:
ASSIGNMENT 22
PROBLEM:Write a C program to reverse the order of the elements in the stack using additional stack.
ALGORITHM:
1. Initialize Temporary Storage:
- Declare a temporary stack (`tempStack`) to hold reversed elements.
- Set the `top` pointer of `tempStack` to `-1`.

2. Reverse the Elements:


- Iterate through the original stack from the last element (`size - 1`) to the first element (`0`).
- Push each element from the original stack onto the `tempStack` by incrementing the `top` pointer of
`tempStack`.
3. Copy Reversed Elements:
- Iterate through `tempStack` from the first element (`0`) to the last element (`top`).
- Copy each element from `tempStack` back to the original stack.

4. Output the Results:


- The original stack is now reversed. Display the reversed stack if needed.
SOURCE CODE:
#include <stdio.h>
#define MAX 100
void reverseStack(int stack[], int size) {
int tempStack[MAX];
int top = -1;
int i;
for (i = size - 1; i >= 0; i--) {
tempStack[++top] = stack[i];
}
for (i = 0; i <= top; i++) {
stack[i] = tempStack[i];
}
}
void displayStack(int stack[], int size) {
int i;
for (i = 0; i < size; i++) {
printf("%d ", stack[i]);
}
printf("\n");
}

int main() {
int stack[MAX], size,i;

printf("Enter the number of elements in the stack: ");


scanf("%d", &size);

printf("Enter %d elements:\n", size);


for (i = 0; i < size; i++) {
scanf("%d", &stack[i]);
}

printf("Original Stack: ");


displayStack(stack, size);

reverseStack(stack, size);

printf("Reversed Stack: ");


displayStack(stack, size);

return 0;
}
OUTPUT:
ASSIGNMENT 24
PROBLEM: Write a C program to implement Merge Sort.Show the output for the best as well as worst
case.
ALGORITHM:
1. Start with Input:
- Accept an array of `n` elements from the user.
- Take the size of the array `n` and the elements as input.
2. Recursive Division:
- Call the `mergeSort` function with parameters: the array, the left index (`left = 0`), and the right
index (`right = n-1`).
- If `left < right`, find the middle index (`mid = left + (right - left) / 2`).
- Recursively call `mergeSort` for:
- The left half: from `left` to `mid`.
- The right half: from `mid + 1` to `right`.
3. Merge Sorted Halves:
- After both halves are sorted, call the `merge` function to combine them.
- The `merge` function performs the following:
- Create two temporary arrays to hold elements of the left and right halves.
- Compare elements of both temporary arrays and copy the smaller element back into the original
array.
- Copy any remaining elements from the temporary arrays into the original array.
4. Base Condition for Recursion:
- If `left >= right`, stop further division (the array segment contains a single element, which is
inherently sorted).
5. Output the Sorted Array:
- Once the recursive calls and merges are complete, the array is fully sorted.
- Print the sorted array.
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h>
// Function to merge two halves
void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
// Temporary arrays
int L[n1], R[n2];
// Copy data to temporary arrays
for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
// Merge temporary arrays back into the original array
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++;
}
// Copy remaining elements of L[], if any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
// Copy remaining elements of R[], if any
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
// Function to implement Merge Sort
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
// Recursively sort the first and second halves
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
// Merge the sorted halves
merge(arr, left, mid, right);
}
}
// Function to print an array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int n;

printf("Enter the number of elements: ");


scanf("%d", &n);
int arr[n];
printf("Enter %d elements: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Original array: ");
printArray(arr, n);
mergeSort(arr, 0, n - 1);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
OUTPUT:
BEST CASE

WORST CASE
ASSIGNMENT 25
PROBLEM: Write a C program to implement Heap Sort. Show the output for the best and worst case.
ALGORITHM:
1. Input:
- Start with an array of `n` elements.
2. Build a Max Heap:
- Treat the array as a complete binary tree.
- For all non-leaf nodes, starting from the last non-leaf node (index `n/2 - 1`), perform the `heapify`
operation to ensure the subtree rooted at each node satisfies the max heap property.
- The max heap property ensures that every parent node is greater than or equal to its children.
3. Heapify Function:
- Compare the root node with its left and right children.
- If the left or right child is larger than the root, swap the root with the largest child.
- Recursively call `heapify` on the affected child node to restore the max heap property.
4. Sorting the Array:
- Swap the root of the max heap (largest element) with the last element of the array.
- Reduce the heap size by one (exclude the last element, which is now sorted).
- Perform the `heapify` operation on the root to restore the max heap property for the reduced heap.
- Repeat this process until all elements are sorted.
5. Output the Sorted Array:

SOURCE CODE:
#include <stdio.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void heapify(int arr[], int n, int i) {
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // Left child
int right = 2 * i + 2; // Right child
// If the left child is larger than the root
if (left < n && arr[left] > arr[largest]) {
largest = left;
}
// If the right child is larger than the largest so far
if (right < n && arr[right] > arr[largest]) {
largest = right;
}
// If the largest is not the root
if (largest != i) {
swap(&arr[i], &arr[largest]);
// Recursively heapify the affected subtree
heapify(arr, n, largest);
}
}
void heapSort(int arr[], int n) {
// Build a max heap
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
// Extract elements from the heap one by one
for (int i = n - 1; i > 0; i--) {
// Move the current root to the end
swap(&arr[0], &arr[i]);
// Call heapify on the reduced heap
heapify(arr, i, 0);
}
}

// Function to print an array


void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Original array: ");
printArray(arr, n);
heapSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}

OUTPUT:
BEST CASE

WORST CASE
ASSIGNMENT 26
PROBLEM: Write a C program to implement Radix Sort. Show the output for the best and worst case.
ALGORITHM:
1. Determine the Maximum Value:
Identify the largest number in the array to determine the maximum number of digits (`d`) in the array
elements.
2. Iterate Through Each Digit Place:
Start sorting the numbers based on the least significant digit (LSD), moving toward the most significant
digit (MSD). For each digit place:
- Initialize Buckets:
Create 10 buckets (or lists) for digits 0 through 9.
- Place Elements in Buckets:
Place each element in the bucket corresponding to the current digit.
- Collect from Buckets:
Collect the elements from the buckets in order (from 0 to 9) to form the updated array.
3. Repeat for Each Digit Place:
Repeat the process for all digit places, from LSD to MSD, until the array is fully sorted.
4. Output the Sorted Array:
After processing all digit places, the array is sorted.

SOURCE CODE:
#include <stdio.h>
int getMax(int arr[], int n) {
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
void countingSort(int arr[], int n, int exp) {
int output[n];
int count[10] = {0};
// Count occurrences of each digit
for (int i = 0; i < n; i++) {
count[(arr[i] / exp) % 10]++;
}
// Update count[i] to store cumulative positions
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
// Build the output array
for (int i = n - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}

for (int i = 0; i < n; i++) {


arr[i] = output[i];
}
}

void radixSort(int arr[], int n) {


int max = getMax(arr, n);
for (int exp = 1; max / exp > 0; exp *= 10) {
countingSort(arr, n, exp);
}
}

void printArray(int arr[], int n) {


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int n;
// Taking input for the size of the array
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
// Taking input for array elements
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Original Array: ");
printArray(arr, n);
// Sorting the array using Radix Sort
radixSort(arr, n);
printf("Sorted Array: ");
printArray(arr, n);
return 0;
}
OUTPUT:
BEST CASE

WORST CASE
ASSIGNMENT 23
PROBLEM STATEMENT: Write a C program to reverse the order of the elements in the stack using
additional Queue.
ALGORITHM:
Input:
- A stack `S` with `N` elements.
- An empty queue `Q`.
Steps:
1.Initialize an Empty Queue:
- Create an empty queue `Q`.

2. Push Stack Elements into Queue:


- While the stack `S` is not empty:
- Pop the top element from stack `S`.
- Enqueue the popped element into queue `Q`.

3.Reverse Order with FIFO Property:


- Use the queue's FIFO (First-In, First-Out) property to preserve the reversed order.

4.
Push Queue Elements Back into Stack:
- While the queue `Q` is not empty:
- Dequeue the front element from queue `Q`.
- Push the dequeued element back onto stack `S`.

5. Output:
- The stack `S` is now reversed.

Output:
- Stack `S` with its elements in reversed order.
SOURCE CODE:
#include <stdio.h>
#include <stdlib.h
#define MAX 100

void enqueue(int queue[], int *rear, int value) {


queue[++(*rear)] = value;
}
int dequeue(int queue[], int *front, int rear) {
if (*front > rear) {
printf("Queue underflow\n");
return -1; // Return -1 in case of underflow
}
return queue[(*front)++];
}
void push(int stack[], int *top, int value) {
if (*top >= MAX - 1) {
printf("Stack overflow\n");
return;
}
stack[++(*top)] = value;
}
int pop(int stack[], int *top) {
if (*top == -1) {
printf("Stack underflow\n");
return -1; // Return -1 in case of underflow
}
return stack[(*top)--];
}
void displayStack(int stack[], int top) {
if (top == -1) {
printf("Stack is empty\n");
return;
}
for (int i = 0; i <= top; i++) {
printf("%d ", stack[i]);
}
printf("\n");
}

void reverseStack(int stack[], int *top, int queue[], int *front, int *rear) {
// Push all stack elements to the queue
while (*top != -1) {
int value = pop(stack, top);
enqueue(queue, rear, value);
}

while (*front <= *rear) {


int value = dequeue(queue, front, *rear);
push(stack, top, value);
}
}

int main() {
int stack[MAX], queue[MAX];
int top = -1, front = 0, rear = -1;
int size, element;
printf("Enter the number of elements in the stack: ");
scanf("%d", &size);
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &element);
push(stack, &top, element);
}
printf("Original Stack: ");
displayStack(stack, top);
reverseStack(stack, &top, queue, &front, &rear);
printf("Reversed Stack: ");
displayStack(stack, top);

return 0;
}
OUTPUT:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy