Stack using fixed size array

Stack is one of the data structure that uses LIFO (Last In First Out) or FILO (First In Last Out) property i.e. element which is stored in last, will be out (read) first.
Real life example of stack is stack of plates. Last plate put over the plates is the first plate that is removed or used.

#include <iostream>
using namespace std;
const int MAX_INDEX = 50;  // Maximum index of array.
const int MIN_INDEX  = -1; // Minimum index  of array.

class stack
{
private:
unsigned int arr[MAX_INDEX];
int top;
public:
stack()
{
top = MIN_INDEX;
}
~stack()
{
top = MIN_INDEX;
}
void push(unsigned int data)
{
if ((top + 1)>= MAX_INDEX)
{
cout << “Stack is full” << endl;
return;
}
arr[++top] = data;
}
int pop()
{
if (top <= MIN_INDEX)
{
return MIN_INDEX;
}
return arr[top--];
}

bool isEmpty()
{ return (top == MIN_INDEX);
}

void display()
{
while(top)
{
cout << "Element: " << arr[top--] << endl;
}
}
};

int main()
{
stack s1;
s1.push(10);
s1.push(15);
s1.push(20);
cout <<"Element: " << s1.pop() << endl;
cout <<"Element: " << s1.pop() << endl;
cout <<"Element: " << s1.pop() << endl;
cout <<"Element: " << s1.pop() << endl;
return 0;
}

 

Ouput:
20
15
10
-1

The program is a stack implementation using fixed size array.

Maximum number of elements that can be stored in stack is 50 represented by MAX_INDEX.

In main function, three elements are pushed in to stack. Once maximum number (MAX_INDEX) of elements are pushed in to stack, then pushing of one more element results in stack overflow.

top indicates the top position of stack.

Every time an element is pushed, first top is increment by one, and then element is put in to stack.

Similarly, when element is pop from stack, element is retrieved or read first and then top is decremented by one.

Once the stack is empty, program return -1 i.e. MIN_INDEX for pop function that indicates empty stack or sometime it is called stack underflow.

Related posts