www.gibmonks.com

Main Page




Previous Page
Next Page

[Page 69 (continued)]

Answers to Self-Review Exercises

2.1

a) main. b) left brace ({), right brace (}). c) semicolon. d) newline. e) if.

2.2
  1. False. Comments do not cause any action to be performed when the program is executed. They are 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. A single cout statement with 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";


[Page 70]
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
 4  using std::cout; // program uses cout
 5  using std::cin; // program uses cin
 6  using std::endl; // program uses endl
 7
 8  // function main begins program execution
 9  int main()
10  {
11     int x; // first integer to multiply
12     int y; // second integer to multiply
13     int z; // third integer to multiply
14     int result; // the product of the three integers
15
16     cout << "Enter three integers: "; // prompt user for data
17     cin >> x >> y >> z; // read three integers from user
18     result = x * y * z; // multiply the three integers; store result
19     cout << "The product is " << result << endl; // print result; end line
20
21     return 0; // indicate program executed successfully
22  } // 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 will be executed whether or not the condition in the if statement is true.] The semicolon after the right parenthesis is a null (or empty) statementa statement that does nothing. We will learn more about the null statement in the next chapter.

  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.


Previous Page
Next Page