Home »
Data Structure
Implement of stack using array
In this article, we are going to learn how to implement/create a stack using array in data structure?
Submitted by Manu Jemini, on December 17, 2017
A stack is a very important data structure because it can store data in a very practical way. A stack is a linear data structure. Stack array list follows the Last in First Out principle. The element gets to add up at the TOP and deleted from the TOP.
Image source: https://upload.wikimedia.org/wikipedia/commons/thumb/2/29/Data_stack.svg/391px-Data_stack.svg.png
In the Code below there are four parts. First three function to implement three different operations like Insert an item, delete an item and display the Stack. The Fourth part is the main function, in that a do while loop is implemented to keep the user engaged and provide him the all the given choices, according to the choice one of the three function get called.
The Push function checks whether the stack is full or not. If the stack is full it’s not do anything but if not it takes input from the user and push it to the top of the stack.
The Pop function checks whether the stack is empty, if not then it prints the topmost item and deletes it from the stack.
The Third function will simply print all the elements of the stack if exist. If not, then it will say stack is Empty.
Note - The Stack can hold only 5 items, for changing the capacity edit the second line.
Read more about algorithms and examples to implement stack in C and C++.
C language program to implement stack using array
#include<stdio.h>
#define MAX 5
int top = -1;
int stack_arr[MAX];
/*Begin of push*/
void push()
{
int pushed_item;
if(top == (MAX-1))
printf("Stack Overflow\n");
else
{
printf("Enter the item to be pushed in stack : ");
scanf("%d",&pushed_item);
top=top+1;
stack_arr[top] = pushed_item;
}
}
/*End of push*/
/*Begin of pop*/
void pop()
{
if(top == -1)
printf("Stack Underflow\n");
else
{
printf("Popped element is : %d\n",stack_arr[top]);
top=top-1;
}
}
/*End of pop*/
/*Begin of display*/
void display()
{
int i;
if(top == -1)
printf("Stack is empty\n");
else
{
printf("Stack elements :\n");
for(i = top; i >=0; i--)
printf("%d\n", stack_arr[i] );
}
}
/*End of display*/
/*Begin of main*/
main()
{
int choice;
do{
printf("1.Push\n");
printf("2.Pop\n");
printf("3.Display\n");
printf("4.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 :
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
break;
default:
printf("Wrong choice\n");
}}while(choice!=4);
}
/*End of main*/
Output