Unit 4 - Iteration and Loops

For Loops

  • For loops repeat a command or commands.

  • Each for loop declares a counter variable to monitor the loop's progression, usable inside the loop.

  • The header of the for loop has three parts:

    • Initialization: Declares and initializes the counter variable.

    • Test Expression: Checks if the loop should continue. If the test expression evaluates to false the loop terminates and the program continues to the code after the loop.

    • Update: Modify the variable at the end of each loop cycle.

Example:

for (int i = 0; i < 4; i++) {
    System.out.println(i);
}

Tracing the Loop:

  1. int i = 0: Declares and initializes i to 0.

  2. i < 4: Checks if i is less than 4. If true, the loop continues.

  3. System.out.println(i): Prints the value of i.

  4. i++: Increments i by 1 at the end of each loop.

  5. The loop continues until i is no longer less than 4.

While Loops and Do While Loops

  • While Loops: Repeat commands while a Boolean expression remains true.

    while (true) {
        // This loop will run forever
    }
    
    int i = 4;
    while (i > 0) {
        // This loop will also run forever because i is never decremented
    }
    

    To make the above loop terminate, inside the body of the loop decrement the value of i.

int i = 4;
while (i > 0) {
    System.out.println(i);
    i--;
}
  • A while loop might not execute even once if the condition is initially false.

  • Do While Loops: Checks the Boolean expression at the end of the loop so it always runs at least once.

Example using while loop:

int userGuess = 0;
int secretNumber = 23;

while (userGuess != secretNumber) {
    System.out.println("Guess the number I'm thinking of:");
    // Assume user input updates userGuess here
}

System.out.println("You got it right!");

Do While Loop Example:

int i = -2;
do {
    System.out.println(i);
    i--;
} while (i > 0);

Note: Do while loops have a semicolon at the end.

Reversing a String Using a For Loop and Substring

Goal: Reverse the letters in a string.

String original = "pupils";
String reverse = ""; // Empty string

for (int i = original.length() - 1; i >= 0; i--) {
    reverse = reverse + original.substring(i, i + 1);
}

System.out.println(reverse);

Explanation:

  • original.length() returns the number of characters in the string.

  • Strings are treated as arrays internally, so indexing starts at 0.

  • The index of the last character is length - 1.

  • substring(i, i + 1) extracts the character at index i.

  • substring is "inclusive exclusive", meaning it includes the start index but excludes the end index.

  • The loop iterates backward through the string and concatenates each character to the reverse string.

Nested Loops

  • Definition: A loop inside another loop.

  • Outer loop runs once, the inner loop goes through a complete cycle.

  • Useful when working with two-dimensional arrays.

Example:

class NestedLoop {
    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print("# ");
            }
        }
    }
}

Explanation:

  • The outer loop runs twice (i = 0 and i = 1).

  • The inner loop runs three times for each outer loop iteration (j = 0, j = 1, and j = 2).

  • Total inner loop executions: 2 * 3 = 6.

  • Any type of loop (for, while, do while) can be nested.

  • Nested loops can contain more complex algorithms, such as if statements.