Return Values CS Thinking Example 2
Follow the full solution, then compare it with the other examples linked below.
Example 2
mediumWhat is the difference between a function that returns a value and one that just prints? Compare: FUNCTION add(a,b): RETURN a+b vs FUNCTION printSum(a,b): OUTPUT a+b.
Solution
- 1 Step 1: `add(3,4)` returns 7 โ the caller can use the result: SET x = add(3,4).
- 2 Step 2: `printSum(3,4)` displays 7 but returns nothing โ SET x = printSum(3,4) would give x = None/undefined.
- 3 Step 3: Functions with return values are more versatile because their output can be used in further calculations.
Answer
RETURN sends a value back to the caller for further use; OUTPUT only displays it. RETURN is more flexible.
Understanding the distinction between returning and printing is crucial. Functions that return values can be composed and reused; functions that only print are less flexible.
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 3 mediumFUNCTION max(a, b): IF a > b THEN RETURN a ELSE RETURN b. What is max(max(3, 7), max(5, 2))?
Example 4 mediumWhat is the output of this program? FUNCTION double(n) RETURN n * 2 END FUNCTION FUNCTION addThr