You know the solution works for one iteration of the loop but not if it works for other conditions. You can test a larger range of possible conditions by using breakpoints and the Watch window—a window in which you can view the value of selected data or expressions during a debugging session.
·To test conditions using the Watch window:
1.From the Data menu, choose Add Watch.
2.Type the proposed expression:
Period / 12 + 1
3.Choose OK to put this expression in the Watch window.
Now you can see the results of the expression as your program executes, but you have to stop the program at places where the results of this expression are informative. You do this by setting breakpoints. A breakpoint is a location to stop execution or a condition when you want your program to stop.
1.Move to the Source window by clicking it or by using the F6 key.
2.Move the cursor to the printf statement and press F9 to set a breakpoint there.
This breakpoint stops execution and returns control to CodeView each time the printf statement is about to be executed. You can then examine the values of the variables in the Local window and the results of your expression in the Watch window.
3.Press F5 to run the program.
Now each time you press F5, the program executes all statements up to but not including the printf statement. Repeat this until Period equals 12. At this point, you are in the last month of the first year. Notice that the expression you specified does not handle this boundary condition correctly. It changes from 1 to 2 one period too early.
·To adjust for the boundary condition:
1.Add the following expression to the Watch window:
(Period - 1) / 12 + 1
2.Restart the program by choosing Restart from the Run menu.
3.Press F5 to start execution.
The program asks for input again. These values are:
Present Value: | 14500 |
Interest: | 14 |
Number of Periods: | 5 |
Your program stops at the breakpoint you set on the printf statement.
On the first iteration, you'll notice that the watch expression from the last run,
Period / 12 + 1, is still in the Watch window.
·To remove the incorrect expression:
1.From the Data menu, choose Delete Watch.
2.Select the expression you want to delete.
3.Press ENTER to delete the Watch expression from the window.
Run your test; press F5 to step through the loop one iteration at a time. This time, you should get the correct results.
·To switch from CodeView back to PWB:
Choose Exit from the CodeView File menu.
Now that you've built and debugged your program, you may want to reformat your code to make it easier to read. The following section describes how to do this using PWB's editing functions.