Loop tracing

What are the values of a and b after the for loop finishes?

int a = 10, b = 3, t;
for (int i=1; i<=6; i++)
{
   t = a;
   a = i + b;
   b = t - i;
}

Set up a table

Make a table with a column for each variable and a row for each iteration of the loop.

List the variables in the order they are updated.

Fill in the column for the loop variable (i in this case)

t = a; a = i + b; b = t - i;

i t a=10 b=3
1 10 4 9
2 4 11 2
3 11 5 8
4 5 12 1
5 12 6 7
6 6 13 0

An alternative to tracing

Don’t, however, leap to tracing too quickly.

If the question is about whether a loop works to achive some end

Analyze abstractly

  • How many times does the loop run?

  • What happen on the first iteration?

  • What happens on the last iteration?