While Loops

This program doubles the value of num each time through the loop.

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

To Do:

  • Trace through this to figure out what will be printed.
  • Run this program in your compiler. Modify it to run longer or to print a different sequence.
  • Why is this easier to do with a while loop than a for loop?

NEXT: