CompTIA Tech+ (FC0-U71)Software Development ConceptsMedium
A developer needs to create a function that calculates the factorial of a given positive integer. The factorial of a non-negative integer 'n' is the product of all positive integers less than or equal to 'n'. For example, factorial(5) = 5 * 4 * 3 * 2 * 1 = 120. The function should call itself with a smaller input until it reaches a base case (n=0 or n=1). Which programming concept is being described?
- AIteration
- BEncapsulation
- CPolymorphism
- DRecursion
Show answer & explanationAnswer & explanation
Correct answer: D. Recursion
Recursion is a programming technique where a function calls itself directly or indirectly to solve a problem. It relies on having a base case to stop the calls and avoid an infinite loop.
Why the other options are wrong
- A. Iteration uses loops (for, while) to repeat code, not self-calling functions.
- B. Encapsulation is an OOP concept of bundling data and methods that operate on the data within a single unit.
- C. Polymorphism is an OOP concept allowing objects of different classes to be treated as objects of a common type.
Recursion
A programming technique where a function calls itself repeatedly until a specific base condition is met. It's often used to solve problems that can be broken down into smaller, self-similar subproblems.
- Requires a 'base case' to terminate the recursive calls and prevent infinite loops.
- Each recursive call solves a smaller part of the overall problem.
- Uses the call stack to manage function calls.
- Can sometimes lead to stack overflow errors if the recursion depth is too large.
Memory trick: Recursion is like a mirror reflecting itself, getting smaller each time.