AP CSP Day 38: Loop Algorithms
Share
Practice Question
What is displayed after the following code runs?
PROCEDURE calculate(x, y)
{
result ← x * y + x
RETURN result
}
a ← 3
b ← calculate(a, a + 1)
DISPLAY(b)The argument a + 1 is evaluated before the call: a + 1 = 3 + 1 = 4. So calculate(3, 4) executes. Inside: result = 3 * 4 + 3 = 12 + 3 = 15. The returned value 15 is stored in b and displayed.
A) 12 results from computing x * y (3*4) but forgetting to add x. C) 9 results from x * x = 3*3, ignoring the second parameter. B) 16 results from (x+1) * y = 4*4, substituting incorrectly.
Students either forget to evaluate the argument expression (a+1) before passing it, or they compute x*y and stop without adding the final x term.
Always evaluate argument expressions completely before substituting into the procedure. Then trace the procedure body with the substituted values, following order of operations.
Keep Practicing!
Consistent daily practice is the key to AP CSP success.
AP CSP Resources Get 1-on-1 Help