Stack using Array in C
Here you will get code to learn the Stack using Array in C programming using data structure.
Stack using Array
In computer science, a stack is a linear data structure that follows to the Last-In-First-Out (LIFO) concept. It stores and manages a collection of elements where items are added and removed from one end, called the top. Common operations on a stack include push (add) and pop (remove) operations.
Algorithm for Stack using Array
1. Create a fixed-size array to store stack elements.
2. Initialize a variable ‘top’ to -1 to represent an empty stack.
3. Define functions for basic stack operations:
– Push(item): Increment ‘top’ and add ‘item’ to the array at the ‘top’ index.
– Pop(): Return the element at the ‘top’ index and decrement ‘top’.
– IsEmpty(): Check if ‘top’ is -1 to determine if the stack is empty.
– IsFull(): Check if ‘top’ is equal to the maximum array size minus one.
4. Optionally, define a function ‘Peek()’ to retrieve the top element without removing it.
5. Use these operations to manipulate the stack as needed.
Program code Stack using Array in C
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 | //Stack using Array in C #include<stdio.h> #include<conio.h> #include<stdlib.h> #include<ctype.h> #define size 2 int stack[size],top=-1,b,res; void push(); void pop(); void display(); main() { int c; //clrscr(); printf("1.Push\n"); printf("2.Pop\n"); printf("3.Display\n"); printf("4.Exit\n"); do { printf("\n Enter your choice: "); scanf("%d",&c); switch(c) { case 1: push(); break; case 2: pop(); break; case 3: printf("\nContents of stack : "); display(); break; default: exit(1); } } while(c<4); getch(); } void push() { if(top>=size) { printf("\nStack is overflow"); return; } else { printf("\nEnters the number to be pushed : "); scanf("%d",&b); top++; stack[top]=b; //printf("\nNumber pushed: %d",stack[top]); return; } } void pop() { if (top==-1) { printf("\nStack is overflow"); return; } else { res=stack[top]; top--; printf("\nDeleted one is %d ",res); return; } } void display() { int i; if(top==-1) { printf("\nStack is overflow"); return; } for(i=top;i>=0;i--) { printf("%d\t",stack[i]); } } |
Output
1.Push
2.Pop
3.Display
4.Exit
Enter your choice: 1
Enters the number to be pushed : 10
Enter your choice: 1
Enters the number to be pushed : 20
Enter your choice: 1
Enters the number to be pushed : 30
Enter your choice: 3
Contents of stack : 30 20 10
Enter your choice: 2
Deleted one is 30
Enter your choice: 3
Contents of stack : 20 10
Enter your choice: 4