Loops

1. Loops in Java

  • Loops are used to execute a block of code multiple times.

  • Types of loops in Java:

    • While Loop

    • Do-While Loop

    • For Loop

1.1 Loop Components

  • Loop Body: code that gets executed repeatedly.

  • Iteration: each execution of the loop body.

2. The While Statement

  • Definition: Repeats code based on a Boolean expression.

  • Execution Process:

    • Check the Boolean expression before each iteration.

    • If true, execute loop body; if false, exit the loop.

  • Syntax:

    • while (Boolean_Expression) { Statement_1; Statement_2; ...; }

2.1 Example: While Loop

public class WhileExample {
    public static void main(String[] args) {
        int i = 1;
        while (i < 5) {
            System.out.println("Number: " + i);
            i++;
        }
    }
}

3. The Do-While Statement

  • Definition: Executes code at least once, then checks a Boolean expression.

  • Execution Process:

    • Execute loop body first, then check the condition.

    • If true, continue executing; if false, exit the loop.

  • Syntax:

    • do { Statement_1; ...; } while (Boolean_Expression);

3.1 Example: Do-While Loop

public class DoWhileExample {
    public static void main(String[] args) {
        int i = 1;
        do {
            System.out.println("Number: " + i);
            i++;
        } while (i <= 5);
    }
}

4. The For Statement

  • Definition: Primarily used to iterate through a set number of times.

  • Execution Process:

    • Initialize variables, check Boolean expression before iterations, and update variables after each iteration.

  • Syntax:

    • for (Initialization; Boolean_Expression; Update) { Body }

4.1 Example: For Loop

public class ForLoopExamples {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
        }
    }
}

5. The For-Each Loop (Enhanced For Loop)

  • Simplifies iteration over arrays/collections without using an index variable.

  • Syntax:

    • for (Type var : arrayOrCollection) { }

5.1 Example: For-Each Loop

public class ForEachArrayExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        for (int num : numbers) {
            System.out.println("Current number: " + num);
        }
    }
}

6. Nested Loops

  • An inner loop starts over for each iteration of the outer loop.

  • Example:

for (int rowNum = 1; rowNum <= 3; rowNum++) {
    for (int columnNum = 1; columnNum <= 2; columnNum++) {
        System.out.print("row " + rowNum + " column " + columnNum);
    }
    System.out.println();
}

7. Break and Continue Statements

  • Break: Exits the nearest enclosing loop or switch.

  • Continue: Skips to the next iteration of the nearest enclosing loop.

7.1 Example of Break

while (true) {
    if (someCondition) break;
}

8. Infinite Loops

  • Occurs when a loop's condition never becomes false.

  • Common Causes:

    • Forgetting to change the variable tested in the Boolean expression.

8.1 Example of Infinite Loop

while (true) {
    // Will run forever unless broken out of
}

9. Loop Bugs

  • Common Types:

    • Infinite Loops: Caused by improperly designed conditions.

    • Off-By-One Errors: Incorrect loop range causing extra iterations.

9.1 Debugging Techniques

  • Track variable changes during execution.

  • Use tracing statements to identify errors.

10. Assertion Checks

  • Verify program state with assertions.

  • How to Use: assert Boolean_Expression;

10.1 Example

assert value > 0 : "Value must be greater than 0";

11. Preventive Coding

  • Techniques:

    • Incremental Development

    • Code Review

    • Pair Programming

12. Generating Random Numbers

  • Use Java's Random class for pseudo-random number generation.

12.1 Example of Random Number Generation

import java.util.Random;
Random rnd = new Random();
int randomNum = rnd.nextInt(10); // Generates a number between 0-9

13. Conclusion

  • Understanding loops, their structures, and debugging techniques is essential for effective programming in Java. Proper use of the loops can enhance program efficiency and functionality.