Skip to content
Home » Operations on stack using arrays in C

Operations on stack using arrays in C

Below is the code to perform operations on stack using arrays.

#include <stdio.h>
#include <stdlib.h>
#define n 5
int top=-1;
int stack[5];
int value;
int isEmpty(){
if(top==-1){
return 1;
}else{
return 0;
}
}
int isFull(){
if(top==n-1){
return 1;
}else{
return 0;
}
}
void push(int data){
if(isFull()){
printf("Overflow");
}else{
top+=1;
stack[top]=data;
}
}
int pop(){
if(isEmpty()){
printf("Underflow");
}else{
value=stack[top];
top--;
}
return value;
}
int peek(){
//int value;
if(isEmpty()){
printf("Underflow");
}else{
value=stack[top];
}return value;
}
void print(){
if(isEmpty()){
printf("Underflow");
}else{
for(int i=0;i<=top;i++){
printf("%d ",stack[i]);
}
}
}
int main(){
int choice,data;
while(1){
printf("\n1.Insert element\n2.Delete element\n3.Top value\n4.Display elements\n5.Exit");
printf("\nEnter your choice:");
scanf("%d",&choice);
switch(choice){
case 1:
printf("\nEnter element to be inserted:");
scanf("%d",&data);
push(data);
break;
case 2:
data=pop();
printf("\nDeleted element is %d",data);
break;
case 3:
data=peek();
printf("\nTop value is %d",data);
break;
case 4:
printf("\nElements in the stack: ");
print();
break;
case 5:
exit(1);
default:
printf("\nEnter valid choice....");
break;
}
}
}

OUTPUT:

1.Insert element
2.Delete element
3.Top value
4.Display elements
5.Exit
Enter your choice:1

Enter element to be inserted:35

1.Insert element
2.Delete element
3.Top value
4.Display elements
5.Exit
Enter your choice:1

Enter element to be inserted:45

1.Insert element
2.Delete element
3.Top value
4.Display elements
5.Exit
Enter your choice:3

Top value is 45
1.Insert element
2.Delete element
3.Top value
4.Display elements
5.Exit
Enter your choice:4

Elements in the stack: 35 45
1.Insert element
2.Delete element
3.Top value
4.Display elements
5.Exit
Enter your choice:2

Deleted element is 45
1.Insert element
2.Delete element
3.Top value
4.Display elements
5.Exit
Enter your choice:5