JOOPs Through Java
Challenge roadmap
0/30 Days Completed 0 Learning Days

Day 6 of 30 · Week 1 — Java Foundations

Loops: for, while, do-while

1 Learn

A loop repeats code. for is great when you know how many times to repeat.

while repeats as long as a condition stays true, checking it before each round.

do-while runs the body at least once, then checks the condition.

Want more detail? Open the full lesson

2 See the Code

Java
public class Loops {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            System.out.println("for " + i);
        }
        int n = 3;
        while (n > 0) {
            System.out.println("while " + n);
            n--;
        }
        int k = 10;
        do {
            System.out.println("do " + k);
        } while (k < 5);
    }
}
  • for: start i at 1, repeat while i <= 3, add 1 each time.
  • while: prints 3, 2, 1 and stops when n becomes 0.
  • do-while: prints once even though k < 5 is false.

Output

for 1
for 2
for 3
while 3
while 2
while 1
do 10

3 Practice

  • Print the 5 times table from 5 x 1 to 5 x 10 using a for loop.

Try it in your own Java setup or write it in the Practice Notebook.

4 Quick Check

  1. 1. Which loop always runs at least once?

  2. 2. How many times does for (int i = 0; i < 4; i++) run?

Step 5

Answer and check the Quick Check above to unlock this.