basics · beginner · ~15 min

Iterative factorial

Accumulate a product in a loop.

Challenge

Compute a factorial with a loop, accumulating a product.

Task

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.

Input

A single non-negative int n.

Output

Returns n!, as a long.

Example

factorial_iter(0)   ->   1
factorial_iter(1)   ->   1
factorial_iter(5)   ->   120
factorial_iter(6)   ->   720

Edge cases

  • 0! == 1 and 1! == 1 (the loop body simply never multiplies).

Input format

A single non-negative int n.

Output format

n! as a long.

Constraints

n >= 0; 0! == 1.

Starter code

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.