There are a couple of ways to interrupt a loop: one is to use the keyword break and the other is to use the keyword continue.
In the following example, a loop-continuation-condition is set to test if the number is less than 20. If true, the number variable will increment by one and the current value of the variable number will be added to the total as is defined by the variable sum.
So if we let the following loop continue without any sort of interruption, the number will be 20 and the sum will be 210.
However, adding the keyword break after the test is performed within the while loop will cause the loop to stop if the sum is at or larger than 100.
The output for the number variable will be 14 and for the sum variable, 105.
The next example deals with the keyword continue.
We start the loop by testing whether the number is less than 20. If so, the number variable is incremented by 1. The next condition that it checks is whether the number variable is set to 10 or 11. If so, the continue keyword causes the loop to skip any of the code following the condition and restarts from the beginning testing whether the variable number is less than 20. In this case, neither 10 nor 11 will be added to the sum.
If the code executed without the continue keyword, sum would be equal to 210.
However, due to the test and the continue keyword being executed prior to sum, the output will be 189.
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20 = 189
In the following example, a loop-continuation-condition is set to test if the number is less than 20. If true, the number variable will increment by one and the current value of the variable number will be added to the total as is defined by the variable sum.
So if we let the following loop continue without any sort of interruption, the number will be 20 and the sum will be 210.
However, adding the keyword break after the test is performed within the while loop will cause the loop to stop if the sum is at or larger than 100.
The output for the number variable will be 14 and for the sum variable, 105.
The next example deals with the keyword continue.
We start the loop by testing whether the number is less than 20. If so, the number variable is incremented by 1. The next condition that it checks is whether the number variable is set to 10 or 11. If so, the continue keyword causes the loop to skip any of the code following the condition and restarts from the beginning testing whether the variable number is less than 20. In this case, neither 10 nor 11 will be added to the sum.
If the code executed without the continue keyword, sum would be equal to 210.
However, due to the test and the continue keyword being executed prior to sum, the output will be 189.
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20 = 189
Comments
Post a Comment