Repeated Testing and Actions
At this point, you can see what it takes to make a working loop. However, consider another example or two. For example, think about a change-making program. If your program is required to make penny change, there is a chance that you will have to give as many as four pennies as change. Without loops, you would have to implement the following program code segment four times, as shown here.
if there is still penny change to be returned
{
give out one penny
subtract one penny from the "change to be returned" variable
}
if there is still penny change to be returned
{
give out one penny
subtract one penny from the "change to be returned" variable
}
if there is still penny change to be returned
{
give out one penny
subtract one penny from the "change to be returned" variable
}
if there is still penny change to be returned
{
give out one penny
subtract one penny from the "change to be returned" variable
}
With a loop, you really only change one word for this process.
while there is still penny change to be returned
{
give out one penny
subtract one penny from the "change to be returned" variable
}
Logically, you can rephrase the "while" statement with something a little more mathematical, such as the following. This will make it easy to translate to the Java programming language.
// loop while the change to be returned is greater than zero
{
// give out one penny
// subtract one penny from the "change to be returned" variable
}
Now look at the loop information.
- initializing condition: some amount of penny change is specified
- condition to continue: not all of the pennies have been returned
- updating action: each time a penny is returned, decrement the number of pennies still to be returned
Consider one more example of this kind of loop before going on. Suppose you want to count the number of letters in a sentence. Think your way through the loop information.
- initializing condition: there is a sentence assumed to have at least one letter, and a period at the end of the sentence
- condition to continue: the period has not been found yet
- updating action: a letter is found and counted, and the looping operation goes on to look at the next character
Now look at the pseudo code.
// loop while newest character found is not a period
{
// count the character
// (increment a character counter)
// go look at the next character
}
It turns out that while this is a good representation of a character-counting loop, there is a small flaw in the logic for some circumstances. This will be discussed further in the next topic. However, for right now, watch the following video to see some follow up support for this topic.