#include <stdio.h>
#include <stdlib.h>
#include <limits.h> // For INT_MIN
#define SIZE 100
// Create a stack with capacity of 100 elements
int stack[SIZE];
// Initially stack is empty
int top = -1;
//////////////// Push /////////////////
void push()
{
int element;
if (top >= SIZE)
{
printf("Stack Overflow, can't add more element element to stack.\n");
}
else
{
printf("Enter the item to be pushed in stack : ");
scanf("%d", &element);
top = top + 1;
stack[top] = element;
printf("Data pushed to stack.\n");
}
}
//////////////// Pop /////////////////
int pop()
{
if (top == -1)
printf("Stack Underflow\n");
else
{
printf("\nPopped element is : %d\n", stack[top]);
top = top - 1;
}
}
//////////////// Display /////////////////
void display()
{
int i;
if (top == -1)
printf("Stack is empty\n");
else
{
printf("Stack elements :\n");
for (i = top; i >= 0; i--)
printf(" %d ", stack[i]);
}
}
/////////// MAIN MENU ///////////////
int main()
{
int choice, data;
while (1)
{
printf("\n-----MENU----\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Size\n");
printf("4. Display\n");
printf("5. Exit\n");
printf("------------------------------------\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
printf("Stack size: %d\n", top + 1);
break;
case 4:
display();
break;
case 5:
printf("Exiting from app.\n");
exit(0);
break;
default:
printf("Invalid choice, please try again.\n");
}
printf("\n\n");
}
return 0;
}
Output
---------- MENU ----------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 2
Stack is empty.
---------- MENU ----------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 1
Enter data to push into stack: 10
Data pushed to stack.
---------- MENU ----------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 1
Enter data to push into stack: 20
Data pushed to stack.
---------- MENU ----------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 1
Enter data to push into stack: 30
Data pushed to stack.
---------- MENU ----------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 3
Stack size: 3
---------- MENU ----------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 2
Data => 30
---------- MENU ----------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 2
Data => 20
---------- MENU ----------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 2
Data => 10
---------- MENU ----------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 2
Stack is empty.
---------- MENU ----------
1. Push
2. Pop
3. Size
4. Exit
------------------------------------
Enter your choice: 4
Exiting from app.
0 Comments