0% found this document useful (0 votes)
10 views

Lab Program No. 3

Lab DSA Vtu 3rd sem computer engineering
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Lab Program No. 3

Lab DSA Vtu 3rd sem computer engineering
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

/* 3.

Create a menu-driven program in C to perform various operations on a stack of integers using an array-based im
. Perform the following operations.
• Push an Element on to Stack.
• Pop an Element from Stack.
• Demonstrate Overflow and Underflow situations on Stack.
• Display the status of Stack.
• Exit
*/

#include <stdio.h>
#include <stdlib.h>

#define MAX 5 // Maximum size of the stack

// Stack structure
typedef struct Stack {
int items[MAX];
int top;
} Stack;

// Function to initialize the stack


void initStack(Stack* stack) {
stack->top = -1; // Stack is empty
}

// Function to check if the stack is full


int isFull(Stack* stack) {
return stack->top == MAX - 1; // Stack is full
}

// Function to check if the stack is empty


int isEmpty(Stack* stack) {
return stack->top == -1; // Stack is empty
}

// Function to push an element onto the stack


void push(Stack* stack, int value) {
if (isFull(stack)) {
printf("Stack Overflow! Cannot push %d onto stack.\n", value);
} else {
stack->items[++stack->top] = value; // Increment top and add value
printf("Pushed %d onto stack.\n", value);
}
}

// Function to pop an element from the stack


int pop(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack Underflow! Cannot pop from stack.\n");
return -1; // Return -1 to indicate failure
} else {
return stack->items[stack->top--]; // Return value and decrement top
}
}

// Function to display the stack


void display(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty.\n");
} else {
printf("Stack elements: ");
for (int i = stack->top; i >= 0; i--) {
printf("%d ", stack->items[i]);
}
printf("\n");
}
}

// Main function
int main() {
Stack stack;
initStack(&stack);
int choice, value;

do {
printf("\nMenu:\n");
printf("1. Push an element onto stack\n");
printf("2. Pop an element from stack\n");
printf("3. Display stack status\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to push: ");
scanf("%d", &value);
push(&stack, value);
break;
case 2:
value = pop(&stack);
if (value != -1) {
printf("Popped value: %d\n", value);
}
break;
case 3:
display(&stack);
break;
case 4:
printf("Exiting...\n");
break;
default:
printf("Invalid choice! Please try again.\n");
}
} while (choice != 4);

return 0;
}

You might also like