Return Values CS Thinking Example 4
Follow the full solution, then compare it with the other examples linked below.
Example 4
mediumWhat is the output of this program?
FUNCTION double(n)
RETURN n * 2
END FUNCTION
FUNCTION addThree(n)
RETURN n + 3
END FUNCTION
SET result = addThree(double(4))
OUTPUT result
Solution
- 1 Step 1: Evaluate the inner call first: double(4) โ RETURN 4 * 2 = 8.
- 2 Step 2: The return value 8 is passed to addThree: addThree(8) โ RETURN 8 + 3 = 11.
- 3 Step 3: result = 11. OUTPUT 11.
Answer
11. Nested function calls evaluate from the inside out โ the inner function's return value becomes the argument to the outer function.
Composing functions by using one function's return value as another's argument is a fundamental pattern. The key is evaluating the innermost call first and working outward.
About Return Values
The value that a function sends back to the code that called it, specified by the return statement. When a function executes a return statement, it immediately stops running and passes the specified value back to the caller, where it can be stored, used in expressions, or passed to other functions.
Learn more about Return Values โMore Return Values Examples
Example 1 medium
FUNCTION square(n): RETURN n * n. What is the output of: SET result = square(4) + square(3). OUTPUT
Example 2 mediumWhat is the difference between a function that returns a value and one that just prints? Compare: FU
Example 3 mediumFUNCTION max(a, b): IF a > b THEN RETURN a ELSE RETURN b. What is max(max(3, 7), max(5, 2))?