< previous page page_242 next page >

Page 242
9. If your program produces an answer that does not agree with a value you've calculated by hand, try these suggestions:
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
a. Redo your arithmetic.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
b. Recheck your input data.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
c. Carefully go over the section of code that does the calculation. If you're in doubt about the order in which the operations are performed, insert clarifying parentheses.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
d. Check for integer overflow. The value of an int variable may have exceeded INT_MAX in the middle of a calculation. Some systems give an error message when this happens, but most do not.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
e. Check the conditions in branching statements to be sure that the correct branch is taken under all circumstances.
Summary
Using logical expressions is a way of asking questions while a program is running. The program evaluates each logical expression, producing a nonzero value if the expression is true or the value zero if the expression is not true.
The If statement allows you to take different paths through a program based on the value of a logical expression. The If-Then-Else is used to choose between two courses of action; the If-Then is used to choose whether or not to take a particular course of action. The branches of an If-Then or If-Then-Else can be any statement, simple or compound. They can even be another If statement.
The algorithm walk-through requires us to define a precondition and a postcondition for each module in an algorithm. Then we have to verify that those assertions are true at the beginning and end of each module. By testing our design in the problem-solving phase, we can eliminate errors that can be more difficult to detect in the implementation phase.
An execution trace is a way of finding program errors once we've entered the implementation phase. It's a good idea to trace a program before you run it, so that you have some sample results against which to check the program's output.
Quick Check
1. Write a C++ expression that compares the variable letter to the constant Z and yields TRUE if letter is less than Z. (pp. 188192)
2. Write a C++ expression that yields TRUE if letter is between A and Z inclusive. (pp. 188196)
3. What form of the If statement would you use to make a C++ program print out Is a letter if the value in letter is between A and Z inclusive, and print out Is not a letter if the value in letter is outside that range? (pp. 202204)
4. What form of the If statement would you use to make a C++ program print out Is a letter only if the value in letter is between A and Z inclusive? (pp. 206209)

 
< previous page page_242 next page >