Factorial Output

Hi

I have the following code below that works. I however want the output to look different. How do i make the output look like so:
If the user enters the number 3, output:
factorial(3) returns 3*factorial(2)
factorial(2) returns 2*factorial(1)
factorial(1) returns 1

factorial(3) = 6


#include <iostream>

using namespace std;

unsigned long factorial(int number);

int main()
{
int x;
cout << "Enter a number" << endl;
cin >> x;

cout << "factorial (" << x << ") = " << factorial(x);
}

unsigned long factorial(int number)
{
if (number <= 1 )
return 1;
else
return number * factorial (number - 1);
}
Last edited on
You can put a cout statement (with a combination of text and the use of the number variable value) into the if and else sections of the factorial function before the return line.

factorial(3) returns 3*factorial(2)
text( number )text number text( number-1 text

The base case would be a shorter statement.
text( number )text
Thanks. My output is now:
factorial(3) returns 3*factorial(2)
factorial(2) returns 2*factorial(1)
factorial(1) returns 1*factorial (0)

Is it possible to make the last line display:
factorial(1) returns 1
instead.

Here'my new code:

#include <iostream>
using namespace std;

unsigned long factorial(int number);

int main()
{
int x;
cout << "Enter a number" << endl;
cin >> x;

cout << endl << "factorial (" << x << ") = " << factorial(x);
}
unsigned long factorial(int number)
{
if (number < 1 )
return 1;
else
cout << "factorial(" << number << ") returns " << number << "*factorial (" << (number-1) << ") " << endl;
return number * factorial (number - 1);
}
The base case would be a shorter statement.
text( number )text


Yes - that would go in the if part (base case of the recursion) of the function. It'll just be a shorter cout statement.

Don't forget to put curly braces now that you have multiple statements running in the if/else.
1
2
3
4
5
6
7
8
9
10
if
{
 do this
 and do that
}
else
{
 do this
 and do this
}
Oh okay I understand now. Thanks a lot! appreciate it!
Topic archived. No new replies allowed.