Loops in Java — exercises with vowels, grades up to -1 and primes in a range (and the loop that once froze on me)

The first loop I wrote in Java froze. No error, no exception: the terminal started filling up with “Round 0”, “Round 0”, “Round 0″… so fast you couldn’t read it, and the laptop fan started sounding like a hair dryer. I had to stop it with Ctrl + C. The bug was a line that wasn’t there: the i++ that moves the loop on. The condition i < 5 was true at the start and stayed true forever, because nothing changed it. You’ll see it with its real output (and a brake so it doesn’t fill the page) in “What’s wrong here?”.

Here are three Java loop exercises, from easier to harder: counting the vowels in a sentence (walking through a text with for and a switch inside), asking for grades until a -1 arrives (sentinel, accumulators, maximum and minimum without storing the grades) and finding the primes in a range (nested loops with break). As in the loops practice, everything typed comes from Scanner and there are no arrays. At the end you have the exam-style quiz and the cheat sheet.

How to use this article

  1. Read the statement and the expected output of each exercise. The output is real: if your program prints the same with the same data, you’re on the right track.
  2. Try it without looking at anything for at least 15 minutes. If you get stuck, open the hint.
  3. Before the solutions, do “What’s wrong here?”: three fragments with one bug each. Predict what they print before reading the explanation.
  4. Compare your solution with the commented one. Make a trace table of two or three rounds: it’s the fastest way to find where the two part ways.

The outputs come from a single run with Java 21 on a computer set to Spanish: decimals are typed with a comma (7,5 instead of 7.5) and printf prints one too; on a computer set to English you’d use a point. What appears after each question is what was typed; the words typed in are Spanish, and the counts depend on their letters. In the site’s Java playground the typed data goes in the Input tab, one line per value.

Every Java topic of FP2, in order and with its quiz, is in the solved Java exercises.

Basic level

Exercise 1 — Vowel counter

Write VowelCounter: it asks for a word or sentence and counts how many times each vowel appears, the total and which one is the most repeated (on a tie, the first in the order a, e, i, o, u). Upper case doesn’t matter, and accented vowels count as their vowel (á is an a). If there are none, it says so.

Expected output with programacion (Spanish for “programming”):

=== VOWEL COUNTER ===
Word or sentence: programacion
--- Result ---
a: 2  e: 0  i: 1  o: 2  u: 0
Total vowels: 5
Most repeated: a (2 times)

With capitals and accents (“Programación en Java”):

=== VOWEL COUNTER ===
Word or sentence: Programación en Java
--- Result ---
a: 4  e: 1  i: 1  o: 2  u: 0
Total vowels: 8
Most repeated: a (4 times)

With no vowels:

=== VOWEL COUNTER ===
Word or sentence: FP2 xyz 2026
--- Result ---
a: 0  e: 0  i: 0  o: 0  u: 0
Total vowels: 0
No vowels.

Lowercase the text once, before the loop. Walk through it with for (int k = 0; k < text.length(); k++) (you’ll want to keep i for the counter of the vowel i) and inside, a switch on text.charAt(k) with arrows: case 'a', 'á' -> a++;. For the most repeated, start by assuming it’s a and compare it with the others using >. Check by hand: “programacion” has two o, two a and one i.

Intermediate level

Exercise 2 — Grades with a sentinel value

Write SentinelGrades: it asks for grades one by one (with decimals) until -1 is typed, which isn’t a grade but the signal that you’ve finished. Grades outside 0-10 are rejected with a warning and don’t count. At the end, it shows how many grades there are and how many passed, the average with two decimals, the maximum and the minimum, without storing the grades (we haven’t seen arrays yet). If none were entered, it warns and doesn’t calculate the average.

Expected output with 6, 8, 11 (not valid), 4, 9 and 7,5:

=== SUBJECT GRADES ===
Type the grades one by one (from 0 to 10). Type -1 to finish.
Grade: 6
Grade: 8
Grade: 11
  Not valid: it goes from 0 to 10.
Grade: 4
Grade: 9
Grade: 7,5
Grade: -1
--- Summary ---
Grades: 5 (passed: 4)
Average: 6,90
Maximum: 9.0  Minimum: 4.0

If the first one is -1:

=== SUBJECT GRADES ===
Type the grades one by one (from 0 to 10). Type -1 to finish.
Grade: -1
--- Summary ---
No grades: the average cannot be calculated.

A do-while (true) that asks for the grade and leaves with break when it’s -1; for out-of-range grades, a warning and continue. You need a counter, another one for passes and a sum accumulator, all outside the loop and starting at 0. The maximum and minimum cannot start at 0: give them the value of the first valid grade (the round where the counter becomes 1). The average is sum / count, and only if count > 0.

Final challenge

Exercise 3 — Prime numbers in a range

Write PrimesInRange: it asks for a start and an end and shows the primes between them (both included), in rows of five. At the end, the total number of primes and how many divisions were needed to find them. If the start is greater than the end, it warns and stops. 0 and 1 are not prime: if the start is below 2, it starts at 2.

Expected output from 10 to 30:

=== PRIME NUMBERS IN A RANGE ===
From: 10
To: 30
--- Primes found ---
11 13 17 19 23
29
Total: 6 primes (38 divisions)

From 1 to 100:

=== PRIME NUMBERS IN A RANGE ===
From: 1
To: 100
--- Primes found ---
2 3 5 7 11
13 17 19 23 29
31 37 41 43 47
53 59 61 67 71
73 79 83 89 97
Total: 25 primes (236 divisions)

With the range the wrong way round:

=== PRIME NUMBERS IN A RANGE ===
From: 30
To: 10
Invalid range: 'from' must be less than or equal to 'to'.

The outer loop goes through each candidate n in the range; the inner loop tries divisors d from 2. For each candidate, an isPrime = true flag that the inner loop sets to false if it finds a divisor (and then break: no need to carry on). There’s no need to try up to n - 1: d * d <= n is enough. For rows of five, collect the primes in a String and print it each time the total is a multiple of 5; at the end, print whatever is left.

What’s wrong here?

Before the solutions, three fragments with one bug each: all three compile without warnings. Read each one and predict what it prints before looking at the output.

Mistake 1

public class Rounds {
    public static void main(String[] args) {
        int i = 0;
        int brake = 0;                            // emergency brake: NOT part of the bug
        while (i < 5) {
            System.out.println("Round " + i);
            brake++;
            if (brake == 6) {
                System.out.println("(brake: 6 rounds and still going)");
                break;
            }
        }
    }
}

How many rounds does it do? Real output:

Round 0
Round 0
Round 0
Round 0
Round 0
Round 0
(brake: 6 rounds and still going)

Without the brake, it would never end: it’s my frozen loop. The condition is i < 5, but nobody changes i inside the body: it’s 0 in the first round, in the second and in the millionth. The brake (brake == 6) is not part of the bug: I put it there so the output fits on the page.

A while whose condition depends on a variable the body doesn’t change. The for makes it harder because the step is in the header (i++), but in a while it’s your job. Before running, point with your finger at the line in the body that changes the condition.

Fix:

public class Rounds {
    public static void main(String[] args) {
        int i = 0;
        while (i < 5) {
            System.out.println("Round " + i);
            i++;                                  // the condition variable has to change
        }
    }
}
Round 0
Round 1
Round 2
Round 3
Round 4

Mistake 2

public class FindPair {
    public static void main(String[] args) {
        // I want the FIRST pair (a, b) from 1 to 6 with a * b == 12
        for (int a = 1; a <= 6; a++) {
            for (int b = 1; b <= 6; b++) {
                if (a * b == 12) {
                    System.out.println("Found: " + a + " x " + b);
                    break;
                }
            }
        }
        System.out.println("End of the search");
    }
}

We want the first pair a × b = 12. Real output:

Found: 2 x 6
Found: 3 x 4
Found: 4 x 3
Found: 6 x 2
End of the search

break only leaves the loop it’s in, the inner one (b). The outer one doesn’t notice and moves on to a = 3, finds 3 × 4, leaves that row, moves on to 4… Four pairs in total.

break only leaves the inner loopTwo 6 by 6 tables with the products a times b. With only break, each row is walked up to its first 12 and the search carries on in the next row: 2×6, 3×4, 4×3 and 6×2 appear. With the flag in the outer for condition, the search ends at 2×6.Only break: 4 pairsa=1123456a=224681012a=3369121518a=44812162024a=551015202530a=661218243036With a flag: 1 paira=1123456a=224681012a=3369121518a=44812162024a=551015202530a=661218243036In violet, the cells that get checked; in coral, the ones that print.
The break cuts the row short, but the outer for carries on with the next one.

Thinking break leaves every loop. It only leaves the nearest one. To stop the outer one too you need a flag in its condition (or a label, break search;, as you saw in the theory).

Fix with a flag:

public class FindPair {
    public static void main(String[] args) {
        boolean found = false;
        for (int a = 1; a <= 6 && !found; a++) {     // the flag stops the outer one too
            for (int b = 1; b <= 6; b++) {
                if (a * b == 12) {
                    System.out.println("Found: " + a + " x " + b);
                    found = true;
                    break;
                }
            }
        }
        System.out.println("End of the search");
    }
}
Found: 2 x 6
End of the search

Mistake 3

import java.util.Scanner;

public class WrongMinimum {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double minimum = 0;
        System.out.print("Grade: ");
        double grade = sc.nextDouble();
        while (grade != -1) {
            if (grade < minimum) {
                minimum = grade;
            }
            System.out.print("Grade: ");
            grade = sc.nextDouble();
        }
        System.out.println("Minimum: " + minimum);
    }
}

With the grades 6, 8, 4 and 9, what’s the minimum? Real output:

Grade: 6
Grade: 8
Grade: 4
Grade: 9
Grade: -1
Minimum: 0.0

minimum starts at 0, and no real grade is below 0, so the if never goes in and the “minimum” stays at a 0 that nobody typed. The same bug the other way round would make a maximum that starts at 100 never change.

Initialising a minimum (or a maximum) with a value that “looks neutral”. For a sum, 0 is neutral; for a minimum, it isn’t. Either initialise it with the first real value, or with a value any data will beat (Double.MAX_VALUE for a minimum).

Fix with Double.MAX_VALUE:

import java.util.Scanner;

public class WrongMinimum {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double minimum = Double.MAX_VALUE;          // any real grade will be lower
        System.out.print("Grade: ");
        double grade = sc.nextDouble();
        while (grade != -1) {
            if (grade < minimum) {
                minimum = grade;
            }
            System.out.print("Grade: ");
            grade = sc.nextDouble();
        }
        System.out.println("Minimum: " + minimum);
    }
}
Grade: 6
Grade: 8
Grade: 4
Grade: 9
Grade: -1
Minimum: 4.0

Commented solutions

Solution Exercise 1

Before the code, the approach: what do you need to keep track of while you walk through the sentence? Five counters, one per vowel, because the statement asks how many there are of each. The total doesn’t need a sixth counter: it comes from adding up the five at the end. And the most repeated vowel isn’t worked out inside the loop either, but afterwards, once you have the five numbers.

The obvious route would be one loop per vowel: walk through the sentence looking for a’s, then again looking for e’s… It works, but you read the text five times. With a switch inside a single for, each character is looked at once and goes straight to its counter.

import java.util.Scanner;

/**
 * Vowel counter: a for walks through the sentence and a switch adds one to the right vowel.
 * Accented vowels count as their vowel (á → a) and upper case does not matter.
 */
public class VowelCounter {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("=== VOWEL COUNTER ===");
        System.out.print("Word or sentence: ");
        String text = sc.nextLine().toLowerCase();       // a single conversion, outside the loop

        int a = 0, e = 0, i = 0, o = 0, u = 0;           // one counter per vowel, all at 0
        for (int k = 0; k < text.length(); k++) {        // k: i is already the counter of the vowel i
            switch (text.charAt(k)) {
                case 'a', 'á' -> a++;
                case 'e', 'é' -> e++;
                case 'i', 'í' -> i++;
                case 'o', 'ó' -> o++;
                case 'u', 'ú', 'ü' -> u++;
                default -> { }                           // consonants, spaces, digits: nothing
            }
        }
        int total = a + e + i + o + u;
        System.out.println("--- Result ---");
        System.out.println("a: " + a + "  e: " + e + "  i: " + i + "  o: " + o + "  u: " + u);
        System.out.println("Total vowels: " + total);

        if (total == 0) {
            System.out.println("No vowels.");
        } else {
            // The most repeated: start by assuming a and compare with the rest (> and not >=: on a tie the first one wins)
            char mostRepeated = 'a';
            int maxCount = a;
            if (e > maxCount) { mostRepeated = 'e'; maxCount = e; }
            if (i > maxCount) { mostRepeated = 'i'; maxCount = i; }
            if (o > maxCount) { mostRepeated = 'o'; maxCount = o; }
            if (u > maxCount) { mostRepeated = 'u'; maxCount = u; }
            System.out.println("Most repeated: " + mostRepeated + " (" + maxCount + " times)");
        }
        sc.close();
    }
}

Why it’s done this way:

  • toLowerCase() once, outside the loop. Doing it inside (Character.toLowerCase(c) in every round) would also work, but this way the switch only has to look at lower case and nothing is repeated.
  • The index is called k. The counters a, e, i, o, u are named after their vowel, and i is taken. If the for used int i, javac would say variable i is already defined in method main(String[]).
  • Arrow switch with several values per case. case 'a', 'á' -> a++; puts the vowel together with its accented form. The empty default -> { } makes it clear the rest of the characters are ignored on purpose.
  • > and not >= for the most repeated. With “programacion” a and o tie at 2. With >, o doesn’t beat a and the first one wins (as the statement asks). With >=, the last of the tied ones would win.
kcharactercaseaio
2o'o'001
5a'a'101
7a'a'201
9i'i'211
10o'o'212

(The rounds for consonants go to default and change nothing; total: 2 + 1 + 2 = 5.)

What comes out with “Oso panda”?

a: 2 e: 0 i: 0 o: 2 u: 0, total 4, and the most repeated is a (2 times), even though the first vowel in the text is o. The tie isn’t decided by the order of the sentence but by the order of the ifs: it starts by assuming a, and o doesn’t beat it with >, it only equals it.

Solution Exercise 2

Before the code, the approach. Since there are no arrays, you can’t store the grades and calculate later: everything is worked out on the fly. For each figure in the summary, ask yourself what you need to remember about the previous grades. For the average, the sum and how many there are; for the passes, a counter; for the maximum and minimum, only the best and worst so far, not all of them.

The obvious route for the loop would be while (grade != -1), but then you have to ask for the first grade before the loop and repeat the request at the end of the body: the same code written twice. With do-while (true) and break, the request is written only once.

import java.util.Scanner;

/**
 * Grades with a sentinel value: grades are asked for until -1 arrives. An accumulator for the average,
 * counters and maximum/minimum WITHOUT storing the grades (no arrays).
 */
public class SentinelGrades {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("=== SUBJECT GRADES ===");
        System.out.println("Type the grades one by one (from 0 to 10). Type -1 to finish.");

        int count = 0, passed = 0;
        double sum = 0;
        double maximum = 0, minimum = 0;            // overwritten with the first valid grade
        double grade;
        do {
            System.out.print("Grade: ");
            grade = sc.nextDouble();
            if (grade == -1) {
                break;                              // the sentinel is not a grade: it is not counted
            }
            if (grade < 0 || grade > 10) {
                System.out.println("  Not valid: it goes from 0 to 10.");
                continue;                           // do-while: jumps to the condition at the end
            }
            count++;
            sum += grade;
            if (grade >= 5) {
                passed++;
            }
            if (count == 1) {                       // the first grade is both the maximum and the minimum
                maximum = grade;
                minimum = grade;
            } else if (grade > maximum) {
                maximum = grade;
            } else if (grade < minimum) {
                minimum = grade;
            }
        } while (true);                             // the only way out is the sentinel break

        System.out.println("--- Summary ---");
        if (count == 0) {
            System.out.println("No grades: the average cannot be calculated.");
        } else {
            System.out.println("Grades: " + count + " (passed: " + passed + ")");
            System.out.printf("Average: %.2f%n", sum / count);
            System.out.println("Maximum: " + maximum + "  Minimum: " + minimum);
        }
        sc.close();
    }
}

Why it’s done this way:

  • do-while (true) with break. You have to ask for the grade before you can know whether it’s the sentinel, so the body runs at least once. The exit is in the middle of the body (at the break), not in the condition: that’s why the condition is true.
  • The sentinel isn’t counted. The break comes before count++ and sum += grade. If it came after, the -1 would get into the average.
  • continue for out-of-range grades. In a do-while, it jumps to the condition at the end (true), so another grade is asked for without counting the 11.
  • Maximum and minimum from the first grade. When count becomes 1, that grade is both the maximum and the minimum; from then on, they only change if a grade beats them. The else if is safe: a grade can’t be above the maximum and below the minimum at the same time.
  • The sums. Valid grades: 6, 8, 4, 9 and 7.5. Sum: 6 + 8 + 4 + 9 + 7.5 = 34.5. Average: 34.5 / 5 = 6.90. Passed: all except the 4, that is, 4. The maximum and minimum come out with a point (9.0, 4.0) because + prints them with a double; the average comes out with a comma because it’s printf on a computer set to Spanish.
TypedCounts?countsummaximumminimum
6Yes1666
8Yes21486
11No: continue21486
4Yes31884
9Yes42794
7,5Yes534.594
-1No: break534.594
Why count == 1 and not “the first round of the loop”?

Because the first round may bring a grade that isn’t valid. If you type 11, then 7 and then -1, the 11 is rejected with continue and count stays at 0. The grade that really is the first one is the 7: with it count becomes 1 and the maximum and minimum start at 7. Result: Grades: 1 (passed: 1), Average: 7,00, Maximum: 7.0 Minimum: 7.0. If you marked the first round as “first”, that round would go to the 11, which is discarded, and the 7 would be compared with a maximum and minimum still at 0: the minimum would come out as 0.0, the same bug as mistake 3.

Solution Exercise 3

Before the code, the approach: the problem is two questions, one inside the other. The inner one is “is this n prime?”, and the outer one, “which numbers do I ask it for?”. Write the inner loop first for a fixed n (try 29 and 25), check that it gets them right, and only then wrap it in the loop over the range.

The obvious route for the inner question is to count the divisors from 1 to n and check that there are exactly two. It works, but it does n divisions per candidate: from 10 to 30 that would be 420, against the 38 of this solution, which stops with break at the first divisor and never goes past the root.

import java.util.Scanner;

/**
 * Primes in a range: the outer loop walks through the numbers and the inner one looks for a divisor
 * up to the square root (d * d <= n), stopping with break as soon as it finds one.
 */
public class PrimesInRange {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("=== PRIME NUMBERS IN A RANGE ===");
        System.out.print("From: ");
        int from = sc.nextInt();
        System.out.print("To: ");
        int to = sc.nextInt();

        if (from > to) {
            System.out.println("Invalid range: 'from' must be less than or equal to 'to'.");
            return;
        }
        if (from < 2) {
            from = 2;                                     // neither 0 nor 1 is prime: start at 2
        }

        System.out.println("--- Primes found ---");
        int total = 0, divisions = 0;
        String row = "";
        for (int n = from; n <= to; n++) {                // outer loop: each candidate
            boolean isPrime = true;                       // reset for EACH candidate
            for (int d = 2; d * d <= n; d++) {            // inner loop: divisors up to the root
                divisions++;
                if (n % d == 0) {
                    isPrime = false;
                    break;                                // leaves only the inner loop
                }
            }
            if (isPrime) {
                total++;
                row += n + " ";
                if (total % 5 == 0) {                     // every 5 primes, one line
                    System.out.println(row.trim());
                    row = "";
                }
            }
        }
        if (!row.isEmpty()) {
            System.out.println(row.trim());               // the last line, if it was left half full
        }
        System.out.println("Total: " + total + " primes (" + divisions + " divisions)");
        sc.close();
    }
}

Why it’s done this way:

  • isPrime = true inside the outer loop. Each candidate starts as “prime until proven otherwise”. If it were declared outside, as soon as one number wasn’t prime the flag would stay false for all the following ones.
  • d * d <= n instead of d < n. Divisors come in pairs: if 28 = 2 × 14, trying 2 has already found it. If a number had a divisor above its root, its partner would be below and would have shown up earlier. That saves most of the divisions:
Up to the square root is enoughThe numbers from 2 to 28 in a row. Only 2, 3, 4 and 5 meet d times d less than or equal to 29; with 6, 36 is already over 29 and the loop stops. That is 4 divisions instead of 27.Is 29 prime? Divisors that are tried23456789101112131415161718192021222324252627286 × 6 = 36 > 29: it stopsd * d <= n4 divisions (2, 3, 4, 5)d < n27 divisions (2 to 28)If 29 had a divisor above 5, its partner would be below 5 and would already have shown up.
Divisors come in pairs (2 × 14 = 28): it is enough to look for the small one.
  • break only leaves the inner loop, which is exactly what we want here: stop trying divisors of this candidate and move on to the next. It’s the same break that caused trouble in mistake 2; the difference is what we wanted to do.
  • Rows of five. total % 5 == 0 is true with the 5th, 10th… prime. What’s left half full (29 in the range 10-30) is printed after the loop.
  • The sums for the range 10-30. Primes: 11, 13, 17, 19, 23 and 29, six of them. Divisions: 38. For example, 29 tries 2, 3, 4 and 5 (4 divisions); with d < n it would have been 27.
ndivisors triedPrime?divisions so far
102 (10 % 2 = 0, break)No1
112, 3 (4 × 4 = 16 > 11, stops)Yes3
122 (break)No4
132, 3Yes6
Where do the 38 divisions in the range 10-30 come from?

The 11 even numbers (10, 12… 30) cost one division each: 2 divides them at the first try and break. That’s 11.

The odd ones cost more. 11 and 13 try 2 and 3 (with 4, 4 × 4 is already above them): 2 each. 15, 21 and 27 also stop at 2, because 3 divides them. 17, 19 and 23 try 2, 3 and 4: 3 each. 25 and 29 go up to 5: 4 each (25 is divided exactly by 5). In total, 2 × 5 + 3 × 3 + 4 × 2 = 27.

11 + 27 = 38, the figure in the output.

Exam-style quiz

Now test yourself as in the exam. The FP2 Java quiz works like this: 15 questions in 15 minutes covering the whole Java syllabus, with a few from each topic. Here are the loop ones: answer without running anything, check and read the explanation of the ones you miss. These questions also make up the bank of the FP2 theory mock exam.

Question 1Short answer

What number does this fragment print?

int n = 0;
for (int i = 10; i > 0; i -= 3) n++;
System.out.println(n);
Solution

Answer: 4

i takes the values 10, 7, 4 and 1: four iterations. Then it becomes −2, the condition i > 0 is false and the loop ends. Listing the values of i one by one is the safe way to avoid an off-by-one mistake.

Question 2Fill in the gaps

In Python you have for i in range(10, 0, -2):. Fill in the Java loop that does the same:

for (int i = ____; i ____ 0; i ____ 2)

Words:

  • 0
  • 10
  • +=
  • <
  • -=
  • >=
  • >
Solution

for (int i = 10; i > 0; i -= 2)

range(10, 0, -2) starts at 10, goes down in twos and doesn’t include 0: 10, 8, 6, 4, 2. That’s why the condition is i > 0 (with >= the 0 would sneak in). The third argument of range is the step: here, subtract 2.

Question 3Short answer

What does this fragment print?

int k = 5;
do {
    System.out.print(k);
    k++;
} while (k < 3);
System.out.println();
Solution

Answer: 5

The do-while checks the condition at the end, so the body runs at least once even though 5 < 3 is false from the start. With a normal while nothing would be printed.

Question 4Short answer

What does this fragment print?

for (int i = 1; i <= 6; i++) {
    if (i % 2 == 0) continue;
    if (i == 5) break;
    System.out.print(i);
}
System.out.println();
Solution

Answer: 13

Even numbers are skipped with continue (it jumps to the next iteration without printing). 1 and 3 are printed; on reaching 5, break stops the whole loop, so 5 isn’t printed.

Question 5Single choice

What does this fragment print?

int[] v = {1, 2, 3};
for (int x : v) x = x * 10;
System.out.println(v[0] + v[1] + v[2]);
  1. 6
  2. 60
  3. 123
  4. It doesn’t compile
Solution

Answer: 6

In a for-each, the variable receives a copy of each element’s value (with primitives). To change the array you need its index: for (int i = 0; i < v.length; i++) v[i] *= 10;.

Question 6Short answer

What number does this fragment print?

int c = 0;
for (int i = 0; i < 4; i++)
    for (int j = i; j < 4; j++)
        c++;
System.out.println(c);
Solution

Answer: 10

The inner loop starts at i, so it runs 4 times when i = 0, 3 when i = 1, then 2 and 1: 4 + 3 + 2 + 1 = 10. It’s the pattern for going through only half a matrix (or comparing each pair once).

Question 7True or false

True or false?

  1. The body of a do-while runs at least once.
  2. The for-each gives you the element’s index on each iteration.
  3. A variable declared in the for header doesn’t exist after the loop.
  4. while (true) with a break inside is a valid loop.
  5. for (;;) doesn’t compile because its three parts are missing.
Solution
  • T — The body of a do-while runs at least once.
  • F — The for-each gives you the element’s index on each iteration.
  • T — A variable declared in the for header doesn’t exist after the loop.
  • T — while (true) with a break inside is a valid loop.
  • F — for (;;) doesn’t compile because its three parts are missing.

The for-each gives you the value, not the position: if you need the index, use a classic for. All three parts of the for are optional: for (;;) is an infinite loop, just like while (true).

Question 8Single choice

What number does this fragment print?

int sum = 0;
for (int i = 1; i <= 10; i += 2) sum += i;
System.out.println(sum);
  1. 25
  2. 30
  3. 36
  4. 55
Solution

Answer: 25

With step 2 starting at 1, i is 1, 3, 5, 7 and 9; when it becomes 11 the condition fails. The sum of the odd numbers is 25.

Question 9Order

Put in order what a for (init; condition; update) does in its first iterations:

  1. Runs the initialisation (only once)
  2. Checks the condition again
  3. Runs the body
  4. Checks the condition
  5. Runs the update
Solution

Correct order:

  1. Runs the initialisation (only once)
  2. Checks the condition
  3. Runs the body
  4. Runs the update
  5. Checks the condition again

The initialisation runs only once at the start. Then it repeats: condition → body → update. If the condition is false from the start, the body never runs.

Question 10Match

Match each situation with the most suitable loop:

Repeat a number of times you already know
Ask for a value until it’s valid (at least once)
Go through every element without needing its position
Repeat while something holds that may be false from the start

Definitions:

  • switch
  • while
  • for-each
  • do-while
  • for
Solution
  • Repeat a number of times you already know → for
  • Ask for a value until it’s valid (at least once) → do-while
  • Go through every element without needing its position → for-each
  • Repeat while something holds that may be false from the start → while

for is for counting; do-while, for «do it once and repeat if needed» (validating input); for-each, for going through elements; and while, for conditions that don’t depend on a counter. switch isn’t a loop.

Question 11Short answer

What does this fragment print?

String s = "";
int i = 3;
while (i > 0) {
    s = s + i;
    i--;
}
System.out.println(s + i);
Solution

Answer: 3210

On each iteration i is glued to the end of s: "3", "32", "321". When i reaches 0 the loop ends, but i still exists (it was declared outside) and is 0, so 3210 is printed.

See it with Python Tutor

Python Tutor (pythontutor.com) runs code line by line and shows how the variables change. Choose Java in the drop-down and paste this program, the prime search from 10 to 15:

public class TutorPrimes {
    public static void main(String[] args) {
        int total = 0;
        for (int n = 10; n <= 15; n++) {
            boolean isPrime = true;
            for (int d = 2; d * d <= n; d++) {
                if (n % d == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                total++;
                System.out.println(n + " is prime");
            }
        }
        System.out.println("Total: " + total);
    }
}

Output:

11 is prime
13 is prime
Total: 2

What to watch step by step:

  1. With n = 10, the inner loop does a single round: 10 % 2 == 0, isPrime becomes false and break takes it out straight away.
  2. With n = 11, it tries d = 2 and d = 3; with d = 4, 4 * 4 = 16 is no longer <= 11 and the loop ends without break: isPrime is still true.
  3. Notice that isPrime goes back to true at the start of each candidate: it’s created again in every outer round.
  4. total only goes up with 11 and 13: it ends at 2.

Summary

  • A loop must have a way to end: some variable in its condition changes every round (or there is a break that is surely reached).
  • Walking through a text: for (int k = 0; k < text.length(); k++), with <.
  • Sentinel: ask, check whether it’s the exit value with break and, if not, process it. The sentinel is never counted.
  • Accumulators and counters, outside the loop and at 0; maximum and minimum, with the first real value (or with Double.MAX_VALUE/-Double.MAX_VALUE).
  • break only leaves the nearest loop; to stop the outer one, a flag in its condition or a label.
  • In nested loops, whatever resets every outer round (like isPrime) is declared inside the outer loop.
FP2 exam coming up?The pack for each exam, the Python and Java cheat sheet and the practical solutions with their tests, for free.See the pack

Cheat sheet: loops in Java

The essentials in 30 seconds: if you know how many rounds, for; if it depends on what happens, while; if it must run at least once, do-while. Positions go from 0 to length() - 1, so <. Something in the condition must change every round. break leaves the nearest loop and continue jumps to the next round. Accumulators start at 0; maximums and minimums, with the first value.

I want to…CodeResult
Walk through a textfor (int k = 0; k < t.length(); k++)positions 0 to length() - 1
Walk backwardsfor (int k = t.length() - 1; k >= 0; k--)from the last one to 0
Just the charactersfor (char c : t.toCharArray())no index
Two indexes at oncefor (int i = 0, j = n - 1; i < j; i++, j--)they cross halfway
Repeat while it holdswhile (attempts < MAX && !guessed)may never go in
Repeat at least oncedo { … } while (option != 0);always goes in
Read up to a sentineldo { x = sc.nextInt(); if (x == -1) break; … } while (true);-1 isn’t processed
Skip bad dataif (bad) { continue; }back to the condition
Leave two loopsflag in the outer condition, or break label;stops both
Minimum with no previous datadouble min = Double.MAX_VALUE;any value is smaller
Is it prime?for (int d = 2; d * d <= n; d++)up to the root

Templates from the exercises:

ExercisePatternWith this dataGives
Vowelsfor + arrow switch, one counter per vowelprogramaciontotal 5, most repeated a (2)
Sentineldo-while (true) + break + continue, max/min from the first value6, 8, 11, 4, 9, 7,5, -15 grades, average 6,90, 9.0 / 4.0
Primesnested, reset flag, d * d <= n + breakfrom 10 to 306 primes, 38 divisions
SymptomLikely cause
The program never endsnothing changes the condition variable (missing i++)
StringIndexOutOfBoundsException: Index N out of bounds for length N<= instead of <
The average includes the -1the sentinel break comes after adding
The minimum comes out as 0 (or the maximum never changes)it was initialised with 0 instead of the first value
Several results appear when one was wantedbreak only leaves the inner loop
After the first non-prime, nothing is primethe flag was declared outside the outer loop
variable i is already definedthe same name in two nested loops (or in a counter)

Before handing it in, ask yourself:

  1. Which line in the body changes the condition of each loop?
  2. Have I tried the empty case (-1 first, a text with no vowels, a range with no primes)?
  3. Are my accumulators outside the loop and what resets, inside?
  4. Does each break leave the loop I think it does?

That wraps up loops. The next topic is methods in Java: the block you repeated three times in the guessing game, and the prime check, become a method with a name that you call from wherever you need it.

Keep goingAll Java articles

Did this article help you? Here is how you can support SergioLearns →

Ready for the exam?FP2 theory mock exam — Python, Java or the resit, against the clock and with your real mark (just like in the lab)