In this program, we will see Stack Implementation in C Programming.
We shall see the stack implementation in the C programming language here.
The C Program is written for implementation of STACK
using Array, the basic operations of a stack are PUSH( )
, POP( )
and
DISPLAY( )
.
PUSH function in the code is used to insert an element to the top of the stack, the POP function used to remove the element from the top of the stack.
Finally, the display function used to print the values at any time. All stack functions are implemented in C Code.
Program to Implement Stack
#include <stdio.h> int MAXSIZE = 8; int stack[8]; int top = -1; int isempty() { if(top == -1) return 1; else return 0; } int isfull() { if(top == MAXSIZE) return 1; else return 0; } int peek() { return stack[top]; } int pop() { int data; if(!isempty()) { data = stack[top]; top = top - 1; return data; } else { printf("Could not retrieve data, Stack is empty.\n"); } } int push(int data) { if(!isfull()) { top = top + 1; stack[top] = data; } else { printf("Could not insert data, Stack is full.\n"); } } int main() { // push items on to the stack push(3); push(5); push(9); push(1); push(12); push(15); printf("Element at top of the stack: %d\n" ,peek()); printf("Elements: \n"); // print stack data while(!isempty()) { int data = pop(); printf("%d\n",data); } printf("Stack full: %s\n" , isfull()?"true":"false"); printf("Stack empty: %s\n" , isempty()?"true":"false"); return 0; }
Output
Element at top of the stack: 15 Elements: 15 12 1 9 5 3 Stack full: false Stack empty: true
Ask your questions and clarify your/others doubts about Stack Implementation by commenting. Documentation.
Please write to us at [email protected] to report any issue with the above content or for feedback.
Related Programs
- C Program to Compute Quotient and Remainder
- C Program to Find ASCII Value of a Character
- C Program to Swap Two Numbers
- C Program to Demonstrate the Working of Keyword long
- C Program to Find the Size of int, float, double and char
- C Program to Multiply two Floating Point Numbers
- C Program to implement Circular Linked List