While Loops

Compare the two programs below.

1
2
3
4
5
6
7
8
9
10
11
12
13
// Print 0 1 2 3 4 5 
package numbers;
//import java.util.*;
public class Numbers {
  public static void main(String[] args) {
    int num=0;
    while (num<=5) {
      System.out.print(num+" ");
      num=num+1;
    }//loop
    System.out.println(); 
  }//main
}//class
CODE
1
2
3
4
5
6
7
8
9
10
11
// Print 0 1 2 3 4 5 using while and ++
package numbers;
//import java.util.*;
public class Numbers {
  public static void main(String[] args) {
    int num=0;
    while (num<=5) 
      System.out.print(num++ +" ");
    System.out.println(); 
  }//main
}//class
CODE

In the first program the body of the loop has 2 statements, one to print and one to increment num.

The second program has just one statement in the body of the loop: the increment is combined with the print statement.

Notice that we don't even have to enclose the body of the loop in { } because there is just one statement.

Both programs print 0 1 2 3 4 5.

NEXT: