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

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

For Loops


25sp ver.

Note: this is for the Spring 2025 iteration of CSE 121. Looking for a different quarter? Please visit https://courses.cs.washington.edu/courses/cse121/.

The For Loop¶

(repeats a group of statements a fixed number of times)

for (initialization; test; update) {
    statement;
    ...
    statement;
}

Example

for (int i = 1; i <= 10; i++) {
    System.out.println(i + " squared is " + (i * i));
}

For Loop Control Flow Diagram¶

Flow chart of for loop control with 5 steps explained below
  • (Step 1) First, perform the initialization once at the beginning.
  • (Step 2) Then test: is the test true?
    • (Step 3) If the test is true, execute the statements inside the for loop body.
      • (Step 4) Perform the update and go back to Step 2.
    • (Step 5) If the test is not true, execute the statements that are immediately after the for loop body.

Ways to Increment and Decrement the Update Variable¶

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

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.