🎯 What you will learn
- Write a for loop with start, check and step
- Use while loops
- Avoid off-by-one bugs
👋 Let’s get started!
Java’s for loop packs three things into one line: where to start, when to stop, and how to step. Once it clicks, you can count anything! 🔁
🪜 Step by step
1. 🔁 for loop parts
for (start; keep-going check; step) { … }
for (int i = 1; i <= 5; i++) {
System.out.println("Lap " + i);
}
2. ⬇️ Counting down
Use i– to count backwards.
for (int i = 3; i >= 1; i--) {
System.out.println(i);
}
System.out.println("Liftoff! 🚀");
3. ⏳ while
Repeat while something is true.
int coins = 0;
while (coins < 50) {
coins += 20;
}
System.out.println("Coins: " + coins);
🧪 Try it!
Read the code, guess what it prints, then press 👀 Show output.
Times table
int n = 7;
for (int i = 1; i <= 5; i++) {
System.out.println(n + " x " + i + " = " + (n * i));
}Sum 1 to 10
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
System.out.println(sum);📖 Key words
Tap a card to flip it over!
- i++
- Adds 1 to i ➕
- i–
- Subtracts 1 from i ➖
- +=
- Adds to a variable ⬆️
- Off-by-one
- A loop that runs one time too many or too few 🎯
🏆 Challenge
How many stars print? Predict, then check.
Challenge
for (int i = 0; i < 4; i++) {
System.out.print("⭐");
}Knowledge Check Quiz
- How many times does it run?
- What does i++ do?
- What prints last?