Counting with a While Loop

Download the following code, and get it to compile. This assignment shows you how we can abuse a while loop to make something repeat an exact number of times.

Files Needed

(Do not re-type this program. Simply download a copy of the file by right-clicking and choosing "Save link as..." from the context menu. Save it into your normal code folder.)

Normally, while loops are best for repeating as long as something is true:

But sometimes, we know in advance how many times we want to do something.

We can do that sort of thing with a while loop, but we have to use a counter. A counter is a number variable (int or double) that starts with a value of 0, and then we add 1 to it whenever something happens. So, here, we're going to be adding 1 to the counter everytime we repeat the loop. And when the counter reaches a predetermined value, we'll stop looping.

What You Should See

Type in a message, and I'll display it five times.
Message: All work and no play makes Jack a dull boy.
1. All work and no play makes Jack a dull boy.
2. All work and no play makes Jack a dull boy.
3. All work and no play makes Jack a dull boy.
4. All work and no play makes Jack a dull boy.
5. All work and no play makes Jack a dull boy.

Study Drills

Assignments turned in without these things will receive no credit.

  1. What does n += 1 do? Remove it and see what happens. (Then put it back.) Answer in a comment.
  2. Change the code so that the loop repeats ten times instead of five.
  3. Change the code so that it asks the person how many times to display the message. Then, print it that many times.
    Type in a message, and I'll display it several times.
    Message: HELLO! My name is Inigo Montoya. You killed my father; prepare to die.
    How many times? 3
    1. HELLO! My name is Inigo Montoya. You killed my father; prepare to die.
    2. HELLO! My name is Inigo Montoya. You killed my father; prepare to die.
    3. HELLO! My name is Inigo Montoya. You killed my father; prepare to die.
    

Bonus - Count by 10s

For +10 bonus points, see if you can change the code so that the message still prints the number of times they specified, but the numbers in front count by tens, like so:

Type in a message, and I'll display it several times.
Message: I'm sending out an S.O.S.
How many times? 5
10. I'm sending out an S.O.S.
20. I'm sending out an S.O.S.
30. I'm sending out an S.O.S.
40. I'm sending out an S.O.S.
50. I'm sending out an S.O.S.



©2013–2015 Graham Mitchell

This assignment is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 United States License.
Creative Commons License