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 useianywhere, only within the loop. - We create a condition (just like the while loop) involving
i. In this case, loop whilei<10. - Finally, we choose how we want to increment
i. In this case, we want to add 1 on every loop (allowingito increase). We could make thisi+=2, or eveni--, granted thatistarts higher or that the condition changes
And that's basically it.
Remember that we don't use a
;afteri++, 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 decrementediby 1, whenchoice.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.