For Loops

In this example, n starts with 10 and counts backwards. It is important to think through the code and make sure that you don't have an endless loop. If we start with 10 and subtract 1 each time, n>=0 will eventually be false and the loop will end.

1
2
3
4
5
6
7
8
9
10
11
//Blast off: a count down
package numbers;
public class Numbers {
  public static void main(String[] args) {
    int n;
    for(n=10; n>=0; n--) { //count BACKWARDS
      System.out.println(n);
    }//loop
    System.out.println("Blast off!");
  }//main
}//class
CODE

Output:

10
9
8
7
6
5
4
3
2
1
0
Blast off!

Note that "Blast off" prints just once, when the loop ends.

NEXT: