For the next example, we once again formulate an algorithm by using pseudocode and top-down, stepwise refinement, and write a corresponding C++ program. We’ve seen that control statements can be stacked on top of one another (in sequence). In this case study, we examine the only other structured way control statements can be connected—namely, by nesting one control statement within another.
Consider the following problem statement:
A college offers a course that prepares students for the state licensing exam for realestate brokers. Last year, ten of the students who completed this course took the exam. The college wants to know how well its students did on the exam. You’ve been asked to write a program to summarize the results. You’ve been given a list of these 10 students. Next to each name is written a 1 if the student passed the exam or a 2 if the student failed.
Your program should analyze the results of the exam as follows:
Input each test result (i.e., a 1 or a 2). Display the message “Enter result” on the screen each time the program requests another test result.
Count the number of test results of each type.
Display a summary of the test results, indicating the number of students who passed and the number who failed.
If more than eight students passed the exam, print “Bonus to instructor!”
After reading the problem statement carefully, we make the following observations:
The program must process test results for 10 students. A counter-controlled loop can be used, because the number of test results is known in advance.
Each test result has a numeric value—either a 1 or a 2. Each time it reads a test result, the program must determine whether it’s a 1 or a 2. We test for a 1 in our algorithm. If the number is not a 1, we assume that it’s a 2. (Exercise 4.20 considers the consequences of this assumption.)
Two counters are used to keep track of the exam results—one to count the number of students who passed the exam and one to count the number who failed.
After the program has processed all the results, it must decide whether more than eight students passed the exam.
Let’s proceed with top-down, stepwise refinement. We begin with a pseudocode representation of the top:
Analyze exam results and decide whether a bonus should be paid
Once again, the top is a complete representation of the program, but several refinements are likely to be needed before the pseudocode can evolve naturally into a C++ program.
Our first refinement is
Initialize variables
Input the 10 exam results, and count passes and failures
Print a summary of the exam results and decide whether a bonus should be paid
Here, too, even though we have a complete representation of the entire program, further refinement is necessary. We now commit to specific variables. Counters are needed to record the passes and failures, a counter will be used to control the looping process and a variable is needed to store the user input. The variable in which the user input will be stored is not initialized at the start of the algorithm, because its value is read from the user during each iteration of the loop.
The pseudocode statement
Initialize variables
can be refined as follows:
Initialize passes to zero
Initialize failures to zero
Initialize student counter to one
Notice that only the counters are initialized at the start of the algorithm.
The pseudocode statement
Input the 10 exam results, and count passes and failures
requires a loop that successively inputs the result of each exam. We know in advance that there are precisely 10 exam results, so counter-controlled looping is appropriate. Inside the loop (i.e., nested within the loop), a double-selection structure will determine whether each exam result is a pass or a failure and will increment the appropriate counter. The refinement of the preceding pseudocode statement is then
While student counter is less than or equal to 10
Prompt the user to enter the next exam result
Input the next exam result
If the student passed
Add one to passes
Else
Add one to failures
Add one to student counter
We use blank lines to isolate the If…Else control structure, which improves readability.
The pseudocode statement
Print a summary of the exam results and decide whether a bonus should be paid
can be refined as follows:
Print the number of passes
Print the number of failures
If more than eight students passed
Print “Bonus to instructor!”
The complete second refinement appears in Fig. 4.13. Notice that blank lines are also used to set off the While structure for program readability. This pseudocode is now sufficiently refined for conversion to C++.
The program that implements the pseudocode algorithm and two sample executions are shown in Fig. 4.14. Lines 8–10 and 16 of main
declare the variables that are used to process the examination results.
Initializing local variables when they’re declared helps you avoid any compilation warnings that might arise from attempts to use uninitialized variables and helps you avoid logic errors from using uninitialized variables.
The while
statement (lines 13–29) loops 10 times. During each iteration, the loop inputs and processes one exam result. Notice that the if
…else
statement (lines 20–25) for processing each result is nested in the while
statement. If the result
is 1
, the if
…else
statement increments passes
; otherwise, it assumes the result
is 2
and increments failures
. Line 28 increments studentCounter
before the loop condition is tested again at line 13. After 10 values have been input, the loop terminates and line 32 displays the number of passes
and failures
. The if
statement at lines 35–37 determines whether more than eight students passed the exam and, if so, outputs the message "Bonus to instructor!"
Figure 4.14 shows the input and output from two sample program executions. During the first, the condition at line 35 is true—more than eight students passed the exam, so the program outputs a message to bonus the instructor.
As you learned in Chapter 2, C++11 introduced list initialization so that you can use one syntax to initialize a variable of any type. Consider line 10 of Fig. 4.14:
unsigned int studentCounter{1};
You also can write this as
unsigned int studentCounter = {1};
though the form without =
is preferred. Prior to C++11, you would have written this as
unsigned int studentCounter = 1;
For fundamental-type variables, list-initialization syntax prevents narrowing conversions that could result in data loss. For example, previously you could write
int x = 12.7;
which attempts to assign the double
value 12.7
to the int
variable x
. In this case, C++ converts the double
value to an int
, by truncating the floating-point part (.7
), a narrowing conversion that loses data. The actual value assigned to x
is 12
. Many compilers warn you of this, but still allow the statement to compile. However, using list initialization, as in
int x{12.7};
or
int x = {12.7};
yields a compilation error, thus helping you avoid a potentially subtle logic error. For example, Apple’s Xcode LLVM compiler gives the error
Type 'double' cannot be narrowed to 'int' in initializer list
We’ll discuss additional list-initializer features in later chapters.
You might think that the following statement from Fig. 4.10
int average{total / 10}; // int division yields int result
contains a narrowing conversion, but total
and 10
are both int
values, so the initializer value is an int
. If in the preceding statement total
were a double
variable or if we used the double
literal value 10.0
, then the initializer value would have type double
. In this case the compiler would issue an errror message due to an attempted narrowing conversion.