The real power of a program is realized when the same type of operation must be made over and over.
The repetition control structure is also known as the looping or iteration control structure. Looping is the process of repeatedly executing one or more steps of an algorithm or program; it is essential in programming, as most programs perform repetitious tasks. Every loop consists of the following three parts. Programmers use the repetition structures, referred to more simply as aloop, when they need the computer to repeatedly process one or more program instructions until some condition is met, at which time the repetition structures end. Repetition is also known as iterationor loop.
Constructing a repetitive section of code requires that four elements be present. The first necessary element is a repetition statement. This repetition statement defines the boundaries containing the repeating section of code and also controls whether the code is executed or not. C++ provides three different forms of repetition statements:
while structure
for structure
do-while structure
Each of these statements requires a condition that must be evaluated, which is the second required element for constructing repeating sections of code. Valid conditions are similar to those used in selection statements. If the condition is true, the code is executed; otherwise, it is not.
The third required element is a statement that initially sets the condition. This statement must always be placed before the condition is first evaluated to ensure correct loop execution the first time the condition is evaluated.
Finally, there must be a statement within the repeating section of code that allows the condition to become false. This is necessary to ensure that, at some point, the repetition stop.
The condition being tested can be evaluated at either (1) the beginning or (2) the end of the repeating section of code.
If the test occurs at the beginning of the loop, the type of loop is called a pre-test loop or entrance-controlled loop. If the test occurs at the end of the loop, the type of loop is called a post-test loop or exit-controlled-loop.
In addition to where the condition is tested (pretest or posttest), repeating sections of code are also classified. In a fixed count loop, the condition is used to keep track of how many repetitions have occurred. In this kind of loops, a fixed number of repetitions are performed, at which point the repeating section of code is exited.
In many situations, the exact number of repetitions are not known in advance or the items are too numerous to count beforehand. In such cases, a variable condition loop is used. In a variable condition loop, the tested condition does not depend on a count being achieved, but rather on a variable that can change interactively with each pass through the loop. When a specified value is encountered, regardless of how many iterations have occurred, repetitions stop.
Home > Articles > Programming > C/C++
␡
4.7 Sentinel-Controlled Repetition
< BackPage 7 of 12Next >
This chapter is from the book
Repetition Control Structure C++ Definition
C++ for Programmers
This chapter is from the book
This chapter is from the book
4.7 Sentinel-Controlled Repetition
Let us generalize the class average problem. Consider the following problem:
Develop a class average program that processes grades for an arbitrary number of students each time it is run.
In the previous class average example, the problem statement specified the number of students, so the number of grades (10) was known in advance. In this example, no indication is given of how many grades the user will enter during the program's execution. The program must process an arbitrary number of grades. How can the program determine when to stop the input of grades? How will it know when to calculate and print the class average?
One way to solve this problem is to use a special value called a sentinel value (also called a signal value, a dummy value or a flag value) to indicate 'end of data entry.' The user types grades in until all legitimate grades have been entered. The user then types the sentinel value to indicate that the last grade has been entered.
Clearly, the sentinel value must be chosen so that it cannot be confused with an acceptable input value. Grades on a quiz are normally nonnegative integers, so –1 is an acceptable sentinel value for this problem. Thus, a run of the class average program might process a stream of inputs such as 95, 96, 75, 74, 89 and –1. The program would then compute and print the class average for the grades 95, 96, 75, 74 and 89. Since –1 is the sentinel value, it should not enter into the averaging calculation.
Implementing Sentinel-Controlled Repetition in Class GradeBook
Figures 4.9 and 4.10 show the C++ class GradeBook containing member function deter-mineClassAverage that implements the class average algorithm with sentinel-controlled repetition. Although each grade entered is an integer, the averaging calculation is likely to produce a number with a decimal point. The type int cannot represent such a number, so this class must use another type to do so. C++ provides several data types for storing floating-point numbers, including float and double. The primary difference between these types is that, compared to float variables, double variables can typically store numbers with larger magnitude and finer detail (i.e., more digits to the right of the decimal point—also known as the number's precision). This program introduces a special operator called a cast operator to force the averaging calculation to produce a floating-point numeric result. These features are explained in detail as we discuss the program.
Fig. 4.9 Class average problem using sentinel-controlled repetition: GradeBook header file.
Fig. 4.10 Class average problem using sentinel-controlled repetition: GradeBook source code file.
Fig. 4.11 Class average problem using sentinel-controlled repetition: Creating an object of class GradeBook (Fig. 4.9–Fig. 4.10) and invoking its determineClassAverage member function.
In this example, we see that control statements can be stacked. The while statement (lines 67–75 of Fig. 4.10) is immediately followed by an if...else statement (lines 78– 90) in sequence. Much of the code in this program is identical to the code in Fig. 4.7, so we concentrate on the new features and issues.
Line 55 (Fig. 4.10) declares the double variable average. Recall that we used an int variable in the preceding example to store the class average. Using type double in the current example allows us to store the class average calculation's result as a floating-point number. Line 59 initializes the variable gradeCounter to 0, because no grades have been entered yet. Remember that this program uses sentinel-controlled repetition. To keep an accurate record of the number of grades entered, the program increments variable grade-Counter only when the user enters a valid grade value (i.e., not the sentinel value) and the program completes the processing of the grade. Finally, notice that both input statements (lines 64 and 74) are preceded by an output statement that prompts the user for input.
Floating-Point Number Precision and Memory Requirements
Variables of type float represent single-precision floating-point numbers and have seven significant digits on most 32-bit systems. Variables of type double represent double-precision floating-point numbers. These require twice as much memory as floats and provide 15 significant digits on most 32-bit systems—approximately double the precision of floats. For the range of values required by most programs, float variables should suffice, but you can use double to 'play it safe.' In some programs, even variables of type double will be inadequate—such programs are beyond the scope of this book. Most programmers represent floating-point numbers with type double. In fact, C++ treats all floating-point numbers you type in a program's source code (such as 7.33 and 0.0975) as double values by default. Such values in the source code are known as floating-point constants. See Appendix C, Fundamental Types, for the ranges of values for floats and doubles.
Converting Between Fundamental Types Explicitly and Implicitly
The variable average is declared to be of type double (line 55 of Fig. 4.10) to capture the fractional result of our calculation. However, total and gradeCounter are both integer variables. Recall that dividing two integers results in integer division, in which any fractional part of the calculation is lost (i.e., truncated). In the following statement:
the division calculation is performed first, so the fractional part of the result is lost before it is assigned to average. To perform a floating-point calculation with integer values, we must create temporary values that are floating-point numbers for the calculation. C++ provides the unary cast operator to accomplish this task. Line 81 uses the cast operator static_cast< double >( total ) to create a temporary floating-point copy of its operand in parentheses--total. Using a cast operator in this manner is called explicit conversion. The value stored in total is still an integer.
The calculation now consists of a floating-point value (the temporary double version of total) divided by the integer gradeCounter. The C++ compiler knows how to evaluate only expressions in which the data types of the operands are identical. To ensure that the operands are of the same type, the compiler performs an operation called promotion (also called implicit conversion) on selected operands. For example, in an expression containing values of data types int and double, C++ promotesint operands to double values. In our example, we are treating total as a double (by using the unary cast operator), so the compiler promotes gradeCounter to double, allowing the calculation to be performed—the result of the floating-point division is assigned to average. In Chapter 6, Functions and an Introduction to Recursion, we discuss all the fundamental data types and their order of promotion.
Cast operators are available for use with every data type and with class types as well. The static_cast operator is formed by following keyword static_cast with angle brackets (< and >) around as value should be displayed with two digits of precision to the right of the decimal point—indicated by setprecision( 2 ). The three grades entered during the sample execution of the program in Fig. 4.11 total 257, which yields the average 85.666666.... The parameterized stream manipulator setprecision causes the value to be rounded to the specified number of digits. In this program, the average is rounded to the hundredths position and displayed as 85.67.