Answers to Exercises

1.The correct answer is: “Who knows?” If you said “30”, you forgot that the loop variable values are from 0 through 4, rather than from 1 through 5. On the other hand, if you said “20”, you had the right total of the numbers 0, 2, 4, 6, and 8, but didn't notice that the variable Result was never initialized. Of course, adding anything to an unknown value makes the final value unpredictable. Many current compilers, unfortunately not including the one on the CD in the back of this book, are capable of warning you about such problems. If you're using a compiler that supports such warnings, I recommended that you enable them because that is the easiest way to find such errors, especially in a large program. Unfortunately, a compiler may produce such warnings even when they are not valid, so the final decision is still up to you.

To try this program out, compile morbas00.cpp in the usual manner. Running this program normally isn't likely to give you much information, so you'll probably want to run it under the debugger.

2.The correct answer is 45. In case this isn't obvious, consider the following:
  1. The value of x[0] is set to 3.

  2. In the first for loop, the value of i starts out at 1.

  3. Therefore, the first execution of the assignment statement x[i] = x[i–1] * 2; is equivalent to x[1] = x[0] * 2;. This clearly sets x[1] to 6.

  4. The next time through the loop i is 2, so that same assignment statement x[i] = x[i–1] * 2; is equivalent to x[2] = x[1] * 2;. This sets x[2] to 12.

  5. Finally, on the last pass through the loop, the value of i is 3, so that assignment statement x[i] = x[i–1] * 2; is equivalent to x[3] = x[2] * 2; This sets x[3] to 24.

  6. The second for loop just adds up the values of all the entries in the x Vec; this time, we remembered to initialize the total, Result, to 0, so the total is calculated and displayed correctly.

Running this program normally isn't likely to give you much information, but you might want to run it under control of the debugger.

3.Let's start with Susan's proposed solution to this problem, in Figure 4.21, and the questions that came up during the process.
Figure 4.21. Weight requesting program, first try (codemorbas02.cpp)
#include <iostream>
using namespace std;

int main()
{
  short weight;

  cout << "Please write your weight here. "
;

  cin >> weight

  return 0;
}

Susan: Would this work? Right now by just doing this it brought up several things that I have not thought about before.

First, is the # standard for no matter what type of program you are doing?

Steve: The iostream header file is needed if you want to use <<, >>, cin and cout, which most programs do, but not all.

Susan: Ok, but I meant the actual pound sign (#), is that always a part of iostream?

Steve: It's not part of the filename, it's part of the #include command, which tells the compiler that you want it to include the definitions in the iostream file in your program at that point.

Susan: So then this header is declaring that all you are going to be doing is input and output?

Steve: Not exactly. It tells the compiler how to understand input and output via << and >>. Each header tells the compiler how to interpret some type of library functions; iostream is the one for input and output.

Susan: Where is the word iostream derived from? (OK, io, but what about stream?)

Steve: A stream is C++ talk for “a place to get or put characters”. A given stream is usually either an istream (input stream) or an ostream (output stream). As these names suggest, you can read from an istream or write to an ostream.

Susan: Second, is the really necessary here, or would the program work without it?

Steve: It's optional, however, if you want to use it the should be inside the quotes, since it's used to control the appearance of the output. It can't do that if it's not sent to cout. Without the , the user would type the answer to the question on the same line as the question. With the , the answer would be typed on the next line as the would cause the active screen position to move to the next line at the end of the question.

Susan: OK, that is good, since I intended for the weight to be typed on a different line. Now I understand this much better. As far as why I didn't include the inside the quotes, I can't tell you other than the time of night I was writing or it was an oversight or a typo. I was following your examples and I am not a stickler for details type person.

Now that that's settled, I have another question: Is “return 0” the same thing as an ENTER on the keyboard with nothing left to process?

Steve: Sort of. When you get to that statement in main, it means that you're done with whatever processing you were doing and are returning control to the operating system (the C: prompt).

Susan: How does the program handle the ENTER? I don't see where it comes into the programs you have written. It just seems that, at the end of any pause, an ENTER would be appropriate. So does the compiler just know by the way the code is written that an ENTER will necessarily come next?

Steve: The >> input mechanism lets you type until you hit an ENTER (or a space in the case of a string), then takes the result up to that point.

One more point. We never tell the user that we have received the information. I've added that to your example.

Figure 4.22 illustrates the compiler's output for that erroneous program.

Figure 4.22. Error messages from the erroneous weight program (codemorbas02.cpp)
Error E2206 MORBAS02.cpp 8: Illegal character '' (0x5c) in function main()
Error E2379 MORBAS02.cpp 8: Statement missing ; in function main()
Error E2379 MORBAS02.cpp 12: Statement missing ; in function main()

And Figure 4.23 shows the corrected program.

Figure 4.23. The corrected weight program (codemorbas03.cpp)
#include <iostream>
using namespace std;

int main()
{
   short weight;

   cout << "Please write your weight here: ";

   cin >> weight;

   cout << "I wish I only weighed " << weight << " pounds.";

   return 0;
}

4.This was an offshoot of the previous question, which occurred when Susan wondered when the program in Figure 4.23 would terminate. Let's start from that point in the conversation:

Susan: Would this only run once? If so how would you get it to repeat?

Steve: We could use a while loop. Let's suppose that we wanted to add up all the weights that were entered. Then the program might look like Figure 4.24.

Figure 4.24. The weight totalling program (codemorbas04.cpp)
#include <iostream>
using namespace std;

int main()
{
   short weight;
   short total;

   cout << "Please type in your weight, typing 0 to end:";
   cin >> weight;

   total = weight;

   while (weight > 0)
     {
     cout << "Please type in your weight, typing 0 to end:";
     cin >> weight;
     total = total + weight;
     }

   cout << "The total is: " << total << endl;
   return 0;
}

In case you were wondering, the reason we have to duplicate the statements to read in the weight is that we need an initial value for the variable weight before we start the while loop, so that the condition in the while will be calculated correctly.

By the way, there's another way to write the statement

total = total + weight;

that uses an operator analogous to ++, the increment operator:

total += weight;

This new operator, +=, means “add what's on the right to what's on the left”. The motivation for this shortcut, as you might imagine, is the same as that for ++: it requires less typing, is more likely to be correct, and is easier to compile to efficient code. Just like the “increment memory” instruction, many machines have an “add (something) to memory” instruction. It's easier to figure out that such an instruction should be used for an expression like x += y than in the case of the equivalent x = x + y. Let's see what Susan has to say about this notation:

Susan: Now I did find something that was very confusing. You say that += means to “add what's on the right to what's on the left” but your example shows that it is the other way around. Unless this is supposed to be mirror imaged or something, I don't get it.

Steve: No, the example is correct. total += weight; is the same as total = total + weight;, so we're adding the value on the right of the += (i.e., weight) to the variable on the left (i.e., total). Is that clearer now?

Susan: OK, I think I got it now, I guess if it were more like an equation, you would have to subtract total from the other side when you moved it. Why is it that the math recollection that I have instead of helping me just confuses me?

Steve: Because, unfortunately, the = is the same symbol used to mean “is equal to” in mathematics. The = in C++ means something completely different: “set the thing on the left to the value on the right”.

Running this program normally isn't likely to give you much information, so you might want to run it under control of the debugger.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset