5.15 Answers to Chapter Questions

I l @ ve RuBoard

Answer 5-1: The programmer accidentally omitted the end-comment symbol ( */ ) after the comment for height. The comment continues onto the next line and engulfs the width variable declaration. Example 5-13 shows the program with the comments underlined .

Example 5-13. Triangle area program
 #include <iostream> int  height;  /* The height of the triangle   int  width;    /* The width of the triangle*/  int  area;  /* Area of the triangle (computed) */  int main(  ) {     std::cout << "Enter width and height? ";     std::cin >> width >> height;     area = (width * height) / 2;     std::cout << "The area is " << area << '\n';     return (0); } 

Some people may think that it's unfair to put a missing comment problem in the middle of a chapter on basic declarations. But no one said C++ was fair. You will hit surprises like this when you program in C++ and you'll hit a few more in this book.

Answer 5-2: The problem is with the way we specified the element of the array: array[2,4] . This should have been written: array[2] [4] .

The reason that the specification array[2,4] does not generate a syntax error is that it is legal (but strange ) C++. There is a comma operator in C++ (see Chapter 29), so the expression 2,4 evaluates to 4 . So array[2,4] is the same as array[4] . C++ treats this as a pointer (see Chapter 15), and what's printed is a memory address, which on most systems looks like a random hexadecimal number.

Answer 5-3: The problem is that the Zip code 02137 begins with a zero. That tells C++ that 02137 is an octal constant. When we print it, we print in decimal. Because 02137 8 is 1119 10 the program prints:

 New York's Zip code is: 1119 
I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

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