basics · beginner · ~15 min
Accumulate a product in a loop.
Compute a factorial with a loop, accumulating a product.
Implement long factorial_iter(int n) that returns n! (the product 1 * 2 * ... * n) using a loop. By definition 0! == 1. Assume n >= 0. No main — the grader calls it.
A single non-negative int n.
Returns n!, as a long.
factorial_iter(0) -> 1
factorial_iter(1) -> 1
factorial_iter(5) -> 120
factorial_iter(6) -> 720
0! == 1 and 1! == 1 (the loop body simply never multiplies).A single non-negative int n.
n! as a long.
n >= 0; 0! == 1.
long factorial_iter(int n) {
/* TODO */
return 1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.