Return Values CS Thinking Example 1
Follow the full solution, then compare it with the other examples linked below.
Example 1
mediumFUNCTION square(n): RETURN n * n. What is the output of: SET result = square(4) + square(3). OUTPUT result.
Solution
- 1 Step 1: square(4) returns 4 * 4 = 16.
- 2 Step 2: square(3) returns 3 * 3 = 9.
- 3 Step 3: result = 16 + 9 = 25. Output: 25.
Answer
Return values allow functions to send data back to the caller. The returned value can be used in expressions, assigned to variables, or passed to other functions.
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 2 medium
What 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))?
Example 4 mediumWhat is the output of this program? FUNCTION double(n) RETURN n * 2 END FUNCTION FUNCTION addThr