Step 1 of 5 · Reading · ~4 min
Learn
Control Flow
Loops
A loop repeats a block of code. By the end of this lesson you can choose between Java's loop forms, build a running total across iterations, and get the first and last pass of a loop exactly right.
The classic for: counting
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 every pass; the loop ends when it is false), update (i++, runs after every pass). Read it aloud: "start at 0, keep going while under 5, step by one." Note it runs five times but never reaches 5.
while and do-while
int n = 1000;
int digits = 0;
while (n > 0) { // checked first: may run zero times
n /= 10;
digits++;
}
// digits == 4
Use while when you do not know the count in advance (halve until small, read until empty). do { ... } while (cond); checks after the body, so the body always runs at least once.
for-each: visit every element
int[] prices = {12, 7, 30}; below is an array, a fixed row of values written inside braces. The arrays lesson covers it fully; here it just gives the loop something to visit.
int[] prices = {12, 7, 30};
for (int p : prices) {
System.out.println(p);
}
No index and no chance of an off-by-one. Use it when you want the values, not their positions.
break and continue
break leaves the innermost loop at once; continue skips the rest of this pass and moves to the next one:
for (int i = 1; i <= 6; i++) {
if (i % 2 == 0) {
continue; // skip even i
}
System.out.println(i); // 1 3 5
}
The accumulator pattern
To combine many values into one, declare the running value (bill here) before the loop, so it survives the passes, and update it inside:
int bill = 0;
for (int p : prices) {
bill += p;
}
System.out.println(bill); // 49
Declare bill inside the loop and it resets every pass. Forget = 0 and the compiler refuses, since locals have no default. Which values get added is decided by an if inside the loop: the loop visits everything, the condition chooses.
The trap: off-by-one
The most common loop bug is the boundary. < versus <= decides whether the last value is included, and the start decides whether the first is:
int sum = 0;
for (int i = 1; i <= 5; i++) { sum += i; } // 15: i takes 1,2,3,4,5
int sum = 0;
for (int i = 1; i < 5; i++) { sum += i; } // 10: i takes 1,2,3,4
Before you run a loop, write down the first and last value i takes. "Up to and including N" is i <= n. "Below N" is i < n. They differ by exactly one pass, and that pass is the usual wrong answer.
Totals can outgrow int
An int holds about 2.1 billion. A running total of many large-ish values passes that quickly, and it wraps to a negative number without any error. If a total may get big, declare it long; bill += i then widens i automatically.
Forgetting the update
while (n > 1) { System.out.println(n); } never changes n, so it runs forever. The grader stops it with a time-limit error, not a message about your logic.
Common mistakes
- Off-by-one on either end of the loop range.
- Accumulator declared inside the loop, or never initialized.
- Overflow of an
inttotal. - Using
==in a loop condition on a value that jumps past it. Prefer<,<=,>or>=.
Your exercise
Add up a filtered set of numbers: the loop visits every candidate and an if decides which ones count. Two details decide whether you pass: whether the stated upper limit itself is included, and whether your total can still hold the biggest case.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…