The array is used to construct the stack through array implementation. Arrays are utilised for all stack-related tasks. Let's see how the array data structure can be used to implement each action on the stack.To understand the working procedure lets check the c code.
implement using array:
#include<stdio.h> int stack[100],i,j,choice=0,n,top=-1; void push(); void pop(); void show(); void main() { printf("enter the number of elements in the stack"); scanf("%d",&n); printf("******stack operations in the stack******"); printf("\n \n"); while(choice!=4) { printf("chose one of the operations"); printf("\n 1.push \n 2.pop \n 3.display \n 4.exit "); printf("\n enter your choice"); scanf("%d",&choice); switch(choice) { case 1: { push(); break; } case 2: { pop(); break; } case 3: { show(); break; } case 4: { printf("existing"); } default: { printf("please enter valid choices"); } }; } } void push() { int val; if(top==n) printf("\n overflow"); else { printf("enter the value"); scanf("%d",&val); top=top+1; stack[top]=val; } } void pop() { if(top==-1) printf("underflow"); else top=top-1; } void show() { for(i=top;i>0;i--) { printf("%d",stack[i]); } if(top==-1) { printf("stack is empty"); }}
output:
enter the number of elements in the stack4
stack operations in the stack:
chose one of the operations
1.push
2.pop
3.display
4.exit
enter your choice1
enter the value5
chose one of the operations
1.push
2.pop
3.display
4.exit
enter your choice1
enter the value8
chose one of the operations
1.push
2.pop
3.display
4.exit
enter your choice1
enter the value9
chose one of the operations
1.push
2.pop
3.display
4.exit
enter your choice1
enter the value7
chose one of the operations
1.push
2.pop
3.display
4.exit
enter your choice1
enter the value7
chose one of the operations
1.push
2.pop
3.display
4.exit
enter your choice1
overflowchose one of the operations
1.push
2.pop
3.display
4.exit
enter your choice3
7
7
9
8
chose one of the operations
1.push
2.pop
3.display
4.exit
enter your choice
0 Comments