CompTIA Tech+ (FC0-U71)Software Development ConceptsHard
A developer needs to create a function that calculates the factorial of a given number. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n (e.g., factorial(4) = 4 * 3 * 2 * 1). Which programming concept is particularly well-suited for solving problems like factorial calculation where a problem can be broken down into smaller, self-similar subproblems?
- APolymorphism
- BEncapsulation
- CRecursion
- DIteration
Show answer & explanationAnswer & explanation
Correct answer: C. Recursion
Recursion is a programming technique where a function calls itself to solve a problem. It's especially effective for problems that can be defined in terms of smaller, self-similar instances of the same problem, such as calculating factorials (n! = n * (n-1)!).
Why the other options are wrong
- A. Polymorphism relates to objects taking on many forms, not a technique for calculating factorials.
- B. Encapsulation is about bundling data and methods, not a problem-solving technique for recursive definitions.
- D. Iteration (loops) can solve factorial, but recursion is more closely aligned with the 'self-similar subproblems' concept.
Recursion
Recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem. A recursive function calls itself until it reaches a base case, which is a simple, non-recursive solution.
- Function calls itself
- Requires a base case to terminate
- Elegant for naturally recursive problems (e.g., factorials, tree traversals)
Memory trick: Self-similar problem? Recursion's the solution!