Write a stack program in C using an array. Implement a stack data structure using an Array. In this tutorial, You are going to learn about stack data structure and it’s implementation in C using an array.
C Program to Implement a Stack using Linked List
What is a Stack Data Structure?
A Stack is a Data Structure, in which insertion and deletion operations are allowed only at one end. It worked on LIFO (Last In First Out) Principle. In LIFO, an element which inserted last must be the first element to be removed.
In Stack, Insertion and Deletion operations are known as push and pop.
Push – To insert an element in a Stack.
Pop – To delete an element from a Stack.
MCQ on Stack and Queue Data Structure
There are certain conditions we need to check before push and pop operations. Before push operation, we need to check whether there is a sufficient space available for a new element. If memory is not available, then it’s called as Stack Overflow. Similarly in pop operation, if a stack is empty, then it’s called as Stack Underflow.
Where Stack Data Structure is Used
1. Stack data structure is used when a function is called.
2. To convert Infix to Postfix expression.
3. Evaluation of Postfix and Prefix expression.
4. In recursive function.
Stack Program in C using an Array
A stack can be implemented either through an array or a linked list. In this tutorial, We are going learn to implement a stack push and pop operation in C using an array. You can check my previous post on a C Program to Implement a Stack using Linked List.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
#include <stdio.h> #define MAX 50 int top = -1; int arr[MAX]; void push(int item){ /* If available memory is full. */ if(top == MAX-1){ printf("Stack Overflow"); return; }else{ /* Push the element in an array. */ arr[++top]=item; printf("Push value is %d\n",item); } } void pop(){ int val; if(top == -1){ printf("Stack underflow"); return; } else { val = arr[top]; --top; } printf( "Pop value is %d\n",val); } main() { int arr[MAX]; /*Push the values. */ push(2); push(4); push(6); // Pop the values pop(); pop(); pop(); } |
Output-
Push value is 2
Push value is 4
Push value is 6
Pop value is 6
Pop value is 4
Pop value is 2
Explanation –
In the above program, we have defined an array of size 50. In a push() method we have first checked the stack overflow (whether a memory is available for inserting an element) condition. After that, we have pushed the value in an array and increment the value of a top index.
Similarly, In a pop() method first, we checked stack underflow condition. After that, we have removed last pushed element and decremented the value of a top index.
Excellent Books for Data Structure