Searching...
Friday 8 January 2016

Stack Data Structure Code example

23:13

Q:How to find fictorial,average and multiple of number by stack?

Ans: In this code example i tell you how to find fictorial,average and multiple of number by stack(LIFO) data structure in simple c++ code. You easily Understand it by some c++ concepts.

Code is:

#include<iostream>
using namespace std;
class stack{
int top;
int mul=1;
int sum=0;
int value;
int fac=1;
int array[5];
public:
stack(){
top=-1;
}
void push(){
if(top==4)
cout<<" stack is full !!";
else
{
cout<<"Enter the value=";
cin>>value;
array[++top]=value;
}
}
void pop(){
if(top==-1)
cout<<"Stack is empty !!";
else
{
cout<<"pop operation is done "<<array[top];
value=array[top--];
}
}
void print(){
if(top==-1)
cout<<"Stack is empty !!";
else
{
for(int i=0;i<=top;i++)
{
if(array[i]%2==0)
cout<<array[i]<<" Its is even !!";
else
cout<<array[i]<<" Its is odd !!";
sum=sum+array[i];
mul=mul*array[i];
fac=1;
for(int a=1;a<=array[i];a++)
{
fac=fac*a;
}
cout<<"Factorial of enter value is "<<fac<<endl;
} cout<<"Multi= "<<mul<<endl;
cout<<"Average of stack= "<<sum/(top+1)<<endl;
}
}
};
int main(){
stack obj;
int ch;
m:
cout<<endl<<"1 push"<<endl;
cout<<"2 pop"<<endl;
cout<<"3 print"<<endl;
cout<<"4 exit"<<endl;
cin>>ch;
switch(ch){
case 1:
obj.push();
goto m;
case 2:
obj.pop();
goto m;
case 3:
obj.print();
goto m;
case 4:
break;
default:
cout<<"invalid !!";
}
return 0;

}

0 comments:

Post a Comment