Respuesta :
Handle the print outside of the factorial function, which only needs one userVal when called.
int factorial( int foo )
{
if( foo == 1 )
return 1;
else
return( foo * factorial( foo - 1 ) );
}
int factorial( int foo )
{
if( foo == 1 )
return 1;
else
return( foo * factorial( foo - 1 ) );
}
Answer:
void PrintFactorial(int factCounter, int factValue){
int nextCounter = 0;
int nextValue = 0;
if (factCounter == 0) { // Base case: 0! = 1
cout << "1" << endl;
}
else if (factCounter == 1) { // Base case: Print 1 and result
cout << factCounter << " = " << factValue << endl;
}
else { // Recursive case
cout << factCounter << " * ";
nextCounter = factCounter - 1;
nextValue = nextCounter * factValue;
printFactorial(nextCounter, nextValue);
}
}
Explanation:
The only things that is left is calling the recursive function in the else statement. It is the bolded command on the answer.
factCounter is the value we are multiplying. In the function, it is nextCounter. So for 5, it is 5, then 4, then 3, until 0...
factValue is the value of the factorial. In the function, it is nextValue So it is 5, then 5*4 = 20, then 5*4*3 = 60, then...
void PrintFactorial(int factCounter, int factValue){
int nextCounter = 0;
int nextValue = 0;
if (factCounter == 0) { // Base case: 0! = 1
cout << "1" << endl;
}
else if (factCounter == 1) { // Base case: Print 1 and result
cout << factCounter << " = " << factValue << endl;
}
else { // Recursive case
cout << factCounter << " * ";
nextCounter = factCounter - 1;
nextValue = nextCounter * factValue;
printFactorial(nextCounter, nextValue);
}
}