Tracing

In this lesson, we will continue finding mistakes in a loop by tracing its execution.

Programmers often check the correctness of a program by mentally tracing the paths of its logic. When doing so is difficult or fails to detect an error, we can trace its actual execution by displaying the values of key variables and by displaying messages that indicate the path taken. In this lesson, we consider tracing the logical path of loops.

Places to check a loop’s execution

The method sumOfSquares in the previous lesson correctly implements our desired function, as you should have seen from your output. But what if it hadn’t? When debugging a method, we should examine the values of key variables at both the beginning and the end of the method. We can check the initial values of any input arguments and also check the computed results just before the method ends. Sometimes, knowing only that the method was called will be sufficient.

When debugging a loop, we examine key variables, including those used to control the loop, at the following places:

  • Before the loop begins
  • At the beginning of the loop’s body
  • At the end of the loop’s body
  • After the loop ends

The program given below shows the method sumOfSquares from the previous lesson with additional statements that report the status of its computation at these four points, as well as at the beginning and end of the method. The main method has a selection of the calls to sumOfSquares that appear in the previous lesson. Click the RUN button and notice the results.

Get hands-on with 1400+ tech skills courses.