Skip to content
Loops
step 1/5

Reading — step 1 of 5

Learn

~3 min readControl Flow

Loops

Loops repeat work. Java gives you four forms; picking the right one mostly comes down to one question: do I know how many times, up front?

The classic for — count-controlled

for (int i = 0; i < 5; i++) {
    System.out.println(i);   // 0 1 2 3 4
}

Three slots, separated by semicolons: initialize (int i = 0, runs once), condition (i < 5, checked BEFORE each pass — the loop ends when it turns false), update (i++, runs AFTER each pass). Read it aloud: "start at 0; keep going while under 5; step by one."

while and do-while — condition-controlled

int n = 16;
while (n > 1) {      // check first — may run zero times
    n /= 2;
}

int tries = 0;
do {
    tries++;          // body first — always runs at least once
} while (tries < 3);

Use while when you don't know the iteration count in advance (reading input until it runs out, halving until small enough). do-while is the rare cousin for "do it, THEN decide whether to repeat."

Enhanced for — iterate elements

int[] nums = {1, 2, 3, 4, 5};
for (int x : nums) {
    System.out.println(x);
}

No index bookkeeping, no off-by-one possible. Prefer it whenever you need the elements and not their positions.

break exits the innermost loop immediately; continue skips to the next iteration. For nested loops, a labeled break (break outer;) can exit both at once.

The trap: off-by-one

The single most common loop bug is the boundary. < versus <= decides whether the last value is included:

// Sum 1..5 — CORRECT: <= includes 5
int sum = 0;
for (int i = 1; i <= 5; i++) {
    sum += i;
}
// sum == 15
// BROKEN: < stops at 4
int sum = 0;
for (int i = 1; i < 5; i++) {
    sum += i;
}
// sum == 10 — one short!

Note the accumulator pattern: sum is declared OUTSIDE the loop (so it survives across iterations) and initialized to 0. Declare it inside and it resets every pass; skip the = 0 and the compiler refuses to build — local variables have no default value.

The other classic: forgetting the update. while (n > 1) { System.out.println(n); } never changes n — an infinite loop, which the grader kills with a time-limit error.

Your exercise

Read a positive integer N and print 1 + 2 + ... + N:

int sum = 0;
for (int i = 1; i <= n; i++) {
    sum += i;
}
System.out.println(sum);

For 5 the grader expects 15; for 100, 5050. The mistake it will catch is the off-by-one: writing i < n sums only 1 through N-1 and prints 10 for input 5. If your answer is exactly one N short, your boundary is < where it should be <=. And start i at 1, not 0 — adding 0 is harmless here, but be deliberate about both ends of every loop you write.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…