Counting Up Once More

Line: Loopy Line
Easy Iteration Learning Outcome One Exercise
Type: Exercise
You should have completed: Counting Up Again This topic leads to: Debugger

Summary

This exercise revisits an earlier example of data processing (in this case adding up) and makes the code more efficient by using iteration structures.

Task

  1. Load your application from Counting Up Again
  2. Change the for loop to a while loop - can you make a while loop that behaves just like the for loop?
  3. Run the program and check that it still adds up correctly
  4. Modify the code to let the user decide how many times to go round the loop
  5. Run the program and try with '0' times round the loop
  6. Change the while loop to a do...while loop
  7. Run the program and try with '0' times round the loop - is the result different?

Questions

  1. How would you change the code so that the user is asked whether to continue or not and the code behaves accordingly?

Using a while loop executes until some condition becomes true, rather than a set number of times. It is the ideal solution when we cannot know or calculate how many times to repeat a task, for example where the user is selecting whether to continue or not. Do...while loops are useful in similar circumstances with the exception that they always run at least once.