CPP program to implement factorial of a number using stack.
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
class
stack
{private:
int top;
int para_n[100];
public:
void push(stack *,int);
void pop(stack *,int* );
double fact(int);
}s;
void
stack::push(stack *s,int d)
{ s->top++;
s->para_n[s->top]=d;
}
void
stack::pop(stack *s,int *d)
{ *d=s->para_n[s->top];
s->top--;
}
double
stack::fact(int n)
{ double res;
int
d;
d=n;
s.top=-1;
lab1:
if(d==0)
{ res=1;
goto
lab2;
}
else
{ push(&s,d);
d--;
goto
lab1;
}
lab2:
if(s.top>-1)
{ pop(&s,&d);
res*=d;
goto
lab2;
}
else
return
res;
}
void
main()
{ int num,c;
stack
k;
clrscr();
while(1)
{ clrscr();
do{
clrscr();
cout<<"\nTo
Find the factorial of a number\n\n";
cout<<"------------------------------------------\n";
cout<<"1.Enter
a number";
cout<<"\n2.Display
factorial";
cout<<"\n3.Exit
from the program";
cout<<"\n\nSelect
yourchoice _ ";
cin>>c;
}while((c<1)||(c>3));
if(c==3)exit(1);
switch(c)
{case
1 :
clrscr();
cout<<"\nEnter
your number ";
cin>>num;
break;
case
2 :
clrscr();
cout<<num<<"!="<<k.fact(num);
break;
}
cout<<"\n\nPress
any key to continue...........";
getch();
}
}
No comments:
Post a Comment