How to implement Stack and realize various operations to be carried out on it.

avatar

word-image.png

AIM: To implement stack and realize various operations to be carried out on it.

Algorithm:

•START
•Declaring all functions that will be utilized in the stack implementation.
•Creating a one-dimensional array with fixed size
•Defining a integer variable top and initialize with -1
•Display a menu with a list of operations in the main method, then make
appropriate function calls to conduct the operation selected by the user on
the stack.

For Push:

1.Start
2.If TOP >= SIZE – 1
3.Print “Stack Overflow”
4.Else
5.TOP = TOP + 1
6.STACK [TOP] = ELEMENT
7.End if
8.Stop

For pop:

1.Start
2.If TOP <= -1
3.Print “Stack Underflow”
4.else
5.Return STACK [TOP]
6.TOP = TOP – 1
7.End

For Peek:

1.Start
2.If TOP <= -1
3.Print “Stack underflow”
4.else
5.Return STACK [TOP]
6.End

For Display:

1.Start
2.if TOP =0
3.Print “stack underflow”
4.else
5.For i= Top to 0
6.Print A[i]
7.End for
8.Stop

Code:

#include<stdio.h>
int stack[10],choice,n,top,x,i;
void push();
void pop();
void peek();
void display();
int main()
{
top = -1;
printf("\n Enter the size of STACK : ");
scanf("%d",&n);
printf("\n1.PUSH\n2.POP\n3.PEEK\n4.DISPLAY\n5.EXIT");
do
{
printf("\nEnter the choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
peek();
break;
}
case 4:
{
display();
break;
}
case 5:
{
printf("\nexiting\n");
break;
}
default:
{
printf ("\nInvalid Choice\n");
}
}
}
while(choice!=5);
return 0;
}
void push()
{
if(top >= n - 1)
{
printf("\nSTACK OVERFLOW\n");
}
else
{
printf("Enter a value to be pushed : ");
scanf("%d",&x);
top++;
stack[top] = x;
}
}
void pop()
{
if(top <= -1)
{
printf("\nSTACK UNDERFLOW\n");
}
else
{
printf("\nThe popped element is %d",stack[top]);
top--;
}}
void peek()
{
if(top <= -1)
{
printf("\nEmpty stack\n");
}
else
{
printf("\n the top element is %d",stack[top]);
}
}
void display()
{
if(top >= 0)
{
printf("\nELEMENTS IN THE STACK\n\n");
for(i = top ; i >= 0 ; i--)
printf("%d\t",stack[i]);
}
else
{
printf("\nEMPTY STACK\n");
}
}



0
0
0.000
0 comments