For Loops

In this example, multiply the value of the variable instead of incrementing or decrementing.

1
2
3
4
5
6
7
8
9
10
11
//for loop prints powers of 2: 1, 2, 4, 8, 16, 32, 64, 128, 256 
package numbers;
public class Numbers {
  public static void main(String[] args) {
    int p;
    for (p = 1; p<500; p*=2) { //we multiply instead of adding
      System.out.print(p+" ");
    }//loop
    System.out.println();
  }//main
}//class
CODE

Output:

1 2 4 8 16 32 64 128 256 

Note that if you start with 0 and multiply each time, you will have an endless loop!.

NEXT: