Function (Programming) CS Thinking Example 2
Follow the full solution, then compare it with the other examples linked below.
Example 2
mediumWhy is it better to write a function `calculateTax(amount, rate)` than to repeat the tax calculation code everywhere?
Solution
- 1 Step 1: Reusability โ the function can be called from multiple places with different arguments.
- 2 Step 2: Maintainability โ if the tax formula changes, we update only one function instead of every occurrence.
- 3 Step 3: Readability โ `calculateTax(100, 0.2)` is clearer than `100 * 0.2` scattered throughout the code.
Answer
Functions improve reusability, maintainability, and readability.
Functions encapsulate logic, reduce code duplication, and make programs easier to understand and maintain. This is a core principle of good software design.
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 1 medium
Define a function `double(n)` that returns n ร 2. Then trace `double(double(3))`.
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