A common task we need to do as part of a loop is to accumulate some valueβto keep a running total of something. For example, we might want to add up all the numbers from 1 to 5. We could do that by creating a variable to hold the total, and then adding each number to the total as we go:
This successfully adds up the numbers that 1-5 and gets 15. Key parts of the recipe:
The accumulator variable total is declared before the loop starts. If we put total inside the loop, it would be recreated with each iteration and never grow. (It would also be unavailable on line 11 once we left the loop.)
Now, because we are Updating the loop counter first, by the time we change the accumulator we are using the wrong value. We could fix that by changing the loop itself to count from zero up to but not including five, but It is easier to just have ++i be the last statement.
DO TEST ON CURRENT VALUE
DO WORK WITH CURRENT VALUE
GO TO THE NEXT VALUE (UPDATE LOOP CONTROL VARIABLE)
By updating the loop control variable at the end of the loop, we ensure that after changing the value, the next thing that happens is testing to see if we want to continue with the loop. If so, we use that value, then calculate the next one.
The program below should find the sum of the first 10 natural numbers, but the code is mixed up and contains extra blocks. Put the necessary blocks in the correct order.
int main() {
---
int n = 1;
---
int n = 10; #distractor
---
int sum = 0;
---
int sum = n; #distractor
---
while (n <= 10) {
---
while (n < 100) { #distractor
---
while (n <= 9) { #distractor
---
cout << n << endl; #distractor
---
sum = sum + n;
---
n++;
---
}
---
}