What are Loops?
Loops let computers repeat actions without writing the same code over and over. Imagine if you had to write "draw a star" 100 times - that would be boring! Loops do it for you!
🔄 Loops in Real Life
🏃 Real Life Example: Running Laps
When your PE teacher says "Run 5 laps," you don't need separate instructions for each lap:
- Lap 1: Run around the track
- Lap 2: Run around the track
- ...and so on
You just repeat "run around track" 5 times. That's a loop!
💻 The FOR Loop
A FOR loop repeats a specific number of times:
for (let i =
1; i <= 5;
i++) {
console.log("⭐ Star number " + i);
}
console.log("⭐ Star number " + i);
}
🎮 Try It: Star Generator
Click "Generate Stars" to see the loop in action!
Waiting for loop to start... 🤖
🔄 The WHILE Loop
A WHILE loop keeps going as long as something is true:
while (lives >
0) {
playGame();
}
// Stops when you run out of lives!
playGame();
}
// Stops when you run out of lives!
📚 Key Words to Remember
- Loop: Code that repeats
- FOR loop: Repeats a specific number of times
- WHILE loop: Repeats while a condition is true
- Iteration: One run through the loop
🎉 Congratulations!
You've completed all 4 lessons! You now know the basics of programming:
- ✅ What programming is
- ✅ Variables (memory boxes)
- ✅ Conditionals (IF/ELSE)
- ✅ Loops (FOR/WHILE)