University of Washington, AP/CS A

Lab 5: for loops

Except where otherwise noted, the contents of this document are Copyright 2013 Stuart Reges and Marty Stepp.

lab document created by Marty Stepp, Stuart Reges and Whitaker Brand

Today's lab

Goals for this lab:

for loops

A for loop repeats a group of statements a given number of times.

for (initialization; test; update) {
    statement(s) to repeat;
}

Example:

for (int i = 1; i <= 3; i++) {
    System.out.println("We're number one!");
}
System.out.println("/cheering");
Output:
We're number one!
We're number one!
We're number one!
/cheering

for loops

for (initialization; test; update) {
    statement(s) to repeat;
}
for (int i = 1; i <= 3; i++) {
    System.out.println("We're number one!");
}
System.out.println("/cheering");

The for loop keeps executing the println as long as the test condition is met:

  1. initialization :: int i = 1; :: start a counter at 1
  2. test :: i <= 3; :: continue as long as the counter i is less than 3
  3. execute the statements :: { System.out.println("We're number one!"); }
  4. update :: i++ :: add 1 to the counter
  5. go back to step 2 and check the test condition again: i is 1 bigger than it was last time through the loop

Once the test isn't true anymore, Java exits the for loop :: System.out.println("/cheering");

Exercise : What's the output?

What output is produced by the following Java program? Write the output in the box on the right side.

public class OddStuff {
    public static void main(String[] args) {
        int number = 32;
        for (int count = 1; count <= number; count++) {
            System.out.println(number);
            number = number / 2;
        }
    }
}

Output:

32
16
8
4

Exercise : Bottles of beer practice-it