|
![]() |
Using Repetition in Problem Solving
The Need for Repetition | Repetition Structures | Testing Programs with Loops
Repetition in programming is about repeating a set of instructions a correct number of times to accomplish the task at hand. In this lecture, we will start by considering how repetition manifests itself in some example problems. Then we will look at the repetition structures provided by C++ and discuss when to use each of the three different repetition structures. Finally, we will look at the impact that using repetition has on program testing.
The Need for Repetition | ![]() |
Many problems' solutions have steps that need to be repeated a number of times. For example, consider the physical process of driving a nail through a piece of wood. We could break this down into a simple algorithm as follows:
This simple problem illustrates several important things. First, the first three steps are needed to prepare, or initialize, conditions so the steps that will be repeated can be effective. Without this initialization, the solution will not work! Second, Steps 4-6 are repeated until a condition is satisfied that indicates the repetition has done all the work required. Third, it should be obvious that each time Step 4 is repeated, the nail head gets closer to the wood, so progress is being made towards the condition that will eventually terminate the repetition.There are basically two different types of repetition situations that can occur. The first occurs when the number of repetitions cannot be determined, as in the hammer and nail problem. This type of repetition must be controlled by some condition, which must be tested for after each pass through the repeated steps. The second type of repetition requires knowing how many times the repeated steps need to execute. This type of repetition is often referred to as count controlled. A simple example problem of this type is as follows:
Problem: Find the average of 10 numbers. This involves summing 10 numbers together and then dividing by 10.
- Set a sum variable to 0.
- Repeat the next step 10 times.
- Get next number and add it to the sum.
- Divide sum by 10 to get the average.
Any time a problem indicates that some form of processing must be done which involves a set of values, repetition will be required in the solution. When the size of the set of values is specified or can be easily determined, then a count controlled repetition is appropriate. If the size of the data set cannot be easily determined, then repetition will still be needed, but the repetition will continue until some condition is reached. The condition that controls when repetition terminates must be expressed in terms of the values of the problem. For instance, suppose we want to find out how many characters are in a string of characters that is terminated by the '\0' character. We have no idea where the '\0' character will be, but we know that we can stop counting when we see it. So our algorithm would look something like this:
Note that this algorithm follows a similar pattern: Prepare for the repetition by initializing everything needed during the repetition (steps 1-3), then do the repetition, testing for when the repetition must end, and within the repeated steps, changing the value being tested in the loop control condition (next character from string).
One thing to consider when using repetition is that whatever is contained within the statements that are repeated will be executed with each iteration of the repetition. For instance, if you need to collect 10 numbers from a user, do you need to prompt the user to input each value that makes the prompt part of the statements that are repeated, or can you prompt the user to enter 10 values one time, which makes the prompt part of the initialization rather than part of the statements which are repeated? Most users don't need to be told over and over to do the same thing. It is also more efficient to do the prompt before the repetition starts so the repetition itself will contain fewer statements and will execute faster! Repetition structures have a big impact on the performance of any program that contains them.
Repetition Structures | ![]() |
Given that we have clearly defined different types of repetition needs, it should not be surprising that C++ provides different repetition structures. For count controlled repetition, C++ provides the for loop. Its basic structure is as follows:
for(initialize expression; test expression; modify expression)
{ // Open curly bracket marks beginning of loop body
// Loop body repeats as long as the test expression is true
} // Close curly bracket marks end of the loop body
Notice that there are three expressions within the parenthesis of the for statement. Each of the first two expressions ends with a semicolon. The initialize expression provides a convenient way of setting the loop control variable to an initial value.
for(int count = 0;…….
In the case above, the count variable is declared and set to the initial value 0. The test expression is used to control when the loop terminates. If the test expression is true, the body of the loop executes. When the test expression becomes false, the loop terminates immediately and execution continues at the statement following the closing curly bracket marking the end of the body of the for statement.
for(int count = 0; count < 100;……
In the case above, as long as count is less than 100, the loop body will continue to execute. The third expression allows for a convenient way to modify the loop control variable. Remember, for any type of repetition, each iteration must change the value of the loop control variable in order to avoid an infinite loop condition.
for(int count = 0; count < 100; count++)
Here, the value of the loop control variable is incremented each time around the loop. So, to clarify the sequence of events which occur when using a for loop:
Note that it is possible that the body of a for loop will never execute. This could happen if the test expression were false when executed the first time.
Check Your Knowledge | |||
|
C++ provides a while loop and a do-while loop, which are repetition structures that are more appropriate for situations where the number of repetitions is not known. The primary difference between these two loop structures is when the condition that controls loop execution is checked. For the while loop, the condition is checked before the loop is entered for the first time. This means that a while loop body may never execute. For the do-while loop, the body executes first, then the loop control condition is checked. This means that a do-while will always execute its body at least one time. The following are examples of problems involving repetition that are easily solved with a while or a do-while loop.
Problem: A user wishes to place an order for 1 or more items. Collect the order information, and then display the order information.
- Initialize item counter to 0.
- Prompt user to enter item info.
- Collect and store item info.
- Increment item counter.
- Ask user if they have more items to enter.
- Collect user response.
- While user response is yes, repeat by going to Step 2.
- For each item collected (0 - value of counter variable) do Step 9.
- Display next item.
Note that this problem used a do-while loop structure first (Steps 2 - 7), followed by a for loop structure (Steps 8-9). Note that Step 1 covers initialization of a variable that is to be used within the repetition structure. The loop body executes before the loop condition is tested (Step 7). A slightly different problem description would result in a while loop structure being more appropriate.
Problem: A user wishes to place an order for 0 or more items. Collect the order information, and then display the order information. The algorithm is as follows:
- Initialize item counter to 0.
- Ask user if they wish to enter an item.
- Collect user response.
- While user response is yes, repeat Steps 5 - 9.
- Prompt user to enter item info.
- Collect and store item info.
- Increment item counter.
- Ask user if they have more items to enter.
- Collect user response.
- For each item collected (0 - value of counter variable) do Step 9.
- Display next item.
Notice that there is a bit more initialization to do before reaching the start of the repetition in this case. Steps 1 - 3 initialize the count variable used in the loop as well as getting an initial value for the loop control variable. This loop structure allows the possibility that there will be 0 items entered; that is, the body of the while loop may not execute at all!
Check Your Knowledge | |||
|
Testing Programs with Loops | ![]() |
The primary thing about repetition is getting the right number of iterations. This is especially true when writing count-controlled loops. Here are some examples of how to calculate the number of times a loop body will execute. This assumes that the loop variable is being incremented by 1.
Initial Condition | Termination Condition | Number Of Iterations of Loop Body |
---|---|---|
Count = 0 | Count < 100 | 100 (Final - Initial) |
Count = 1 | Count < 101 | 100 (Final - Initial) |
Count = 0 | Count <= 100 | 101 (Final - Initial + 1) |
Count = 50 | Count <= 100 | 51 (Final - Initial + 1) |
Notice how changing the test condition from < to <= adds 1 to the number of times the loop body executes. Running a loop backwards would result in a similar table. This assumes that the loop variable is being decremented by 1.
Initial Condition | Termination Condition | Number Of Iterations of Loop Body |
---|---|---|
Count = 100 | Count > 0 | 100 (Initial - Final) |
Count = 100 | Count >= 0 | 101 (Initial - Final + 1) |
Count = 100 | Count >= 1 | 100 (Initial - Final + 1) |
Count = 50 | Count > 0 | 50 (Initial - Final) |
The most common problem with loops is being off by 1. This is manifested when a program either stops one iteration too soon and fails to process the last data item or goes one iteration too far and tries to process a data item that is simply not available. Both of these cases result in program errors. The first case will result in the processing done by the iteration being incorrect. The second can result in a variety of problems, including the program accessing an illegal address and terminating! Testing programs containing loops must include test cases that verify all program loops are executing the correct number of iterations.
To summarize, we have examined how to recognize the need for repetition when analyzing a problem. We have learned when to use the for loop, the while loop, and the do-while loop to implement repetition within a program. Finally, we have considered the impact that using repetition has on testing a program for correctness.
![]() |