The following program segment calculates and displays the factorial of a number. [Example: Factorial of 5 is 1 x 2 x 3 x 4 x 5 = 120] int p, n = 5, f = 0; for(p = n; p > 0; p--) f *= p; System.out.println(f); Name the type of error if any; correct the statement to get the desired output.
Topic: Types of errors
Answer
Type of error: Logical error.
The accumulator f is initialised to 0, and since factorial is built by MULTIPLICATION, every product becomes 0 — the segment prints 0 instead of 120.
Corrected statement: int p, n = 5, f = 1; for(p = n; p > 0; p--) f *= p; System.out.println(f);
Answer in two parts: name the error, then give the corrected line. This is a logical error — the program compiles and runs perfectly, but produces the wrong answer. Contrast it with a syntax error (caught by the compiler) or a runtime error (crashes during execution). The rule to carry away: an accumulator built by ADDITION starts at 0, but one built by MULTIPLICATION must start at 1, because 0 times anything stays 0. Only the initialisation of f changes; the loop itself is correct and counts down 5, 4, 3, 2, 1 giving 120.