Tracing is a technique used to simulate a dry run through the code or pseudocode line by line by hand as if you are the computer executing the code. Tracing can be used for debugging or proving that your program runs correctly or for figuring out what the code actually does. Trace tables can be used to track the values of variables as they change throughout a program. To trace through code, write down a variable in each column of the trace table and keep track of its value throughout the program. Some trace tables also keep track of the output and the line number you are currently tracing.
For example, here is a simple algorithm that adds x to the total every time through the loop which is executed 3 times.
x ← 2 total ← 0 REPEAT 3 TIMES < total ← total + x >DISPLAY(total)
Try tracing through the code and see if your results match the trace table below:
x | total | Output |
---|---|---|
2 | 0 | |
2 | ||
4 | ||
6 | 6 |
Break into POGIL teams of 4 and assign each team member one of the following roles. Record your answers using this worksheet. (File-Make a Copy to have a version you can edit.)
Role | Responsibility |
---|---|
Facilitator | Reads the questions aloud, keeps track of time and makes sure everyone contributes appropriately. |
Spokesperson | Talks to the instructor and other teams. |
Quality Control | Records all answers & questions, and provides team reflection to team and instructor. |
Process Analyst | Considers how the team could work and learn more effectively. |
Suppose we have a list of numbers -- e.g., 5, 10, -2, -3, 7, 8, 12 Here's an algorithm that uses sequence, selection, and iteration (repetition) to add all the even numbers in the list and print out their sum. Notice how indentation and curly brackets are used to clarify the different parts of the algorithm.
1 total ← 0 (Set total to 0) 2 FOR EACH number IN list 3 < 4 IF (EVEN(number)) 5 < 6 total ← total + number (Set total to the current total + number) 7 >8 > 9 DISPLAY(total)
This algorithm contains examples of all three types of control structures, sequence, selection, and repetition. The lines are numbered for convenience.
In this lesson, you learned how to trace through code.
Q-1: What does the following code do?
i ← 1 REPEAT UNTIL i >= 100 DISPLAY i i ← i + 2