CSE 121
CSE 121
  • Home / Calendar
  • Syllabus
  • Assignments
  • Resubmissions
  • Exam
  • Getting Help
  • Course Staff
  • Grading Rubrics
  • Resources

  • Course Tools
  • EdStem
  • Gradescope
  • Grade Calculator
  • Anonymous Feedback
  • Acknowledgements

Nested For Loops, Random, and the Math Class


Nested For Loops¶

(loops inside loops, can be used to produce complex text patterns)

Nested For Loop 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
}

Nested For Loop Output

....1
...2
..3
.4
5

Update Statements¶

(common update statements in for loops)

Statement Description
i++ increment i by 1; same as i = i + 1
i += 1 increment i by 1; same as i = i + 1
i-- decrement i by 1; same as i = i - 1
i -= 1 decrement i by 1; same as i = i - 1

Fenceposting¶

(pulling one iteration out of the loop)

Fenceposting 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

Fenceposting Output

1, 2, 3, 4, 5

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) and max (exclusive)
nextDouble() random double between 0.0 (inclusive) and 1.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

Math Class¶

(a set of useful methods for performing mathematical operations)

Method Returns
Math.abs(value) absolute value (make nonnegative)
Math.max(value1, value2) larger of two values
Math.min(value1, value2) smaller of two values
Math.pow(base, exp) base to the exp power
Math.sqrt(num) square root of num

Example

// Evaluates to 8.0
double num = Math.pow(2, 3);
// Evaluates to 9.0
double big = Math.max(num, Math.sqrt(81));
System.out.println(big + " is big!");

Output

9.0 is big!

Search

Search the class website; related sections and pages will appear below. Note: this search is not as forgiving with typos as other search engines.