write a C program for implementation of stack
Answers
Output
1. void push(int val) { if(top>=n-1) cout<<"Stack Overflow"<<endl; else { top++; stack[top]=val; } }
2. void pop() { if(top<=-1) cout<<"Stack Underflow"<<endl; else { cout<<"The popped element is "<< stack[top] <<endl; top--; } }
Answer:
Program stack using array in data structure in c programming.
#include<stdio.h>
#include<conio.h>
#define MAX 5
int a[MAX],top=-1;
void push();
void pop();
void display();
int main()
{
int ch;
printf("1.push or insert\n");
printf("2.pop or delete\n");
printf("3.display\n");
printf("4.end program\n");
while(1){
printf("\nEnter choice");
scanf("%d",&ch);
switch(ch){
case 1:{
push();
break;
}
case 2:{
pop();
break;
}
case 3:{
display();
break;
}
case 4:{
exit(0);}
default:
{
printf("wrong choice");
}}
}}
void push(){
int data;
if(top==MAX-1){
printf("\n overflow or stack is full");
}
else{
printf("enter element to be pushed:");
scanf("%d",&data);
top++;
a[top]=data;
}}
void pop(){
if(top==-1){
printf("underflow or stack is empty");
}
else{
printf("popped element: %d",a[top]);
top--;
}}
void display (){
int i;
if(top>0){
printf("elements:");
for(i=top;i>0;i--)
printf("\n %d",a[i]);
}
else{
printf("the stack is empty");
}}