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
- Start
- Declare an array and a top variable initialized as -1
- For push operation: Increment 'top' and insert value at 'top' index
- For pop operation: Print the value at 'top' index and decrement 'top'
- 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