Home › Learn › Java › Loops

for loops

Lesson 11 of 40. Repeat a block a counted number of times.

for (int i = 1; i <= n; i++) { ... } has three parts in the parentheses: what to do once before the loop (int i = 1), the condition checked before every round (i <= n), and what to do after every round (i++). The variable i exists only inside the loop. Counting down is for (int i = n; i >= 1; i--); stepping by two is i += 2.

A loop usually builds up a result in a variable declared before it: start int total = 0;, add to it inside, use it after. The off-by-one question is whether the condition is < or <=; say the last value you want out loud and check.

int total = 0;
for (int i = 1; i <= 4; i++) {
    total += i;
}
System.out.println(total);   // 10

Your task

Write static int sumTo(int n) returning 1 + 2 + ... + n (0 for n of 0), static long factorial(int n) returning 1 * 2 * ... * n (1 for 0; use long, since 20! does not fit an int), and static String countdown(int n) returning the numbers from n down to 1 separated by spaces, so countdown(3) is "3 2 1" (and "" for 0).

Hint 1

for (int i = 1; i <= n; i++) total += i; and product *= i in the same shape.

Hint 2

countdown: for (int i = n; i >= 1; i--) add i to the result, with a space before it when the result is not empty: if (!result.isEmpty()) result += " ";

Show the solution
public class Main {
    static int sumTo(int n) {
        int total = 0;
        for (int i = 1; i <= n; i++) {
            total += i;
        }
        return total;
    }

    static long factorial(int n) {
        long product = 1;
        for (int i = 2; i <= n; i++) {
            product *= i;
        }
        return product;
    }

    static String countdown(int n) {
        String result = "";
        for (int i = n; i >= 1; i--) {
            if (!result.isEmpty()) {
                result += " ";
            }
            result += i;
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(sumTo(10) + " " + factorial(5) + " " + countdown(3));
    }
}

    Compiles with OpenJDK javac and TeaVM, both compiled to WebAssembly (7 MB download the first time, then cached), and runs in this tab; nothing is sent anywhere.