Return Values Examples in CS Thinking

Start with the recap, study the fully worked examples, then use the practice problems to check your understanding of Return Values.

This page combines explanation, solved examples, and follow-up practice so you can move from recognition to confident problem-solving in CS Thinking.

Concept Recap

The value that a function sends back to the code that called it, specified by the return statement.

A function is like a vending machine โ€” you put in inputs (arguments) and get back an output (return value). The return value is what comes out.

Read the full concept explanation โ†’

How to Use These Examples

  • Read the first worked example with the solution open so the structure is clear.
  • Try the practice problems before revealing each solution.
  • Use the related concepts and background knowledge badges if you feel stuck.

What to Focus On

Core idea: Return values let functions communicate results back to their callers. A function without a return value just performs an action.

Common stuck point: Print and return are different. Print displays a value; return sends it back to the calling code for further use.

Worked Examples

Example 1

medium
FUNCTION square(n): RETURN n * n. What is the output of: SET result = square(4) + square(3). OUTPUT result.

Solution

  1. 1
    Step 1: square(4) returns 4 * 4 = 16.
  2. 2
    Step 2: square(3) returns 3 * 3 = 9.
  3. 3
    Step 3: result = 16 + 9 = 25. Output: 25.

Answer

25
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.

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.

Practice Problems

Try these problems on your own first, then open the solution to compare your method.

Example 1

medium
FUNCTION max(a, b): IF a > b THEN RETURN a ELSE RETURN b. What is max(max(3, 7), max(5, 2))?

Example 2

medium
What 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

Background Knowledge

These ideas may be useful before you work through the harder examples.

function programming