C++ program for stack implementation using array
#include <iostream>
using namespace std;
int stack [100],n=100,top=-1;
void push (int val)
{
if (top>=n-1)
cout<<"stack overflow";
else{
top++;
stack[top]=val;
}
}
void pop(){
if (top==-1)
cout<<"stack underflow";
else{
cout<<"deleted element="<<stack[top];
top--;
}
}
void display()
{
if(top>=0){
cout<<"stack elements are";
for(int i=top; i>=0; i--)
cout<<stack[i];
}
else
cout<<"stack is empty";
}
int main(){
int ch,val;
cout<<"1.push in stack\n";
cout<<"2.pop from stack\n";
cout<<"3.display stack\n";
cout<<"4.exit\n";
do
{cout<<"\nenter a choice \n";
cin>>ch;
switch(ch){
case 1:{cout<<"enter elements insult\n";
cin>>val;
push(val);
break;
}
case 2: {pop();
break;}
case 3:{display();
break;}
case 4:{cout<<"exit";
break;}
default:{cout<<"invalid choice ";}
}
}
while(ch!=4);
return 0;
}
Stack program c++ updated
#include <iostream>
using namespace std;
int stack [100],n=100,top=-1;
void push (int val)
{
if (top>=n-1)
cout<<"stack overflow";
else{
top++;
stack[top]=val;
}
}
void pop(){
if (top==-1)
cout<<"stack underflow";
else{
cout<<"deleted element="<<stack[top];
top--;
}
}
void display()
{
if(top>=0){
cout<<"stack elements are\n" ;
for(int i=top; i>=0; i--)
cout<<"\n"<<stack[i];
}
else
cout<<"stack is empty";
}
int main(){
int ch,val;
cout<<"1.push in stack\n";
cout<<"2.pop from stack\n";
cout<<"3.display stack\n";
cout<<"4.exit\n";
do
{cout<<"\nenter a choice \n";
cin>>ch;
switch(ch){
case 1:{cout<<"\nenter elements insult";
cin>>val;
push(val);
break;
}
case 2: {pop();
break;}
case 3:{display();
break;}
case 4:{cout<<"exit";
break;}
default:{cout<<"invalid choice ";}
}
}
while(ch!=4);
return 0;
}
Comments
Post a Comment