Stop 03 · Control Flow, Methods & ArraysTopics · 3/8

For, While & Do-While Loops

Part of the Java Roadmap

In short

Computers are brilliant at doing the same thing many times without getting bored. Loops let you print 100 receipts, sum a month of sales or keep a menu running until the user quits.

for loops suit a known number of repetitions, while loops repeat while a condition holds, and do-while always runs at least once. The enhanced for loop (for-each) walks through arrays and collections without an index.

The jaadu jogs around an oval school running track while a coach with a whistle counts laps on fingers.

Think of it like this

Laps around the school ground

"Run 10 laps" is a for loop: you know the count. "Keep running until the whistle" is a while loop: you check before each lap. "Run one lap, then check if coach wants more" is do-while: at least one lap always happens.

Watch it happen

for (int i = 0; i < 4; i++) sum += prices[i];

120
0
i
80
1
45
2
200
3

1/5Start: i = 0, sum = 0.

The big ideas

What you need to know

for: known count

for (init; condition; update). Perfect when you know how many times, like looping over indexes.

while: unknown count

Checks the condition before each pass. Might run zero times.

do-while: at least once

Runs the body first, then checks. Great for menus and input prompts.

for-each

for (int p : prices) walks through every element without an index. Use it when you do not need the position.

See it in code

Walk through the code

java
1import java.util.Scanner;2 3public class Loops {4    public static void main(String[] args) {5        int[] prices = {120, 80, 45, 200};6 7        int sum = 0;8        for (int i = 0; i < prices.length; i++) {9            sum += prices[i];10        }11 12        int max = 0;13        for (int p : prices) {14            max = Math.max(max, p);15        }16 17        int savings = 0, month = 0;18        while (savings < 10_000) {19            savings += 1_500;20            month++;21        }22 23        Scanner sc = new Scanner(System.in);24        String again;25        do {26            System.out.println("Sum " + sum + ", max " + max + ", months " + month);27            System.out.print("Show again? (y/n) ");28            again = sc.next();29        } while (again.equalsIgnoreCase("y"));30    }31}

1/4Classic index loop. prices.length keeps it correct if the array changes size.

A counting for loop, a for-each, a while loop that runs an unknown number of times and a do-while menu.

Save yourself the pain

Common mistakes

Oops

for (int i = 0; i <= prices.length; i++)

Do this instead

Indexes go from 0 to length - 1. Use i < prices.length, or a for-each loop.

Oops

A while loop whose condition never changes inside the body.

Do this instead

That is an infinite loop. Make sure something in the body moves you toward the exit.

Your mission

Loop practice set

~25 min

Quick check

Which loop always runs its body at least once?

Go deeper

  1. 1Print a multiplication table with a for loop and sum digits with a while loop.
  2. 2Build a menu that repeats with do-while until the user chooses exit.
  3. 3Loop over an array with a for-each loop and note when you still need an index.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge