for loops

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:

  1. Initialize our counter variable at a specified value.
  2. Each time before our loop body runs, check whether the counter variable meets the condition we've set.
  3. The body runs.
  4. After the body runs, update the value of our counter variable by some value. The update can increment or decrement the counter.

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 ");
}
  1. We initialize the counter variable i to 0.
  2. We check if i < 2. Since 0 < 2 is true, the condition holds true and we run our loop body.
  3. We print "Wakka " to the console.
  4. We now change the control variable by incrementing i by 1 (that's what i++ does). i was 0, but now it's 1.
  5. We once again check if i < 2. Since 1 < 2 is true, the condition holds true and we run our loop body again.
  6. We again print "Wakka " to the console.
  7. We once again change the control variable. i was 1, now it's 2.
  8. We check if 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

Back to list of tutorials

© 2019–2024 Jeffrey Wang. All rights reserved.




In loving memory of Haskell, 19??-2001.