Stack implementation using Array

10 min read

Stack data structure implementation can be done using arrays and linked lists. Now, let us see the implementation of stacks using array.

Push and Pop operations in arrays

push() 

  • Check if the stack is full.
  • If the stack is full, then display "Stack overflow".
  • If the stack is not full, increment top to the next location.
  • Assign data to the top element.

Algorithm_push()

If TOP >= SIZE – 1 then  //  Stack Overflow indicating that the Stack is FULL.
TOP = TOP + 1
STACK [TOP] = ELEMENT

pop()

  • Check if the stack is empty.
  • If the stack is empty, then display "Stack Underflow".
  • If the stack is not empty, copy top in a temporary variable.
  • Decrement top to the previous location.
  • Delete the temporary variable.

Algorithm_pop()

If TOP = -1 then  //  Stack Underflow indicating that the Stack is EMPTY.
Return STACK [TOP]
TOP = TOP - 1

Now, let us see a program to show the array implementation of stack data structure.

C program to implement stacks using arrays

#include<stdio.h>
int stack[10],choice,n,top,x,i; // Declaration of variables

void push();
void pop();
void display();

int main()
{
top = -1; // Initially there is no element in stack
printf("\n Enter the size of STACK : ");
scanf("%d",&n);
printf("\nSTACK IMPLEMENTATION USING ARRAYS\n");
do
{
printf("\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT\n");
printf("\nEnter the choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
break;
}
default:
{
printf ("\nInvalid Choice\n");
}}}
while(choice!=4);
return 0;
}

void push()
{
if(top >= n - 1)
{
printf("\nSTACK OVERFLOW\n");

}
else
{
printf("Enter a value to be pushed : ");
scanf("%d",&x);
top++; // TOP is incremented after an element is pushed
stack[top] = x; // The pushed element is made as TOP
}}

void pop()
{
if(top <= -1)
{
printf("\nSTACK UNDERFLOW\n");
}
else
{
printf("\nThe popped element is %d",stack[top]);
top--; // Decrement TOP after a pop
}}

void display()
{
if(top >= 0)
{
// Print the stack
printf("\nELEMENTS IN THE STACK\n\n");
for(i = top ; i >= 0 ; i--)
printf("%d\t",stack[i]);
}
else
{
printf("\nEMPTY STACK\n");
}}


OUTPUT

Stack underflow when we try to pop an element from an empty stack

stack implementation using array underflow

Stack overflows when we try to push an element when the array is already full

stack implementation using arrays overflow

Displaying the elements in the stack

stack implementation using arrays display and pop

 

 
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error