Home › Learn › Java › Loops

break and continue

Lesson 13 of 40. Leave a loop early, or skip one round.

break leaves the loop immediately; continue skips the rest of the current round and goes on to the next one. break is how a search stops at the first hit instead of scanning everything; continue is how a loop steps over the cases it does not want without wrapping the whole body in an if.

Both apply to the innermost loop they sit in. A while (true) loop with a break inside is a common shape for "keep going until something happens in the middle of the body".

for (int i = 2; i < 100; i++) {
    if (n % i == 0) {
        System.out.println("divisible by " + i);
        break;
    }
}

Your task

Write static int smallestDivisor(int n) returning the smallest whole number greater than 1 that divides n (for a prime, that is n itself; assume n is at least 2), using break. Then write static int sumOfOdds(int limit) returning the sum of the odd numbers from 1 to limit, skipping the even ones with continue.

Hint 1

for (int i = 2; i <= n; i++) { if (n % i == 0) { found = i; break; } }

Hint 2

for (int i = 1; i <= limit; i++) { if (i % 2 == 0) continue; sum += i; }

Show the solution
public class Main {
    static int smallestDivisor(int n) {
        int found = n;
        for (int i = 2; i <= n; i++) {
            if (n % i == 0) {
                found = i;
                break;
            }
        }
        return found;
    }

    static int sumOfOdds(int limit) {
        int sum = 0;
        for (int i = 1; i <= limit; i++) {
            if (i % 2 == 0) {
                continue;
            }
            sum += i;
        }
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(smallestDivisor(91) + " " + sumOfOdds(10));
    }
}

    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.