🔁 Part 4: Learn Java Loops — Repeat Tasks Like a Coding Pro
In the real world, we repeat things all the time:
- Wake up → brush teeth → repeat every day
- Watch one more episode → again and again 😅
- Count to 10 → one number at a time
Java lets your code repeat actions automatically using loops — and it’s easier than you think.
🎯 What Is a Loop?
A loop is a way to tell your code:
“Do this thing over and over — until I say stop.”
There are 3 main types:
Loop Type | When to Use It |
---|---|
for loop | You know how many times to repeat |
while loop | Repeat while a condition is true |
do-while loop | Like while , but runs at least once |
🧮 1. for
Loop: Count Up Like a Pro
for (int i = 1; i <= 5; i++) {
System.out.println("Step " + i);
}
🧠 What’s Happening?
int i = 1
→ start counting from 1i <= 5
→ keep going while i is 5 or lessi++
→ increase i by 1 each time
➡ Output:
Step 1
Step 2
Step 3
Step 4
Step 5
🔁 2. while
Loop: Repeat Until Something Changes
int x = 3;
while (x > 0) {
System.out.println("Counting down: " + x);
x--;
}
➡ Output:
Counting down: 3
Counting down: 2
Counting down: 1
✅ Runs as long as x > 0
is true
🔂 3. do-while
Loop: Do It At Least Once
int number = 0;
do {
System.out.println("This runs once!");
} while (number != 0);
✅ Even if the condition is false, it runs once before checking
🎨 Real Example: Print All Even Numbers from 1 to 10
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
➡ Output:
2
4
6
8
10
⚠️ Common Mistakes to Avoid
❌ Forgetting to update the counter
while (true) {
// infinite loop! 😱
}
✅ Always make sure your loop can stop!
🎯 Mini Challenge: Countdown with a Twist
Write a loop that counts from 5 to 1, then prints “Liftoff!”
for (int i = 5; i >= 1; i--) {
System.out.println(i);
}
System.out.println("Liftoff! 🚀");
🧭 What’s Next? (Part 5 Preview)
In Part 5, you’ll learn how to:
✅ Group data using arrays
✅ Loop through lists of items
✅ Make your programs work with many values
🧪 Java Loop Cheat Sheet
// For loop
for (int i = 0; i < 10; i++) {
// repeat this 10 times
}
// While loop
while (condition) {
// repeat while condition is true
}
// Do-while loop
do {
// run once, then check condition
} while (condition);