🔁

Understanding General For Loops in Java

Sep 25, 2024

General For Loops in Java

Introduction

  • The lecture introduces general for loops in Java.
  • General format of a for loop consists of:
    • Initialization: Executed once at the start.
    • Test: Determines if the loop should continue.
    • Increment: Modifies the variable after each loop iteration.

Basic For Loop Structure

  • Example: for (initialization; test; increment)
  • Initialization example: int i = 0
    • This sets up the loop variable.
  • Test example: i < 10
    • Checks if the loop should continue.
  • Increment example: i++
    • Modifies the loop variable after each run.

Examples of General For Loops

Countdown Program

  • Task: Count down from 10 to 0.
  • Code: for (int i = 10; i >= 0; i--) { System.out.println(i); }
  • Explanation:
    • Starts with i = 10.
    • Tests if i is greater than or equal to 0.
    • Decrements i by 1 each iteration (i--).

Counting By Twos

  • Task: Count by twos up to 100.
  • Code: for (int i = 0; i <= 100; i += 2) { System.out.println(i); }
  • Explanation:
    • Starts with i = 0.
    • Tests if i is less than or equal to 100.
    • Increments i by 2 each iteration (i += 2).

Modifying the Increment

  • Example: Change increment from 2 to 3 for counting by threes.
  • Code: for (int i = 0; i <= 100; i += 3) { System.out.println(i); }
  • Explanation:
    • This makes the loop count by threes.

Conclusion

  • General for loops offer flexibility with initialization, test, and increment steps.
  • Allow for various counting patterns and control structures in Java programming.