Function (Programming) Examples in CS Thinking

Start with the recap, study the fully worked examples, then use the practice problems to check your understanding of Function (Programming).

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

A named, reusable block of code that performs a specific task, taking input and optionally returning output.

A mini-program with a name. Call it by name whenever you need that task done.

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: Write once, use many times. Functions take input (parameters) and give output (return value).

Common stuck point: Defining a function doesn't run itβ€”you must call the function.

Worked Examples

Example 1

medium
Define a function `double(n)` that returns n Γ— 2. Then trace `double(double(3))`.

Solution

  1. 1
    Step 1: FUNCTION double(n): RETURN n * 2.
  2. 2
    Step 2: Inner call: double(3) = 3 * 2 = 6.
  3. 3
    Step 3: Outer call: double(6) = 6 * 2 = 12.

Answer

12
Functions are reusable blocks of code that take inputs (parameters) and return outputs. They can be composed β€” the output of one function becomes the input of another.

Example 2

medium
Why is it better to write a function `calculateTax(amount, rate)` than to repeat the tax calculation code everywhere?

Practice Problems

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

Example 1

medium
Write a function `isEven(n)` that returns TRUE if n is even, FALSE otherwise. Trace it for n = 7.

Example 2

medium
Given `FUNCTION toSeconds(minutes): RETURN minutes * 60`, what does `toSeconds(3)` return, and why is using a function better than rewriting `minutes * 60` everywhere?

Background Knowledge

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

algorithmabstraction