Representation of a Stack using Array | C++ Solution

Stack using an array in C++


Stack is one of the most important linear data structures, that we can use in different algorithms or implement the application in various problem solving. A stack is a linear data structure, that means it can be easily implememented using an array. You can use array to store some elements in the specific order you recieve them. Then you can use simple easy techniques to manage the data so that it can work like an Stack. Here we will go through the Representation of a Stack using Array.

Representation using an Array

There are some major differences between a stack and an array. like,

  • Array size is fixed, but the same isn’t applied for stack.
  • Also, in a stack you can only pop or push values only from or in the last element

Now let us focus on how we can implement a stack using an array.

For Example:

We are given a stack of elements:  2, 4, 3, 1, 5.

Step 1:

  • Push (5).
  •  Top of stack = 5
  • Element is inserted at a[4].

Step 2:

  • Push (1).
  •  Top of stack = 1
  • Element is inserted at a[3].

Step 3:

  • Push (4).
  •  Top of stack = 4
  • Element is inserted at a[2].
Stack using an array

Step 4:

  • Push (3).
  •  Top of stack = 3
  • Element is inserted at a[1].
Stack using an array

Step 5:

  • Push (2).
  •  Top of stack = 2
  • Element is inserted at a[0].
Stack using an array step 6

Code for Stack in C++ (using Class)

// Cpp Program for Implmentation of stack (array) using structure
using namespace std;

class Stack
    int top;
    int maxSize;
    int* array;
    Stack(int max)
        array=new int[max];
    int isFull()
        cout<<"Will not be able to push maxSize reached"<<endl;
        return top==maxSize-1;

    int isEmpty()
        cout<<"Will not be able to pop minSize reached"<<endl;
        return top==-1;
    void push(int item)
        if(isFull()) return;
        cout<<"We have pushed "<<item<<" to stack"<<endl;
    int pop()
        if(isEmpty()) return INT_MIN;
        return array[top--];
    int peek()
        if(isEmpty()) return INT_MIN;
        return array[top];

int main()
    Stack stack(10);
    int flag=1;
            cout<<"We have popped "<< stack.pop()<<" from stack"<<endl;
            cout<<"Can't Pop stack must be empty\n";



We have pushed 5 to stack                         
We have pushed 10 to stack
We have pushed 15 to stack
We have popped 15 from the stack
Do you want to Pop again? Yes: 1 No: 0
Representation of a stack using linked list

What is Stack?

Stack is a data structure where you can add any kind of and store then in a LIFO (last in first out) manner. To kno more about Stack in C++ STL :

Stack in C++ STL

suppose you push 2,3,4 in to the stack respectively. When you pop out a value, the last pushed value (4) will be deleted from it. Then if you try to see what is in the top of the stack, you will find its the second last value entered (2)

Article is contributed by Rahit Saha