1

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??

2 Answers 2

1

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;
1

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.

1
  • 1
    oh, so that's the story... i 've tried like this before but it keeps prompting the exrra x at the end. btw thanks a lot brother
    – Mu Az
    Nov 10, 2013 at 14:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.