ARRAY IMPLEMENTATION OF STACK
Aim
To write a C-program to implement stack
using array data structure.
And perform the following stack
operations
1.
POP
2.
PUSH
3.
PEEP
Algorithm
STEP 1:Start
STEP 2:Initialize stack, will=1,i, num
STEP 3:Add element in stack
PUSH(S,TOP,X)
3.a. [Check overflow condition]
If(TOP>=N) then
Write(“Stack
is full”)
3.b.
[Insert element]
[Increment
TOP]
TOP <-
TOP+1
S[TOP]<- X
3.c. [Finish the process]
STEP 4: Delete
element in stack
POP(S,TOP)
4.a. [Check for underflow condition]
If(TOP <- 0) then
Write(“Stack is empty”)
4.b.
[Delete element]
[Decrement
TOP]
TOP<- TOP-1
Delete S[TOP+1]
4.c.[Finish the process]
STEP 5:Stop
Coding:
#include<stdio.h>
#include<conio.h>
#define size 10
int stack[size],top=0,b;
int res;
void push();
void pop();
void display();
void main()
{
int
c;
clrscr();
printf("\n1.Push\n2.Pop\n3.Display");
do
{
printf("\n\nEnter
your Choice :: ");
scanf("%d",&c);
switch(c)
{
case
1:
push();
break;
case
2:
pop();
break;
case
3:
printf("\n\nContents
of stack is \t");
display();
break;
default:
printf("\nInvalid
Choice......");
exit(0);
}
}while(c<4);
getch();
}
void push()
{
if(top>=size)
{
printf("\nStack
Overflow");
return;
}
else
{
printf("\nEnter
the number to be pushed into the stack :: ");
scanf("%d",&b);
top++;
stack[top]=b;
printf("\nNumber
pushed is %d",stack[top]);
return;
}
}
void pop()
{
if(top==0)
{
printf("\nStack
Underflow");
return;
}
else
{
res=stack[top];
top--;
printf("\nDeleted
element is %d",res);
return;
}
}
void display()
{
int
i;
if(top==0)
{
printf("\nStack
Underflow");
return;
}
for(i=top;i>0;i--)
printf("%d
, ",stack[i]);
}
Output:
1.Push
2.Pop
3.Display
Enter your Choice :: 1
Enter the number to be pushed into the
stack :: 3
Number pushed is 3
Enter your Choice :: 1
Enter the number to be pushed into the
stack :: 5
Number pushed is 5
Enter your Choice :: 3
Contents of stack is 5 , 3 ,
Enter your Choice :: 2
Deleted element is 5
Enter your Choice :: 3
Contents of stack is 3 ,
Enter your Choice :: 8
Invalid Choice......
No comments:
Post a Comment