In C++ (old-style iostream.h), a function with a default argument is called once and computes a factorial-like product. Predict the printed result.
#include
long FactFinder(long = 5);
int main()
{
for (int i = 0; i <= 0; i++)
cout << FactFinder() << endl; // calls FactFinder(5)
return 0;
}
long FactFinder(long x)
{
if (x < 2)
return 1;
long fact = 1;
for (long i = 1; i <= x - 1; i++)
fact = fact * i; // multiplies up to x-1
return fact;
}
-
AThe program will print the output 1.
-
BThe program will print the output 24.
-
CThe program will print the output 120.
-
DThe program will print the output garbage value.
-
EThe program will report compile time error.
Answer
Correct Answer: The program will print the output 24.
Explanation
Introduction / Context: This question checks your understanding of default function arguments, loop bounds, and how an off-by-one choice in the loop makes the routine compute a product up to x - 1 rather than x. It also reinforces that the loop in main executes exactly once and calls the function with its default parameter value.
Given Data / Assumptions:
- Function prototype: long FactFinder(long = 5).
- Main calls FactFinder() once due to for (i = 0; i <= 0; i++).
- In FactFinder, if x < 2 return 1; otherwise multiply i from 1 to x - 1.
- Classic headers (iostream.h) are assumed to compile in the intended environment.
Concept / Approach: Because the call uses the default, x is 5. The function multiplies numbers from 1 through 4 (not 5). That computes 1 * 2 * 3 * 4 = 24. It then returns this value, which is printed by cout from main, followed by a newline.
Step-by-Step Solution:
In main: the loop runs exactly once and calls FactFinder() → x = 5.Check x < 2 → false; proceed to compute.Initialize fact = 1.Multiply for i = 1..4: fact = 11 → 1; then 12 → 2; then 23 → 6; then 64 → 24.Return 24; cout prints 24.Verification / Alternative check: If the loop were i <= x instead of i <= x - 1, the result would be 120 for x = 5. The present code intentionally stops early.
Why Other Options Are Wrong:
- The program will print the output 1.: This would require x < 2 or an empty product, which is not the case.
- The program will print the output 120.: That would need multiplication up to 5.
- The program will print the output garbage value.: All variables are initialized; no undefined reads occur.
- The program will report compile time error.: The code is valid in the assumed toolchain.
Common Pitfalls: Confusing default-argument usage, assuming factorial(x) instead of factorial(x - 1), or thinking the for loop in main runs multiple times. Also, overlooking that the code prints once because the loop bound is i <= 0.
Final Answer: The program will print the output 24.