Search code examples
c++recursionfactorial

Recursively print Factorial values in decreasing order?


Using C++ to figure out the factorial is straightforward enough. To print the values coming up (if factorial is 5) ... 1 * 2, * 3, * 4 * 5 also no problem - as I think I've done below. But what I'm having a hard time doing is saying show me 5 * 4 then value * 3 then value * 2 etc. I want to be able to print the data going down and I can't seem to figure it out.

#include <iostream>
using namespace std;   

int factorial(int n);

int main()
{
   int number;

   cout << "Enter an integer value ";
   cin >> number;

   cout << "The factorial of " << number << " is ";
   cout << factorial(number) << endl;
}

int factorial(int n)
{
   if (n == 0)
      return 1;                    // Base case
   else
   {
      n = n * factorial(n - 1); // Recursive case
      cout << " going up" << n << " ";
      return n;
   }
}

There are a couple of other posts but I didn't find one asking the same thing. The desired results are: 20 60 120 The current results are 1 2 6 24 120 Please advise. Thank you.


Solution

  • Just change where you are printing the value

    else
       {
          n = n * factorial(n - 1); // Recursive case
          cout << " going up" << n << " ";
          return n;
       }
    

    to

    else
       {
          cout << " going down" << n << " ";    
          n = n * factorial(n - 1); // Recursive case
          return n;
       }
    

    The above would print 5 4 3 2 1 but if you want something like

    5 20 60 ...
    

    Than you have to change the recursive definition a bit.

    #include<iostream>
    
    using namespace std;
    int factorial(int n,int temp);
    int main()
    {
       int number;
    
       cout << "Enter an integer value ";
       cin >> number;
    
       cout << "The factorial of " << number << " is ";
       cout << factorial(number,1) << endl;
    }
    
    int factorial(int n,int temp)
    {
       if (n == 0)
          return temp;                    // Base case
       else
       {   
          cout << " going down" << n * temp << " ";
          factorial(n - 1,n*temp); // Recursive case
          //return n;
       }   
    }