Loops are a control structure that allow you to run code repeatedly. The for loop provides a structured way to do so.
A for loop uses a counter to keep track of which run we are on. Each run is called an iteration. The basic premise goes like this:
A for loop will look like this:
for (<initialization>; <condition>; <update>) {
<statement>;
<statement>;
...
}
Let's go through the following for loop together:
for (int i = 0; i < 2; i++) {
System.out.print("Wakka ");
}
i
to 0.i < 2
. Since 0 < 2
is true, the condition holds true and we run our loop body.i
by 1 (that's what i++
does). i
was 0
, but now it's 1
.i < 2
. Since 1 < 2
is true, the condition holds true and we run our loop body again.i
was 1
, now it's 2
.i < 2
. Since 2 < 2
is false, the condition does not hold true, so we don't run the loop body and move on to the code after the for loop. We're done running the for loop!The output looks like:
Wakka Wakka
You can choose to either repeat the same thing over and over again or have the loop change values, with the values being within a specified range.
Same value:
for (int i = 0; i < 5; i++) {
System.out.println("The Eyes of Texas are upon you!");
}
Output:
The Eyes of Texas are upon you!
The Eyes of Texas are upon you!
The Eyes of Texas are upon you!
The Eyes of Texas are upon you!
The Eyes of Texas are upon you!
Change values every time:
System.out.println("I'm going to count to 10!");
for (int i = 1; i <= 10; i++) {
System.out.println(i + "!");
}
Output:
I'm going to count to 10!
1!
2!
3!
4!
5!
6!
7!
8!
9!
10!
Back to top
© 2019–2024 Jeffrey Wang. All rights reserved.
In loving memory of Haskell, 19??-2001.