24sp ver.
Note: this is for the Spring 2024 iteration of CSE 121. Looking for a different quarter? Please visit https://courses.cs.washington.edu/courses/cse121/.
Nested For Loops¶
(loops inside loops, can be used to produce complex text patterns)
Example
for (int i = 1; i <= 5; i++>) {
    for (int j = 1; j <= (5 - i); j++) {
        System.out.print(".");  // print dots
    }
    System.out.println(i);  // print line number
}
Output
....1
...2
..3
.4
5
Update Statements¶
(common update statements in for loops)
| Statement | Description | 
|---|---|
| i++ | increment iby1; same asi = i + 1 | 
| i += 1 | increment iby1; same asi = i + 1 | 
| i-- | decrement iby1; same asi = i - 1 | 
| i -= 1 | decrement iby1; same asi = i - 1 | 
Random¶
(produce random numbers)
import java.util.*;  // We must include this in order to use Random!
// Create a Random object
Random rand = new Random();
// Generating values
int a = rand.nextInt(10); // generating an integer in the range of 0 to 9
int b = rand.nextInt(10) + 1; // generating an integer in the range of 1 to 10
int c = rand.nextInt(7) + 4; // generating an integer in the range of 4 to 10
Methods¶
| Method | Description | 
|---|---|
| nextInt() | random integer | 
| nextInt(max) | random integer between 0(inclusive) andmax(exclusive) | 
| nextDouble() | random double between 0.0(inclusive) and1.0(exclusive) | 
Formula for Generating a Random Number between min - max (inclusive)¶
| Steps | Example | 
|---|---|
| 1. What is the desired min? | 4 | 
| 2. What is the desired max? | 10 | 
| 3. Calculate the range = max - min + 1 | 10 - 4 + 1 = 7 | 
| 4. Substitute into: rand.nextInt(range) + min | rand.nextInt(7) + 4 | 
Fenceposting¶
(pulling one iteration out of the loop)
Example
System.out.print(1);               // one number to start with
for (int i = 2; i <= 5; i++) {
    System.out.print(", " + i);    // commas between numbers
}
System.out.println();              // end the line
Output
1, 2, 3, 4, 5