In this program, we are going to share how to perform stack operations using C programming language. If you are a beginner and want to start learning the C programming, then keep your close attention in this tutorial as I am going to share a C program to perform stack operations.
Copy the below C program and execute it with the help of C compiler.
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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
#include<stdio.h> #include<conio.h> #include<stdlib.h> #define MAX 50 int size; struct stack { int arr[MAX]; int top; }; void init_stk(struct stack *st) { st->top = -1; } void push(struct stack *st, int num) { if (st->top == size - 1) { printf("\nStack overflow(i.e., stack full)."); return; } st->top++; st->arr[st->top] = num; } int pop(struct stack *st) { int num; if (st->top == -1) { printf("\nStack underflow(i.e., stack empty)."); return NULL; } num = st->arr[st->top]; st->top--; return num; } void display(struct stack *st) { int i; for (i = st->top; i >= 0; i--) printf("\n%d", st->arr[i]); } int main() { int element, opt, val; struct stack ptr; init_stk(&ptr); printf("\nEnter Stack Size :"); scanf("%d", &size); while (1) { printf("\n\ntSTACK PRIMITIVE OPERATIONS"); printf("\n1.PUSH"); printf("\n2.POP"); printf("\n3.DISPLAY"); printf("\n4.QUIT"); printf("\n"); printf("\nEnter your option : "); scanf("%d", &opt); switch (opt) { case 1: printf("\nEnter the element into stack:"); scanf("%d", &val); push(&ptr, val); break; case 2: element = pop(&ptr); printf("\nThe element popped from stack is : %d", element); break; case 3: printf("\nThe current stack elements are:"); display(&ptr); break; case 4: exit(0); default: printf("\nEnter correct option!Try again."); } } return (0); } |
Liked this program? Do Like & share with your friends 🙂
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: C Program to Implement a Stack, program to implement stack, Stack is a LIFO data structure, Stack is a LIFO data structure programs, Stack operations: PUSH(insert operation, What is stack and its operations, What is the stack memory, What is the structure of a stack