For loops

  • One of the most tested concepts in the APCSA exam
  • Skills 3.C, 4.C, and 5.C

Three Parts of a For Loop

  • Initialization of a variable
  • Test condition
for (initialize; test condition; change)
{
   loop body
}

Example

for (int x = 1; x <= 5; x++) {
    System.out.println(x);
}
1
2
3
4
5

Control Flow Diagram

image

  • The code in the initialization area is executed only one time before the loop begins
  • the test condition is checked each time through the loop and the loop continues as long as the condition is true
  • the loop control variable change is done at the end of each execution of the body of the loop
  • When the loop condition is false, execution will continue at the next statement after the body of the loop.

Hacks

- Change the code above to iterate instead from 1-5 to 10-15. (Print numbers 10-15)

- Convert 10 numbers of your choice from two temperature units (F to C, C to F, C to K)

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
  System.out.println(cars[i]);
}
Volvo
BMW
Ford
Mazda