C++ Program To Implement Stack Using Array
C++ Program To Implement Stack Using Array
A stack is an abstract data structure that contains a collection of elements. Stack implements the
LIFO mechanism i.e. the element that is pushed at the end is popped out first. Some of the
principle operations in the stack are −
Example:
#include <iostream>
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
void pop() {
if(top<=-1)
cout<<"Stack Underflow"<<endl;
else {
void display() {
if(top>=0) {
cout<<stack[i]<<" ";
cout<<endl;
} else
cout<<"Stack is empty";
int main() {
cout<<"4) Exit"<<endl;
do {
cin>>ch;
switch(ch) {
case 1: {
cin>>val;
push(val);
break;
case 2: {
pop();
break;
}
case 3: {
display();
break;
case 4: {
cout<<"Exit"<<endl;
break;
default: {
cout<<"Invalid Choice"<<endl;
}while(ch!=4);
return 0;
In the above program, the push() function takes argument val i.e., value to be pushed into the
stack. If a top is greater than or equal to n,there is no space in a stack and overflow is printed.
Otherwise, val is pushed into the stack. The code snippet for this is as follows.
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
The pop() function pops the topmost value of the stack, if there is any value. If the stack is empty
then underflow is printed. This is given as follows.
void pop() {
if(top<=-1)
cout<<"Stack Underflow"<<endl;
else {
top--;
The display() function displays all the elements in the stack. It uses a for loop to do so. If there are
no elements in the stack, then Stack is empty is printed. This is given below.
void display() {
if(top>=0) {
cout<<stack[i]<<" ";
cout<<endl;
}else
cout<<"Stack is empty";
The function main() provides a choice to the user if they want to push, pop or display the stack.
According to the user response, the appropriate function is called using switch. If the user enters
an invalid response, then that is printed.
1. Write a program that converts a decimal integer value into binary and displays the result
on the screen. For example, if the number is 3 then the result should be displayed as (11)2.
Use the stack technique to store the remainder of each step of division and pop the values
from stack and display on the screen.
2. Write a program that reverses an input string using stack and displays the result on the
screen. For example, if the input string is "ABCXYZ", it should be displayed as ZYXCBA