Stack Implementation using Array: CSU1051P - Shoolini U | Efficient Data Stack Operations with dmj.one

Implementation of Stack Using Array

To understand the implementation of a stack using an array using C++

Objective

To understand the implementation of a stack using an array using C++

#include <iostream>
using namespace std;
#define MAX 5

int stack[MAX];
int top = -1;

void push(int val) {
    if(top >= MAX-1) {
        cout << "Stack Overflow" << endl;
    } else {
        stack[++top] = val;
        cout << "Pushed " << val << endl;
    }
}

void pop() {
    if(top < 0) {
        cout << "Stack Underflow" << endl;
    } else {
        cout << "Popped " << stack[top--] << endl;
    }
}

int main() {
    push(5);
    push(4);
    push(3);
    pop();
    pop();

    return 0;
}

Discussion of Algorithm

  1. Start
  2. Declare an array and a top variable initialized as -1
  3. For push operation: Increment 'top' and insert value at 'top' index
  4. For pop operation: Print the value at 'top' index and decrement 'top'
  5. End

Representations

Flow Diagram

   +----------------------------------+
   |                                  |
   |           Start                  |
   |             |                    |
   +----------------------------------+
                  |
                  V
   +----------------------------------+
   |                                  |
   |         Push operations          |
   |             |                    |
   +----------------------------------+
                  |
                  V
   +----------------------------------+
   |                                  |
   |         Pop operations           |
   |             |                    |
   +----------------------------------+
                  |
                  V
   +----------------------------------+
   |                                  |
   |             Exit                 |
   |             |                    |
   +----------------------------------+

Tabular Dry Run

Push | Pop
 5   |   
 4   |  
 3   |  
     |  3
     |  4

Results/Output

Pushed 5
Pushed 4
Pushed 3
Popped 3
Popped 4