Program 5.4: A Simple for Loop

//Count to ten

class CountToTen  {

  public static void main (String args[]) {
  
    for (int i = 1; i <= 10; i = i + 1) {  
      System.out.println(i);
    } 
    System.out.println("All done!");

  }

} 
Here's the output:

% javac CountToTen.java
% java CountToTen
1
2
3
4
5
6
7
8
9
10
All done!
Program 5.4 began by setting the variable i to 1. Then it checks to see if one is in fact less than or equal to ten. Since one is less than ten, the program prints it. Finally it adds one to i and starts over.

i is now 2. The program checks to see if 2 is less than 10. It is! So the program prints "2" and adds one to i again.

i is now three. Once again the code checks to see that 3 is less than or equal to 10. Most human beings get bored about here so let's skip ahead. Fortunately computers don't get bored, and very soon the computer has counted to the point where i is ten. The computer prints "10" and adds one to ten.

Now i is eleven. Eleven is not less than or equal to ten so the computer does not print it. Rather it moves to the next statement after the end of the for loop,

System.out.println("All done!");

The computer prints "All Done!" and the program ends.


Copyright 1996 Elliotte Rusty Harold
elharo@sunsite.unc.edu
This Chapter
Examples
Home