Formulating Algorithms: Nested Control Statements

Formulating Algorithms Nested Control Statements

For the next example, we once again formulate an algorithm by using pseudocode and topdown, stepwise refinement, and write a corresponding C++ program. We have seen that control statements can be stacked on top of one another (in sequence) just as a child stacks building blocks. 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 real estate 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 have been asked to write a program to summarize the results. You have 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:

  1. Input each test result (i.e., a 1 or a 2). Display the prompting message "Enter result" each time the program requests another test result.
  2. Count the number of test results of each type.
  3. Display a summary of the test results indicating the number of students who passed and the number who failed.
  4. If more than eight students passed the exam, print the message "Raise tuition."

After reading the problem statement carefully, we make the following observations:

  1. 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.
  2. Each test result is a numbereither a 1 or a 2. Each time the program reads a test result, the program must determine whether the number is a 1 or a 2. We test for a 1 in our algorithm. If the number is not a 1, we assume that it is a 2. (Exercise 4.20 considers the consequences of this assumption.)
  3. Two counters are used to keep track of the exam resultsone to count the number of students who passed the exam and one to count the number of students who failed the exam.
  4. After the program has processed all the results, it must decide whether more than eight students passed the exam.

Let us proceed with top-down, stepwise refinement. We begin with a pseudocode representation of the top:


Analyze exam results and decide whether tuition should be raised

Once again, it is important to emphasize that the top is a complete representation of the program, but several refinements are likely to be needed before the pseudocode evolves 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 if tuition should be raised


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 last variable is not initialized, 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. Here it is known in advance that there are precisely 10 exam results, so counter-controlled looping is appropriate. Inside the loop (i.e., nested within the loop), an if...else statement 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 tuition should be raised

can be refined as follows:


Print the number of passes
Print the number of failures

If more than eight students passed
     Print "Raise tuition"

The complete second refinement appears in Fig. 4.15. 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++.

Figure 4.15. Pseudocode for examination-results problem.

(This item is displayed on page 158 in the print version)


 1  Initialize passes to zero
 2  Initialize failures to zero
 3  Initialize student counter to one
 4
 5  While student counter is less than or equal to 10
 6      Prompt the user to enter the next exam result
 7      Input the next exam result
 8
 9      If the student passed
10           Add one to passes
11      Else
12           Add one to failures
13
14      Add one to student counter
15
16  Print the number of passes
17  Print the number of failures
18
19  If more than eight students passed
20      Print "Raise tuition"

 

Conversion to Class Analysis

The C++ class that implements the pseudocode algorithm is shown in Fig. 4.16Fig. 4.17, and two sample executions appear in Fig. 4.18.


Figure 4.16. Examination-results problem: Analysis header file.

 1 // Fig. 4.16: Analysis.h
 2 // Definition of class Analysis that analyzes examination results.
 3 // Member function is defined in Analysis.cpp
 4
 5 // Analysis class definition
 6 class Analysis
 7 {
 8 public:
 9 void processExamResults(); // process 10 students' examination results
10 }; // end class Analysis

Figure 4.17. Examination-results problem: Nested control statements in Analysis source code file.

(This item is displayed on pages 158 - 159 in the print version)

 1 // Fig. 4.17: Analysis.cpp
 2 // Member-function definitions for class Analysis that
 3 // analyzes examination results.
 4 #include 
 5 using std::cout;
 6 using std::cin;
 7 using std::endl;
 8
 9 // include definition of class Analysis from Analysis.h
10 #include "Analysis.h"
11
12 // process the examination results of 10 students
13 void Analysis::processExamResults()
14 {
15 // initializing variables in declarations 
16 int passes = 0; // number of passes 
17 int failures = 0; // number of failures 
18 int studentCounter = 1; // student counter
19 int result; // one exam result (1 = pass, 2 = fail)
20
21 // process 10 students using counter-controlled loop
22 while ( studentCounter <= 10 )
23 {
24 // prompt user for input and obtain value from user
25 cout << "Enter result (1 = pass, 2 = fail): ";
26 cin >> result; // input result
27
28 // if...else nested in while 
29 if ( result == 1 )  // if result is 1, 
30  passes = passes + 1;  // increment passes; 
31 else  // else result is not 1, so
32  failures = failures + 1; // increment failures 
33
34 // increment studentCounter so loop eventually terminates
35 studentCounter = studentCounter + 1;
36 } // end while
37
38 // termination phase; display number of passes and failures
39 cout << "Passed " << passes << "
Failed " << failures << endl;
40
41 // determine whether more than eight students passed
42 if ( passes > 8 )
43 cout << "Raise tuition " << endl;
44 } // end function processExamResults

Figure 4.18. Test program for class Analysis.

(This item is displayed on pages 159 - 160 in the print version)

 1 // Fig. 4.18: fig04_18.cpp
 2 // Test program for class Analysis.
 3 #include "Analysis.h" // include definition of class Analysis
 4
 5 int main()
 6 {
 7 Analysis application; // create Analysis object 
 8 application.processExamResults(); // call function to process results
 9 return 0; // indicate successful termination
10 } // end main
 
 Enter result (1 = pass, 2 = fail): 1
 Enter result (1 = pass, 2 = fail): 1
 Enter result (1 = pass, 2 = fail): 1
 Enter result (1 = pass, 2 = fail): 1
 Enter result (1 = pass, 2 = fail): 2
 Enter result (1 = pass, 2 = fail): 1
 Enter result (1 = pass, 2 = fail): 1
 Enter result (1 = pass, 2 = fail): 1
 Enter result (1 = pass, 2 = fail): 1
 Enter result (1 = pass, 2 = fail): 1
 Passed 9
 Failed 1
 Raise tuition
 
 
 Enter result (1 = pass, 2 = fail): 1
 Enter result (1 = pass, 2 = fail): 2
 Enter result (1 = pass, 2 = fail): 2
 Enter result (1 = pass, 2 = fail): 1
 Enter result (1 = pass, 2 = fail): 1
 Enter result (1 = pass, 2 = fail): 1
 Enter result (1 = pass, 2 = fail): 2
 Enter result (1 = pass, 2 = fail): 1
 Enter result (1 = pass, 2 = fail): 1
 Enter result (1 = pass, 2 = fail): 2
 Passed 6
 Failed 4
 

Lines 1618 of Fig. 4.17 declare the variables that member function processExamResults of class Analysis uses to process the examination results. Note that we have taken advantage of a feature of C++ that allows variable initialization to be incorporated into declarations (passes is initialized to 0, failures is initialized to 0 and studentCounter is initialized to 1). Looping programs may require initialization at the beginning of each repetition; such reinitialization normally would be performed by assignment statements rather than in declarations or by moving the declarations inside the loop bodies.

The while statement (lines 2236) loops 10 times. During each iteration, the loop inputs and processes one exam result. Notice that the if...else statement (lines 2932) 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 35 increments studentCounter before the loop condition is tested again at line 22. After 10 values have been input, the loop terminates and line 39 displays the number of passes and the number of failures. The if statement at lines 4243 determines whether more than eight students passed the exam and, if so, outputs the message "Raise Tuition".

Demonstrating Class Analysis

Figure 4.18 creates an Analysis object (line 7) and invokes the object's processExamResults member function (line 8) to process a set of exam results entered by the user. Figure 4.18 shows the input and output from two sample executions of the program. At the end of the first sample execution, the condition at line 42 of member function processExamResults in Fig. 4.17 is truemore than eight students passed the exam, so the program outputs a message indicating that the tuition should be raised.


Introduction to Computers, the Internet and World Wide Web

Introduction to C++ Programming

Introduction to Classes and Objects

Control Statements: Part 1

Control Statements: Part 2

Functions and an Introduction to Recursion

Arrays and Vectors

Pointers and Pointer-Based Strings

Classes: A Deeper Look, Part 1

Classes: A Deeper Look, Part 2

Operator Overloading; String and Array Objects

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

Templates

Stream Input/Output

Exception Handling

File Processing

Class string and String Stream Processing

Web Programming

Searching and Sorting

Data Structures

Bits, Characters, C-Strings and structs

Standard Template Library (STL)

Other Topics

Appendix A. Operator Precedence and Associativity Chart

Appendix B. ASCII Character Set

Appendix C. Fundamental Types

Appendix D. Number Systems

Appendix E. C Legacy Code Topics

Appendix F. Preprocessor

Appendix G. ATM Case Study Code

Appendix H. UML 2: Additional Diagram Types

Appendix I. C++ Internet and Web Resources

Appendix J. Introduction to XHTML

Appendix K. XHTML Special Characters

Appendix L. Using the Visual Studio .NET Debugger

Appendix M. Using the GNU C++ Debugger

Bibliography



C++ How to Program
C++ How to Program (5th Edition)
ISBN: 0131857576
EAN: 2147483647
Year: 2004
Pages: 627

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net