Write a C Program to Implement Stack using Array

Write a C Program to Implement Stack using Array

The stack is first in last out data structure to store the elements. Elements are accessed by push pop operations. Push operation adds a new element in the stack at the top, whereas pop operation deletes the topmost element from the stack. The stack can be implemented using array. Stack using array is the easiest way to understand, how stack actual work.

To implement the stack using array, we need to keep track of the topmost element in the array.

In this program, we have written two functions namely push, and pop that will work as push, pop operation in the stack using array.

Difficulty Level: Low

Operations to be performed on Stack using Array:

Push Operation on Stack: 

Add the new element at the top of the stack.

Pop Operation on Stack:

Read and delete topmost elements from the stack.

Stack Overflow:
If the number of elements in the stack exceeds, a stack overflow occurs.

Stack Underflow: 

While performing the pop operation on the stack, if there is no more element to pop, stack underflow occurs.

Code to implement Stack using Array

#include<stdio.h>

int nTop=-1;
int *pStack = NULL;
/*
nTop: To refer topmost element in array.

pStack: pointer to array that 
can be implemented as stack pointer
*/
/*
Push new element 
at the top of linked list
*/
void push(int n)
{
  printf("\nPush element: %d", n);
  if(nTop>9)
  printf("Overflow");
  else
  {
    nTop++;
    pStack[nTop] = n;
  }
}
/*
Pop topmost element 
from stack
*/

void pop()
{
  printf("\nPop topmost element");
  if(nTop<0)
  printf("\nUnderflow");
  else
  {
    pStack[nTop] = -1;
    nTop--;
   }
}

void DisplayStack()
{
  int i=0;
  if(nTop<0)
  printf("\nStack is empty");
  else
  {
    printf("\nDisplay Stack: ");
    for(; i<=nTop;i++)
    printf("%d ", pStack[i]);
  }
}

int main()
{
  int nSize=10;
  /*
    allocate dynamic memory of size 10 int
    to store 10 elements 
  */
  pStack = (int *)malloc(sizeof(int)*10); 
	
  push(10);
  push(12);
  DisplayStack();
  pop();
  DisplayStack();
  push(45);
  push(24);
  push(12);
  DisplayStack();
  pop();
  pop();
  DisplayStack();
}

Output:

Push element: 10
Push element: 12
Display Stack: 10 12
Pop topmost element
Display Stack: 10
Push element: 45
Push element: 24
Push element: 12
Display Stack: 10 45 24 12
Pop topmost element
Pop topmost element
Display Stack: 10 45

The stack can be implemented from the linked list, but stack using an array is the easiest way to understand and implement. I will write code to implement a stack using a linked list in the upcoming article.

Other similar Program: Implement Linked List in C

For any questions, feel free to use the comment section below.

Stay tuned!

4 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *