Loops
LockedLesson 6 of 60 · Syntax · Easy
Finish these first:Conditionals →Or pass the tests below to unlock it now.
The big idea
A for loop repeats a block of code while counting up or down. A Java for loop has three short parts inside ( ...
Think of it like this: Think of a `for` loop like a tally counter: start at 1, stop after 5, and add 1 each step.
Read the lesson
A for loop repeats a block of code while counting up or down.
A Java for loop has three short parts inside ( ... ): where to start, when to keep going, and how to step:
int coins = 0;
for (int i = 1; i <= 3; i++) {
coins = coins + i; // coins becomes 6 (1 + 2 + 3)
}
Each time through the loop, i++ increases i by 1 until i <= 3 is no longer true.
Quick check
What does `i++` mean in a Java `for` loop?
Your challenge
Inside the { ... } block, write a for loop from 1 to 5 that adds each number to total (so total becomes 15).
More learning tools(compare languages, visual guide, related lessons)
Compare with another language
Similar to python.loops (90% overlap). Python `for x in it` ~ Java for-each; no `i++` in Python.
Visual walkthrough
A diagram, a step-by-step animation, and short captions for Loops.
Learn this first
- ConditionalsNot yet