본문 바로가기
개념/혼자 공부하는 Javascript

chapter 4) continue

by kiseno 2024. 11. 30.
728x90
반응형
SMALL
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        let output = 0
        for (let i = 1; i<10; i++){
            if (i % 2 ===1){
                continue
            }
            output += i
        }
        alert(output)
    </script>
</head>
<body>

</body>
</html>

### Script Breakdown

- **Variable Initialization**: `let output = 0` initializes a variable named `output` to store the cumulative sum of even numbers.

- **For Loop**: `for (let i = 1; i < 10; i++)` creates a loop that iterates from `1` through `9`. The loop counter `i` starts at `1` and increases by `1` on each iteration, stopping before it reaches `10`.

- **Conditional Check and Continue**: 
  - Inside the loop, `if (i % 2 === 1)` checks if the current number (`i`) is odd by using the modulo operator `%` to find the remainder when `i` is divided by `2`. If the remainder is `1`, the number is odd.
  - If the current number is odd, the `continue` statement is executed, which immediately skips to the next iteration of the loop, bypassing the subsequent code that would add the number to `output`.

- **Accumulation**: When the number is even (i.e., the `if` condition does not hold), `output += i` adds the current even number `i` to the cumulative sum stored in `output`.

- **Result Alert**: After the loop completes, `alert(output)` displays the final sum of even numbers between 1 and 9.

### Calculation Explanation

The loop iterates through the numbers 1 to 9. On each iteration, it checks if the number is odd. If so, it skips that number and continues to the next iteration. If the number is even, it adds the number to `output`. Therefore, the sum includes only even numbers: 2, 4, 6, and 8.

### Expected Output

The sum of even numbers between 1 and 9 (inclusive) is `2 + 4 + 6 + 8 = 20`. Thus, the alert dialog will display `20`.

728x90
반응형
LIST

'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글

chapter 4) for  (0) 2024.12.02
chapter 4) while  (0) 2024.12.01
chapter 4) break  (0) 2024.11.29
chapter 3) Using nested conditionals  (0) 2024.11.28
chapter 3) Using conditional operators  (0) 2024.11.27