Mu Az
Mu Az

Reputation: 83

c++ how to print output of factorial program recursively

i want to ask a very simple question.
A simple c++ code to compute factorial of any number is as following:

rslt=1;
for(q=fctrl;q>=1;q--)
{
 rslt=rslt*q;
}
cout<<fctrl<<"! = "<<rslt;

A sample run of fctrl=4, the output is like this "4!=24"
I don't want it that way, instead i want it to print like this "4x3x2x1=24"

Can somebody help me please??

Upvotes: 1

Views: 524

Answers (2)

Nemanja Boric
Nemanja Boric

Reputation: 22157

First, you don't have recursive algorithm - this is iterative solution.

To achive what you want, just output the current loop variable inside it:

rslt=1;
for(q=fctrl;q>=1;q--)
{
   rslt=rslt*q;

   // output q
   cout << q;
   if(q != 1)
   {
       cout << "x";
   }
}
cout<<" = "<<rslt;

The condition if(q != 1) is there to prevent from writing an extra x at the end of the statement.

Upvotes: 1

yizzlez
yizzlez

Reputation: 8805

You could just modify your loop:

for(int q = factrl; q >= 1; q--){
    rslt = rslt * q;
    cout << q;
    if(q != 1) cout << "x";
}
cout << "=" << rslt << endl;

Upvotes: 1

Related Questions