Google Ads

Monday, May 25, 2009

Stack Operation - Using Array

#include “stdio.h”
#include “conio.h”
int n,i,ch,top=-1,s[20],value;
void main()
{
int ch;
clrscr();
printf("\n Enter the stack size:");
scanf("%d",&n);
do
{
printf("\n 1.PUSH\n 2.POP\n 3.PEEK\n 4.DISPLAY\n 5.EXIT");
printf("\n Enter Your Choice:");
scanf("%d", &ch);
switch(ch)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
peek();
break;
case 4:
display();
break;
case 5:
exit(0);
break;
}
}while(ch!=5);
getch();
}


push()
{
if(top==n-1)
printf("\n Stack is full");
else
{
printf("\n Enter The Data :");
scanf("%d",&value);
top++;
s[top]=value;
printf("\n The inserted data is:%d",value);
}
}

pop()
{
if(top==-1)
printf("\n Stack is empty");
else
{
value=s[top];
top--;
printf("\n The deleted data is:%d",value);
}
}

peek()
{
if(top==-1)
printf("\n Stack is empty");
else
{
value=s[top];
printf("\n The peeked value is:%d",value);
}
}


display()
{
if(top==-1)
printf("\n Stack is empty");
else
{
printf("\n Stack Values are:");
for(i=top;i>=0;i--)
printf("\n%d",s[i]);
}
}



Output will be


1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.EXIT
Enter Your Choice:1

Enter The Data :3

1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.EXIT

Enter Your Choice:2

The deleted data is:3

1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.EXIT
Enter Your Choice:1

Enter The Data :5

1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.EXIT
Enter Your Choice:4

Stack Values are :5

1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.EXIT
Enter Your Choice:3

The peeked data is:5

1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.EXIT
Enter Your Choice:5

No comments:

Post a Comment