Section 9c

Repeating a Test


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Repeated Testing and Actions

At this point, you can see what it takes to make a working loop. However, there is more to consider. 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 C 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.

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.

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.