C Program to implement basic operation of Stacks using global variables
Program
#include<stdio.h>
#include<stdlib.h>
#define STACK_SIZE 5
int top;
int s[STACK_SIZE];
int item;
void push()
{
if(top == STACK_SIZE -1)
{
printf("Stack Overflow\n");
return;
}
s[++top] = item;
}
int pop()
{
int item_deleted;
if(top == -1)
{
return 0;
}
item_deleted = s[top];
top--;
return item_deleted;
}
void display()
{
int i;
if(top == -1)
{
printf("Stack is empty\n");
return;
}
printf("Contents of the stack are:\n");
for(i = 0; i <= top; i++)
{
printf("%d\n",s[i]);
}
}
void main()
{
int item_deleted, choice;
top = -1;
for(;;)
{
printf("Enter the choice\n");
printf("1: Push\n2: Pop\n3: Display\n4: Exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter the item to be inserted\n");
scanf("%d",&item);
push();
break;
case 2:
item_deleted = pop();
if(item_deleted == 0)
printf("Stack is empty\n");
else
printf("Item deleted = %d\n",item_deleted);
break;
case 3:
display();
break;
default:
exit(0);
}
}
}
Output
Enter the choice
1: Push
2: Pop
3: Display
4: Exit
1
Enter the item to be inserted
10
Enter the choice
1: Push
2: Pop
3: Display
4: Exit
1
Enter the item to be inserted
20
Enter the choice
1: Push
2: Pop
3: Display
4: Exit
1
Enter the item to be inserted
30
Enter the choice
1: Push
2: Pop
3: Display
4: Exit
1
Enter the item to be inserted
40
Enter the choice
1: Push
2: Pop
3: Display
4: Exit
1
Enter the item to be inserted
50
Enter the choice
1: Push
2: Pop
3: Display
4: Exit
1
Enter the item to be inserted
60
Stack Overflow
Enter the choice
1: Push
2: Pop
3: Display
4: Exit
3
Contents of the stack are:
10
20
30
40
50
Enter the choice
1: Push
2: Pop
3: Display
4: Exit
2
Item deleted = 50
Enter the choice
1: Push
2: Pop
3: Display
4: Exit
2
Item deleted = 40
Enter the choice
1: Push
2: Pop
3: Display
4: Exit
2
Item deleted = 30
Enter the choice
1: Push
2: Pop
3: Display
4: Exit
2
Item deleted = 20
Enter the choice
1: Push
2: Pop
3: Display
4: Exit
2
Item deleted = 10
Enter the choice
1: Push
2: Pop
3: Display
4: Exit
2
Stack is empty
Enter the choice
1: Push
2: Pop
3: Display
4: Exit
3
Stack is empty
Enter the choice
1: Push
2: Pop
3: Display
4: Exit
4