Skip to content

For Loops

  • Lesson
  • 2 min read
  • 3 of 4 in this chapter

Fixed Loops

While loops will run forever until their condition is false.

In contrast, for loops run for a fixed, or preset, number of loops.

So for example, we can have a for loop run 10 times.

Java
for(int i = 0; i < 10; i++) {
System.out.println("Loop #" + i);
}

If you run this, you will print 10 lines and ten lines exactly.

But what exactly is happening inside the parenthesis of the for loop? Let's break it down:

  • We create an int i = 0;, to start us off. It can be any name or number, as long as it doesn't previously exist. It's also important to know that this is a local variable to the loop. We can't use i anywhere, only within the loop.
  • We create a condition (just like the while loop) involving i. In this case, loop while i<10.
  • Finally, we choose how we want to increment i. In this case, we want to add 1 on every loop (allowing i to increase). We could make this i+=2, or even i--, granted that i starts higher or that the condition changes

And that's basically it.

Remember that we don't use a ; after i++, since nothing happens after it.

Stop on input

Now let's take the code from the last lesson and change it to a for loop.

Java
Scanner input = new Scanner(System.in);
boolean stop = false;

for(int i = 1; i <= 10 && !stop; i++) {
  System.out.println("Loop #" + i);

  System.out.println("Do you want to stop? (y/n)");
  String choice = input.nextLine();
  if(choice.equals("y")) {
    stop = true;
    System.out.println("Loop stopped after " + i);
  }
}

We removed one variable, number, and decremented i by 1, when choice.equals("y") because it will go up by 1 at the end of the loop anyways. We also moved the final print inside the loop.