Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

4.8 Nested Control Statements

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 number—either 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.
  3. 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 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.

Conversion to Class Analysis

The C++ class, Analysis, in Fig. 4.12–Fig. 4.13, solves the examination results problem—two sample executions appear in Fig. 4.14.

Fig. 4.12 Examination-results problem: Analysis header file.

 1  // Fig. 4.12: 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

               

Fig. 4.13 Examination-results problem: Nested control statements in Analysis source code file.

 1  // Fig. 4.13: Analysis.cpp
 2  // Member-function definitions for class Analysis that
 3  // analyzes examination results.
 4  #include <iostream>
 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 << "\nFailed " << failures << endl;
40
41      // determine whether more than eight students passed
42      if ( passes > 8 )
43         cout << "Raise tuition " << endl;
44  } // end function processExamResults

               

Lines 16–18 of Fig. 4.13 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 22–36) loops 10 times. During each iteration, the loop inputs and processes one exam result. Notice that the if...else statement (lines 29–32) 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 in 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 in lines 42–43 determines whether more than eight students passed the exam and, if so, outputs the message "Raise Tuition".

Demonstrating Class Analysis

Figure 4.14 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.14 shows the input and output from two sample executions of the program. At the end of the first sample execution, the condition in line 42 of member function processExamResults in Fig. 4.13 is true—more than eight students passed the exam, so the program outputs a message indicating that the tuition should be raised.

Fig. 4.14 Test program for class Analysis.

 1  // Fig. 4.14: fig04_14.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
  • + Share This
  • 🔖 Save To Your Account