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:
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)
Figure 4.22 illustrates the compiler's output for that erroneous program. Figure 4.22. Error messages from the erroneous weight program (codemorbas02.cpp)
And Figure 4.23 shows the corrected program. Figure 4.23. The corrected weight program (codemorbas03.cpp)
| |||
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:
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.
Running this program normally isn't likely to give you much information, so you might want to run it under control of the debugger. |