The objective for today's lab is to investigate the sentinel controlled
while loop and the for loop.
The first part of this lab involves creating a sentinel
controlled while loop. The code is supposed to allow you to
enter numbers until a 0 is entered. For each number entered, processing
simply consists of an output of the number. But, the sentinel is never
to be processed.
- Create a New Project
- Run this
code
The loop is never entered. So, remove the = 0 initialization
- Now try this
code
Now the sentinel is processed. So, lets put the input back prior
to the loop.
- Now VERY CAREFULLY try this
code with an infinite loop
- Now try this
correct code
Notice that a correct sentinel controlled loop follow this outline:
input first value
Use WHILE to check value against sentinel value
Input the next value
Processing in the loop
-
Average sample one code
-
Average sample two code
-
Average correct code
The second part of this lab is to explore the for loop.
- Create a New Project
- Run this
code
Modify the code to count from 6 to 52
- Run this
code
Compare the while loop to the for loop
- Modify the code so that the user gets to input the first value
code
- Modify the code so that the user gets to input the increment
code
- What if the user wants to count backwards?
code
This doesn't work....
- We don't need to subtract a negative. Just add the negative step
value.
code
- This isn't correct either. Should the test still be <=?
code