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
Goals for this lab:
for
loops for definite repetitionnested
for loopsfor
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:
int i = 1;
:: start a counter at 1i <= 3;
:: continue as long as the counter i
is less than 3{ System.out.println("We're number one!"); }
i++
:: add 1 to the counteri
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");
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 |
for
loop that produces the song Bottles of Beer on the Wall:
10 bottles of beer on the wall, 10 bottles of beer Take one down, pass it around, 9 bottles of beer on the wall 9 bottles of beer on the wall, 9 bottles of beer Take one down, pass it around, 8 bottles of beer on the wall ... (output continues in the same pattern) ... 1 bottles of beer on the wall, 1 bottles of beer Take one down, pass it around, 0 bottles of beer on the wall