# Stack using array
Stack is a data structure which follows LIFO i.e. Last-In-First-Out method.
The data/element which is stored last in the stack i.e. the element at top will be accessed first.
Both insertion & deletion takes place at the top.
When we implement stack uisng array we take the direction of the stack i.e the direction in which elements are inserted towards right.
Operations:
isempty()
- to check if the Stack is empty or not.push()
- to insert element in the Stack.pop()
- to delete element from stack.show_top()
- to display element at top.
Lets take an example of an array of 5 elements to implement stack. So we define the size of the array using pre-processor directive
#deifne SIZE 5
& then we can create an array of 5 elements asint A[SIZE];
Also we will declare atop
variable to track the element at the top of the stack which will initially be -1 when the stack is empty i.eint top=-1;
isempty()
- Now that we know that the stack is empty whentop
is equal to -1 we can use this to implement ourisempty()
function i.e. whentop == -1
retrun true else return false.push()
- To push an element into the stack we will simply incrementtop
by one and insert the element at that position. While inserting we have to take care of the condition when the array is full i.e.when top == SIZE-1;
pop()
- To pop an element from the stack we will simple decrementtop
by one which will simply mean that the element is no longer the part of the stack. In this case we have to take care of the condition when the stack is empty i.etop == -1
then we cannot perform the pop operation.show_top()
- we will simply print the element at top if the stack is not empty.Lets say we have an stack with one element i.e 2 and we have to insert ot push an element 3 to this stack.
- then we will simply increment top by one and push the element at top.
- And to pop an element we will simply decrement top by one.
# Source Code - C++
#include <iostream>
using namespace std;
#define SIZE 5
int A[SIZE];
int top = -1;
bool isempty()
{
if(top==-1)
return true;
else
return false;
}
void push(int value)
{
if(top==SIZE-1)
{ cout<<"Stack is full!\n";
}
else
{
top++;
A[top]=value;
}
}
void pop()
{
if(isempty())
cout<<"Stack is empty!\n";
else
top--;
}
void show_top()
{
if(isempty())
cout<<"Stack is empty!\n";
else
cout<<"Element at top is: "<<A[top]<<"\n";
}
void displayStack()
{
if(isempty())
{
cout<<"Stack is empty!\n";
}
else
{
for(int i=0 ; i<=top; i++)
cout<<A[i]<<" ";
cout<<"\n";
}
}
int main()
{
int choice, flag=1, value;
while( flag == 1)
{
cout<<"\n1.PUSH 2.POP 3.SHOW_TOP 4.DISPLAY_STACK 5.EXIT\n";
cin>>choice; switch (choice)
{
case 1: cout<<"Enter Value:\n";
cin>>value;
push(value);
break;
case 2: pop();
break;
case 3: show_top();
break;
case 4: displayStack();
break;
case 5: flag = 0;
break;
}
}
return 0;
}
Time Complexity - Each operation is O(1)
Learn More
- Stack using array