Fix the program
This program is supposed to output the factorial of 5. However, the function factorial is flawed.
The flaw is causing it to infinitely loop.
Analyze the program and fix the function.
#include <iostream>
unsigned long long factorial(int N)
{
if (N == 1)
return 1;
return N * factorial(N);
}
int main()
{
std::cout << "Factorial of 5: " << factorial(5) << "\n";
}
Hint
The value of N is never changed.
This leads to it never reaching 1, which is the condition for reaching the base case.
Answer
#include <iostream>
unsigned long long factorial(int N)
{
if (N == 1)
return 1;
return N * factorial(N-1);
}
int main()
{
std::cout << "Factorial of 5: " << factorial(5) << "\n";
}
Changing
factorialcall insidefactorialto passN-1instead of justNmakes sure thatNeventually reaches 1, preventing the loop from continuing forever.