154k views
0 votes
C++ code-- Factorial Recursion

Write code to complete PrintFactorial()'s recursive case. Sample output if userVal is 5:
5! = 5 * 4 * 3 * 2 * 1 = 120
#include
using namespace std;

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;


}
}

int main() {
int userVal = 0;

userVal = 5;
cout << userVal << "! = ";
PrintFactorial(userVal, userVal);

return 0;
}

2 Answers

2 votes
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 ) );
}
User Thedric Walker
by
8.3k points
6 votes

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

}

}

Step-by-step 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);

}

}

User Makkes
by
8.3k points