C++ Sentinel Controlled Loop

Posted By admin On 27/11/21

I am having trouble writing a sentinel controlled loop in LC-3 assembly language. I know that you must store the sentinel somewhere in memory and that when the sentinel is detected, then the loop is done. However, how do you actually write this in LC-3 code. Lets say I have the following example. In a sentinel-controlled loop, the prompts requesting data entry should explicitly remind the user of the sentinel value. After the loop terminates, the if. Else statement at lines 6980 executes. The condition at line 69 determines whether any grades were input. Sentinel-controlled repetition is sometimes called indefinite repetition because it is not known in advance how many times the loop will be executed. It is a repetition procedure for solving a problem by using a sentinel value (also called a signal value, a dummy value or a flag value) to indicate 'end of data entry'.

Home > Articles > Programming > C/C++

  • C Programming Tutorials brought to you by TONY TUTORIALS.
  • Sentinel Controlled Loop In a sentinel controlled loop the change part depends on data from the user. It is awkward to do this inside a for statement. So the change part is omitted from the for statement and put in a convenient location.
  1. 4.7 Sentinel-Controlled Repetition
< BackPage 7 of 12Next >
This chapter is from the book
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.

Related Resources

  • Book $63.99
  • eBook (Watermarked) $51.19
  • Online Video $119.99
download the slides used in this presentation
PowerPoint pptx Acrobat pdf

Objectives

While engaging with this module, you will...

  1. become literate in the C++ syntax of looping
  2. apply your understanding of loops from the last module to create a working C++ loop
  3. analyze the differences between a while and a do-while loop

The while Loops

The syntax for the while is:

while(expression)
statement

And the details:

  • while is a reserved word.
  • Expression must be fully contained within the parentheses.
  • expression is a valid C++ expression that evaluates to true or false or a numerical value.
  • statement is a simple or compound C++ statement (with all semi-colons included).
  • This is a pre-test loop. This means that the condition in expression is checked before the body of the while loop (statement) might possibly be executed. This implies that the body of the loop may never be executed.
  • How it works: expression is evaluated. If it is true, the body (statement) is executed and control passes back up to expression to be evaluated again. If it is false, control passes out of the loop statement.

So, it is easy to see that, as the loop executes, something in the controlling expression must change! If not, then the loop will execute the body of the loop ad infinitum, or until the power company cuts your power. Since that may take a while (no pun intended), let’s just avoid them.

while (7)
cout<<”hello”<<endl;

This is a ridiculous loop. It is an infinite loop. Remember that 7 ≠ 0 is true. The expression 7 is checked for truth value, the output statement is executed, 7 is checked for value and is true, the output statement is executed again, etc ad infinitum. This loop has no LCV, hence no initialization, check, or update of the LCV.

cout<<'enter number between 5 and 89, inclusive: ';
cin>>input;
while (input < 5 input > 89)
{
cout<<'that value is unacceptable... try again: ';
cin>>input;
}
cout<<'the value '<<input<<'is in the interval [5, 89]'<<endl;

C++ Sentinel Value

Thus, we can now 'cleanse' user input in the sense that we can range check values prompted for. Note: in this course, you will always assume that the value given upon prompt of a user is the right type. That is, if you prompt for a char, you get a char; if you prompt for a number, you get a number, etc. The code to insure this is long and we don’t need to fool with it. So you see that the input from the initial prompt/readin is the LCV that is checked in the while expression, updated inside the loop, and initialized before the loop. Execution cannot leave the loop until proper input is obtained.

long sum = 0;
short counter = 1; // LCV initialization
while (counter <= 100) // LCV check
{
sum += counter;
counter++ ; // LCV update
}
cout<<'sum of first 100 integers is '<<sum;

Here’s an example that could demonstrate a tutorial for learning math:

Controlled

const string QUESTION1 = 'What is 8 – 3 ?'; //if question1 changes, change ANS_Q1
const short ANS_Q1 = 5;
cout<<'QUESTION #1: '<<QUESTION1<<' ';
cin>>ans;
while ( (ans – ANS_Q1) != 0 )
{
cout<<”Your answer is incorrect. Please try again.'<<endl;
cout<<QUESTION1<<' ';
cin>>ans;
}
cout<<'Your answer is CORRECT! Congratulations!'<<endl;

So, you see that there is a computation in the expression that controls the loop. This is perfectly permissible. More complicated expressions are indeed allowed. Notice that, in this last example for instance, if you remove the cin>>ans; statement inside the loop, you will end up with an infinite loop. Why?

Now, you can see that the while statement is a pre-check loop; the condition (expression) is checked before the loop body is repeated (or not). Thus, the body is never guaranteed to execute even once.

The do-while Statement:

The C++ syntax is:

do
statement
while (expression);

And the details:

  • do and while are reserved words.
  • Expression must be fully contained within the parentheses.
  • expression is a valid C++ expression that evaluates to true or false or a numerical value.
  • statement is a simple or compound C++ statement (with all semi-colons included).
  • Do not forget the semicolon after the closing paren.
  • This is a post-test loop. This means that the condition in expression is checked after the body of the loop (statement) is executed. This implies that the body of the loop will always be executed at least once. I emphasize this point because it is very relevant.
  • How it works: Statement is executed. Then, expression is evaluated. If it is true, statement is executed again. If false, control passes out of the do-while statement.

Thus, you see that in this type of loop, the body of the loop will be executed at least once. Thinking of what you might want done at least once but possibly many times, prompting/reading in comes to mind.

short age, count = 0;
do
{
cout<<'Please enter your age: ';
cin>>age;
count++;
if (age <= 0 age > MAX_AGE)
{
cout<<'This is not a valid value!'<<endl;
if (count MAX_ALLOWABLE_TRIES)
exit(1); // continued bad input; bailing out!
}
} while (age <= 0 age > MAX_AGE);

Thus, we may now range-check out user input with a single prompt/read in. The user cannot exit this loop without entering reasonable information. Notice also that I have put the while on the same line as the closing brace. This is done not for the compiler, but for formatting reasons. If the while was put on the next line, it appears that we have begun another while loop, confusing anyone who reads the code. Also notice that I have included a counter variable that will keep track of how many times the user attempts to enter information. If that number of attempts reaches a predetermined “level of tolerance” (MAX_ALLOWABLE_TRIES), then the exit function is invoked and the run of the program terminated.

For example, prompt for and read in an integer between 2 and 174, inclusive, that is a multiple of three.

do
{
cout<<”Enter an integer between 2 and 174 (inclusive) that is a multiple of 3: “;
cin>>input;
} while (!(input >= 2 && input <= 174 && input%3 0));

Here I have built a logical expression that describes what I want to include, and then negated it with the ‘!’ operator.

0.1. Syllabus
2. Programming Fundamentals
2.1. C++ Basics
2.3. Reserved Words
3.1. Logical and Relational
5. Loops
5.1. Sentinel Loops
6. Advanced Branching
7. Odds and Ends
8. Functions
8.1. Reference Parameters
8.3. Dedication of Duty
8.5. Function Overloading
8.7. Inline
9. Random Number Generation
10. Multiple Files
11. Arrays
11.1. Working with Arrays
13. Character Arrays
13.1. Built-in Functions
14. File I/O
14.1. Reading a File
15. Objects
15.1. Defining Classes
15.3. Const Functions
15.5. Constructors
15.7.0 Overloading Operators
15.7.2 IsEquals
15.7.4 Constructor Overload
15.8.1 Bracket Operator
15.9. Static Members

C++ Sentinel Controlled Loop

16. Output Formatting
17. Namespaces
18. Enumerations
19. Sample Homework
19.1. Assignment #2
19.3. Assignment #4
19.5. Assignment #6
19.7. Assignment #8
19.9. Assignment #10