Implementation of Stack using Array.
What is stack:- Click here
Code:-
#include<stdio.h>
#define max 5
int stack[max];
int top=-1;
// function for push the element into stack
void push()
{
int element ;
if(top==max–1)
printf(“Overflow”);
else
{
printf(“Enter a number “);
scanf(“%d”,&element);
top=top+1;
stack[top]=element;
}
}
// function for pop the element from the stack
void pop()
{
int element;
if(top==-1)
printf(“Underflow condition”);
else
{
element=stack[top];
printf(“pop element is %d”,element);
top=top–1;
}
}
// function for display the element of the stack
void display()
{
int element;
if(top==-1)
printf(“Underflow condition”);
else
{
for(int i=top;i>=0;i–)
{
printf(“%d “,stack[i]);
}
}
}
// function for reverse the stack
void reverse()
{
int tem;
for(int i=top;i>top/2;i–)
{
tem=stack[i];
stack[i]=stack[top–i];
stack[top–i]=tem;
}
}
//Driver function
void main()
{
int ch;
printf(“1.pushn”);
printf(“2.popn”);
printf(“3.displayn”);
printf(“4.reversen”);
printf(“5. exitn”);
while(1)
{
printf(“nEnter your choicen”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: reverse();
break;
case 5: exit(0);
default:
printf(“Worng key”);
}
}
}
Output:-
1.push
2.pop
3.display
4.reverse
exit
Enter your choice
1
Enter a number 12
Enter your choice
1
Enter a number 21
Enter your choice
2
pop element is 21
Enter your choice