8. Program for implementing Stack in an array?
Algorithm
Define
MAX as 3,Declare top=-1.
Step
1:Start
Step
2:Declare a[MAX],ch.
Step3:while(ch==’Y’)
repeat steps 3.1 to 3.6
3.1)Print the Menu 1.PUSH
2.POP 3.DISPLAY
3.2)Input and read the
choice,ch.
3.3)If ch==1 then call the
function push(a).
3.4)Else if ch==2 then call
the function pop(a).
3.5)Else if ch==3 then call
the function disp(a).
3.6)Else print “invalid key
pressed”.
Step
4:End while.
Step
5:Stop.
Function
push(a)
Step
1:Declare variable ele.
Step
2:If(top=MAX-1) then
2.1)print STACK OVERFLOW.
Step
3:Else
3.1)Input and read the
element to be inserted,ele.
3.2)Increment ‘top’ by 1.
3.3)Assign a[top]=ele
Step
4:End if
Step
5:Return.
Function
pop(a)
Step
1:If (top=-1) then
1.1)Print STACK UNDERFLOW.
Step
2:Else
2.1)Print the popped
element,a[top].
2.2)Decrement ‘top’ by 1.
Step
3:End if.
Step
4:Return.
Function
disp(a)
Step
1:Declare variable i.
Step
2:If (top= -1)
2.1)Print the stack is
empty.
Step
3:Else
3.1)Initialize i as 0.
3.2)while(i<=top)
repeat step a and b.
a)Print
the element,a[i].
b)Increment i by 1.
3.3)End while.
Step
4:End if.
Step
5:Return.
Program
#include<stdio.h>
#include<conio.h>
#define
MAX 3
int
top=-1;
void
push(int a[])
{
int ele;
if(top==MAX-1)
printf("\nStack Overflow\n Delete Some elements");
else {
printf("\nEnter the element to insert :");
scanf("%d",&ele);
++top;
a[top]=ele;
printf("\nElement pushed successfully\n");
}
}
void
pop(int a[])
{
if(top==-1)
printf("Stack Underflow \nInsert some elements & pop");
else {
printf("Element popped is %d",a[top]);
top--;
}
}
void
disp(int a[])
{
int i;
if(top==-1)
printf("Stack Empty");
else
{
printf("Elements of stack are \n");
for(i=0;i<=top;i++)
{
printf("%d\t",a[i]);
}
}
}
void
main()
{
int a[MAX],ch;
do {
clrscr();
printf("1.PUSH\t2.POP\t3.DISPLAY\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
push(a);
break;
case 2:
pop(a);
break;
case 3:
disp(a);
break;
default:
printf("\nInvalid key pressed");
}
printf("\nContinue (Y/N)");
scanf(" %c",&(char)ch);
}while(ch=='Y'||ch=='y');
getch();
}
Output
1.PUSH 2.POP 3.DISPLAY
1
Enter
the element to insert :10
Element
pushed successfully
Continue
(Y/N) y
1.PUSH 2.POP 3.DISPLAY
1
Enter
the element to insert :11
Element
pushed successfully
Continue
(Y/N) y
1.PUSH 2.POP 3.DISPLAY
1
Enter
the element to insert :12
Element
pushed successfully
Continue
(Y/N) y
1.PUSH 2.POP 3.DISPLAY
1
Stack
Overflow
Delete
Some elements
Continue
(Y/N) y
1.PUSH 2.POP 3.DISPLAY
3
Elements
of stack are
10 11
12
Continue
(Y/N) y
1.PUSH 2.POP 3.DISPLAY
2
Element
popped is 12
Continue
(Y/N) y
1.PUSH 2.POP 3.DISPLAY
2
Element
popped is 11
Continue
(Y/N) y
1.PUSH 2.POP 3.DISPLAY
2
Element
popped is 10
Continue
(Y/N) y
1.PUSH 2.POP 3.DISPLAY
2
Stack
Underflow
Insert
some elements & pop
Continue
(Y/N) y
1.PUSH 2.POP 3.DISPLAY
3
Stack
Empty
Continue
(Y/N) N
No comments:
Post a Comment