|
Does the definition of sum from a preceding page work correctly? Let's do a hand simulation of sum(3). Here is the definition of sum for reference.
int sum(int n) { int s = 0; // the running sum int i = 0; // how far we have gone? while(i < n) { i = i + 1; s = s + i; } return s; }
Variables i and s change each time the loop body is performed, which makes crossing out and replacing values messy. Let's instead show the values of i and s in columns, with the most recent value at the bottom of the column. First, do the initializations.
i s n 0 0 3Since the test i < n is true, we need to perform the loop body. First it adds 1 to i, giving
i s n 0 0 3 1Next, it adds i to s. Notice that i is now 1.
i s n 0 0 3 1 1Again, i < n, so the loop body is done again. After doing the entire loop body, we have the following.
i s n 0 0 3 1 1 2 3Since i is still less than n, we do the loop body again.
i s n 0 0 3 1 1 2 3 3 6Now i is not less than n. The loop is finished. Continuing with the next statement, the function returns 6, which is correct since 1 + 2 + 3 = 6.
Do a hand simulation of the following loop. Show the values of n and r each time the loop reaches its top, including the first and last times.
int r = 1; int n = 1; while(n < 5) { n = n + 1; r = n * r; }Answer
Do a hand simulation of the following loop. Show the values of n and r each time the loop reaches its top, including the first and last times.
int r = 2; int n = 1; while(n < 10) { if(n % 2 == 0) { n = n + 1; r = r * r; } }Answer
|