Return Values CS Thinking Example 2

Follow the full solution, then compare it with the other examples linked below.

Example 2

medium
What 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. 1
    Step 1: `add(3,4)` returns 7 โ€” the caller can use the result: SET x = add(3,4).
  2. 2
    Step 2: `printSum(3,4)` displays 7 but returns nothing โ€” SET x = printSum(3,4) would give x = None/undefined.
  3. 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