/************************************************************
* Filename: Stack_Using_Array.c
* Description: To do stack operations using array
* Author: Sarju S
* Date: 01-Dec-2011
*************************************************************/
#include
#include
#define MAX_STACK_SIZE 100 /*maximum stack size*/
int stack[MAX_STACK_SIZE],top=-1;/* Global Declarations */
void stackFull()
{
fprintf(stderr, "Stack is full cannot add elements\n");
exit(EXIT_FAILURE);
}
void stackEmpty()
{
fprintf(stderr, "Stack is empty cannot delete elements\n");
exit(EXIT_FAILURE);
}
void push(int item)
{/* add an element to stack */
if(top>=MAX_STACK_SIZE-1)
stackFull();
stack[++top] = item;
}
int pop()
{/*Delete top element from the stack*/
if(top==-1)
stackEmpty();
return stack[top--];
}
void display()
{
int i;
for(i=0;i<=top;i++)
printf("%d\t",stack[i]);
}
void main()
{
int ch,element;
do /* Loop for repeating the menu*/
{
printf("\nMENU\n1.PUSH \n2.POP\n3.EXIT");
printf("\nEnter Your Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter the element to add:");
scanf("%d",&element);
push(element);
printf("\nElement added is:%d",element);
printf("\nThe Current Stack is:\n");
display();
break;
case 2: element = pop();
printf("\nElement deleted is:%d",element);
printf("\nThe Current Stack is:\n");
display();
}
}while(ch<3);
}
OUTPUT
krishnakripa@krishnakripa-K8Upgrade-VM800:~$ gcc Stack_Using_Array.c
krishnakripa@krishnakripa-K8Upgrade-VM800:~$ ./a.out
MENU
1.PUSH
2.POP
3.EXIT
Enter Your Choice:2
Stack is empty cannot delete elements
krishnakripa@krishnakripa-K8Upgrade-VM800:~$ ./a.out
MENU
1.PUSH
2.POP
3.EXIT
Enter Your Choice:1
Enter the element to add:11
Element added is:11
The Current Stack is:
11
MENU
1.PUSH
2.POP
3.EXIT
Enter Your Choice:1
Enter the element to add:22
Element added is:22
The Current Stack is:
11 22
MENU
1.PUSH
2.POP
3.EXIT
Enter Your Choice:1
Enter the element to add:33
Element added is:33
The Current Stack is:
11 22 33
MENU
1.PUSH
2.POP
3.EXIT
Enter Your Choice:2
Element deleted is:33
The Current Stack is:
11 22
MENU
1.PUSH
2.POP
3.EXIT
Enter Your Choice:2
Element deleted is:22
The Current Stack is:
11
MENU
1.PUSH
2.POP
3.EXIT
Enter Your Choice:2
Element deleted is:11
The Current Stack is:
MENU
1.PUSH
2.POP
3.EXIT
Enter Your Choice:2
Stack is empty cannot delete elements