[an error occurred while processing this directive]
[an error occurred while processing this directive]
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:
- use
for
loops for definite repetition
- read and write
nested
for loops
- Where you see this icon, you can click it to check the problem in Practice-It!
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:
- initialization ::
int i = 1;
:: start a counter at 1
- test ::
i <= 3;
:: continue as long as the counter i
is less than 3
- execute the statements ::
{ System.out.println("We're number one!"); }
- update ::
i++
:: add 1 to the counter
- 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");
[an error occurred while processing this directive]
[an error occurred while processing this directive]