Loop Design Example
Let's try to design a loop to find the sum of all integers from 0 to n. First, let's consider the pre-condition for the loop. We need two variables for this loop: a variable that acts as a counter for the loop and another variable to hold the sum of all integers through each iteration of the loop. Since we're looking for the sum from 0 to n, let's initialize both variables to 0.
Next, we define the post-condition for the loop. Upon loop termination, the value of the variable sum must be equals to the sum of all integers from 0 to n. How do we decide when does the loop terminate? The loop should terminate when we have added all integer from 0 until n. Therefore, the loop should not terminate until we have added n to sum.
|
Loops while do...while for Control Structure Loop Design Methodology Common Loop Errors |
||
Next >> | |||
Fook Yuen Sin - Team 1 |