DevNet Associate (DEVASC) v1.0Software Development and DesignMedium
A developer needs to implement a function in Python that calculates the factorial of a given non-negative integer. The function should call itself repeatedly with a smaller input until a base case is reached. Which programming concept is being described here?
- ARecursion
- BIteration
- CPolymorphism
- DEncapsulation
Show answer & explanationAnswer & explanation
Correct answer: A. Recursion
Recursion is a programming technique where a function calls itself in order to solve a problem. It typically involves a base case to stop the recursive calls and a recursive step that reduces the problem to a simpler version of itself.
Why the other options are wrong
- B. Iteration involves repeating a block of code using loops (e.g., `for` or `while`), not by a function calling itself.
- C. Polymorphism is an object-oriented concept allowing objects of different classes to be treated as objects of a common type.
- D. Encapsulation is an object-oriented concept of bundling data and methods that operate on the data within a single unit (e.g., a class).
Recursion
Recursion is a programming technique where a function calls itself to solve a problem. It typically involves a 'base case' to stop the recursion and a 'recursive step' that calls the function with a modified input to move closer to the base case.
- Essential for solving problems that can be broken down into smaller, self-similar subproblems.
- Requires a clear base case to prevent infinite loops (stack overflow).
- Can sometimes be less efficient than iterative solutions due to function call overhead.
- Often used in algorithms like tree traversals, mergesort, and quicksort.
Memory trick: Recursion: Repeat, recurse, reach the base.