www.gibmonks.com

Main Page




Previous Page
Next Page

[Page 231 (continued)]

Answers to Self-Review Exercises

5.1
  1. False. The default case is optional. If no default action is needed, then there is no need for a default case. Nevertheless, it is considered good software engineering to always provide a default case.

  2. False. The break statement is used to exit the switch statement. The break statement is not required when the default case is the last case. Nor will the break statement be required if having control proceed with the next case makes sense.

  3. False. When using the && operator, both of the relational expressions must be true for the entire expression to be true.

  4. True.

5.2
  1. sum = 0;
    for ( count = 1; count <= 99; count += 2 )
       sum += count;
    
  2. cout << fixed << left
       << setprecision( 1 ) << setw( 15 ) << 333.546372
       << setprecision( 2 ) << setw( 15 ) << 333.546372
       << setprecision( 3 ) << setw( 15 ) << 333.546372
       << endl;
    

    Output is:

     333.5      333.55      333.546
    
  3. cout << fixed << setprecision( 2 )
       << setw( 10 ) << pow( 2.5, 3 )
       << endl;
    

    Output is:

         15.63
    

  4. [Page 232]
  5. x = 1;
    
    while ( x <= 20 )
    {
       cout << x;
    
       if ( x % 5 == 0 )
          cout << endl;
       else
          cout << '\t';
    
       x++;
    }
    
  6. for ( x = 1; x <= 20; x++ )
    {
       cout << x;
    
       if ( x % 5 == 0 )
          cout << endl;
       else
          cout << '\t';
    }
    

    or

    for ( x = 1; x <= 20; x++ )
    {
       if ( x % 5 == 0 )
          cout << x << endl;
       else
          cout << x << '\t';
    }
    
5.3
  1. Error: The semicolon after the while header causes an infinite loop.

    Correction: Replace the semicolon by a {, or remove both the ; and the }.

  2. Error: Using a floating-point number to control a for repetition statement.

    Correction: Use an integer and perform the proper calculation in order to get the values you desire.

    for ( y = 1; y != 10; y++ )
       cout << ( static_cast< double >( y ) / 10 ) << endl;
    
  3. Error: Missing break statement in the first case.

    Correction: Add a break statement at the end of the statements for the first case. Note that this is not an error if the programmer wants the statement of case 2: to execute every time the case 1: statement executes.

  4. Error: Improper relational operator used in the while repetition-continuation condition.

    Correction: Use <= rather than <, or change 10 to 11.


Previous Page
Next Page