Java Reference
In-Depth Information
As we can see, the programmer merely observed the symptom and addressed the problem by
adding a software patch. However, if you look at the code, not only will the program execute
extra statements, it is also an example of a partially understood concept. It appears that the
programmer does not have a good grasp of why the earlier program produced four lines rather
than three. Adding a patch eliminated the symptom, but it is a poor programming practice.
The programmer must resolve why the program produced four lines. Looking at the program
closely, we can see that the four lines are produced because the outer loop executes four times.
The values assigned to loop control variable i are 1 , 2 , 3 ,and 4 . This is an example of the
classic ''off by one'' problem. (In the ''off by one'' problem, either the loop executes one too
many or one too few times.) We can eliminate this problem by correctly setting the values of
the loop control variable. For example, we can rewrite the loops as follows:
for (i = 1; i <= 3; i++)
{
sum = 0;
for (j = 1; j <= 4; j++)
{
num = infile.nextInt();
System.out.print(num + " ");
sum = sum + num;
}
System.out.println("sum = " + sum);
}
This code fixes the original problem without using a software patch. It also represents
good programming practice. The complete modified program is available with
the Additional Student Files at www.cengagebrain.com. The program is named
Ch5_LoopWithBugsCorrectedProgram.cpp .
Debugging Loops
As we have seen in the earlier debugging sections, no matter how carefully a program is
designed and coded, errors are likely to occur. If there are syntax errors, the compiler will
identify them. However, if there are logical errors, we must carefully look at the code or
even maybe at the design to try to find the errors. To increase the reliability of the
program, errors must be discovered and fixed before the program is released to the users.
Once an algorithm is written, the next step is to verify that it works properly. If the algorithm
is a simple sequential flow or contains a branch, it can be hand traced or you can use the
debugger, if any, provided by the IDE. Typically, loops are harder to debug. The correctness
of a loop can be verified by using loop invariants. A loop invariant is a set of statements that
remains true each time the loop body is executed. Let p be a loop invariant and q be the
(logical) expression in a loop statement. Then p && q remains true before each iteration of the
loop and p && not(q) is true after the loop terminates. The full discussion of loop invariants is
beyond the scope of the topic. However, you can learn about loop invariants in the topic:
Discrete Mathematics: Theory and Applications, D.S. Malik and M.K. Sen, Cengage Learning,
Asia, 2010. Here we give a few tips that you can use to debug a loop.
DEBUGGING
 
Search WWH ::




Custom Search