Home > Articles > Programming > C/C++

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

This chapter is from the book

Answers to Self-Review Exercises

2.1

  1. main.
  2. left brace ({), right brace (}).
  3. semicolon.
  4. newline.
  5. if.

2.2

  1. False. Comments do not cause any action to be performed when the program is executed. They're used to document programs and improve their readability.
  2. True.
  3. True.
  4. True.
  5. False. C++ is case sensitive, so these variables are unique.
  6. True.
  7. True.
  8. False. The operators *, / and % have the same precedence, and the operators + and - have a lower precedence.
  9. False. One statement with cout and multiple \n escape sequences can print several lines.

2.3

  1. int c, thisIsAVariable, q76354, number;
  2. std::cout << "Enter an integer: " ;
  3. std::cin >> age;
  4.                   if ( number != 7 )
       std::cout << "The variable number is not equal to 7\n";
    
                   
  5. std::cout << "This is a C++ program\n" ;
  6. std::cout << "This is a C++\nprogram\n" ;
  7. std::cout << "This\nis\na\nC++\nprogram\n" ;
  8. std::cout << "This\tis\ta\tC++\tprogram\n" ;

2.4

  1. // Calculate the product of three integers
  2.                   int x;
    int y;
    int z;
    int result;
    
  3. cout << "Enter three integers: " ;
  4. cin >> x >> y >> z;
  5. result = x * y * z;
  6. cout << "The product is " << result << endl;
  7. return 0 ;

2.5

(See program below.)

 1  // Calculate the product of three integers
 2  #include <iostream> // allows program to perform input and output
 3  using namespace std; // program uses names from the std namespace
 4
 5  // function main begins program execution
 6  int main()
 7  {
 8     int x; // first integer to multiply
 9     int y; // second integer to multiply
10     int z; // third integer to multiply
11     int result; // the product of the three integers
12
13     cout << "Enter three integers: "; // prompt user for data
14     cin >> x >> y >> z; // read three integers from user
15     result = x * y * z; // multiply the three integers; store result
16     cout << "The product is " << result << endl; // print result; end line
17  } // end function main

2.6

  1. Error: Semicolon after the right parenthesis of the condition in the if statement. Correction: Remove the semicolon after the right parenthesis. [Note: The result of this error is that the output statement executes whether or not the condition in the if statement is true.] The semicolon after the right parenthesis is a null (or empty) statement that does nothing. We'll learn more about the null statement in Chapter 4.
  2. Error: The relational operator =>.

    Correction: Change => to >=, and you may want to change "equal to or greater than" to "greater than or equal to" as well.

  • + Share This
  • 🔖 Save To Your Account