13.5 Break and Continue in Loops (10 mins)

  1. Introduction to break and continue Statements:

    • Break: Exits a loop completely, stopping its execution.

      • Use case: When you want to terminate the loop early, such as when a certain condition is met.

      • Example:

        for (let i = 1; i <= 10; i++) {
          if (i === 5) {
            break;  // Exit the loop when i equals 5
          }
          console.log(i);  // Outputs: 1, 2, 3, 4
        }
    • Continue: Skips the current iteration and moves to the next iteration of the loop.

      • Use case: When you want to skip certain values or conditions, but keep the loop running.

      • Example:

        for (let i = 1; i <= 5; i++) {
          if (i === 3) {
            continue;  // Skip the current iteration when i equals 3
          }
          console.log(i);  // Outputs: 1, 2, 4, 5 (skips 3)
        }
  2. How break and continue Work in Loops:

    • Break: Stops the loop entirely and moves execution to the next part of the program.

    • Continue: Skips the rest of the code in the current loop iteration but continues with the next iteration.

  3. When to Use break and continue:

    • Break: Use when you need to stop a loop once a certain condition is met (e.g., finding a specific value in an array).

    • Continue: Use when you need to skip over certain elements in the loop (e.g., filtering out invalid inputs).

Student Activity (10 mins):

Objective: Incorporate break and continue statements into the previous loops to control the flow of iteration.


Step-by-Step Activity:

  1. Modify the Previous Loops to Include break and continue:

    Instructions:

    • Open your previous HTML file (loops_activity.html) and update the script to include break and continue statements.

  2. Example Code:

  3. Run the file in a browser:

    • Open the HTML file in a browser and use Developer Tools (F12 or right-click and select Inspect > Console) to view how break and continue statements affect the loop’s behavior.


Challenge:

  1. Write a Loop to Find the First Number Divisible by Both 3 and 5:

    • Use the break statement to exit the loop once a number divisible by both 3 and 5 is found.

    • Example:

  2. Write a Loop to Skip All Multiples of 4:

    • Use the continue statement to skip numbers divisible by 4.

    • Example:


Activity Follow-up Questions:

  1. How does the break statement impact the flow of a loop compared to continue?

  2. Can you think of a real-world example where you would want to use break to stop a loop early?

  3. In what scenarios would you use continue to skip certain iterations while still completing the loop?


Expected Outcome:

Students will:

  • Understand how to control loop flow using break to stop execution early and continue to skip specific iterations.

  • Apply these concepts to modify existing loops and solve real-world problems that require breaking or skipping certain conditions.

Last updated