Function (Programming) CS Thinking Example 1
Follow the full solution, then compare it with the other examples linked below.
Example 1
mediumDefine a function `double(n)` that returns n ร 2. Then trace `double(double(3))`.
Solution
- 1 Step 1: FUNCTION double(n): RETURN n * 2.
- 2 Step 2: Inner call: double(3) = 3 * 2 = 6.
- 3 Step 3: Outer call: double(6) = 6 * 2 = 12.
Answer
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.
About Function (Programming)
A named, reusable block of code that performs a specific task, taking input (parameters) and optionally returning output (a return value). Functions allow you to write a piece of logic once and use it many times throughout a program.
Learn more about Function (Programming) โMore Function (Programming) Examples
Example 2 medium
Why is it better to write a function `calculateTax(amount, rate)` than to repeat the tax calculation
Example 3 mediumWrite a function `isEven(n)` that returns TRUE if n is even, FALSE otherwise. Trace it for n = 7.
Example 4 mediumGiven `FUNCTION toSeconds(minutes): RETURN minutes * 60`, what does `toSeconds(3)` return, and why i