0% found this document useful (0 votes)
11 views4 pages

Stack Push and Pop Operations Code

The document is a C program that implements a stack with push and pop operations. It allows users to push elements onto the stack, pop elements from it, and display the current stack contents. The program includes error handling for stack overflow and underflow conditions.
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)
11 views4 pages

Stack Push and Pop Operations Code

The document is a C program that implements a stack with push and pop operations. It allows users to push elements onto the stack, pop elements from it, and display the current stack contents. The program includes error handling for stack overflow and underflow conditions.
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

Ques. Stack: Push and Pop Operation.

#include <stdio.h>
#define SIZE 5 // Maximum size of the stack
int stack[SIZE]; // Array to store stack elements
int top = -1; // Initialize the top of the stack to -1
// Function to push an element onto the stack
void push() {
int value;
if (top == SIZE - 1) {
printf("Stack Overflow! Cannot push more elements.\n");
}
else {
printf("Enter the value to push: ");
scanf("%d", &value);
top++;
stack[top] = value;
printf("%d pushed onto 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 {
int value = stack[top];
top--;
printf("%d popped from the stack.\n", value);
}
}
// Function to display the elements of the stack
void display() {
if (top == -1) {
printf("The stack is empty.\n");
}
else {
printf("Current stack: ");
for (int i = 0; i <= top; i++) {
printf("%d ", stack[i]);
}
printf("\n");
}
}
// Main function to handle user input
int main() {
int choice;
do {
printf("\nStack Operations:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
printf("Exiting program.\n");
break;
default:
printf("Invalid choice! Please try again.\n");
}
}
while (choice != 4);
return 0;
}

You might also like