Explain recursion in programming?

QuestionsQuestions4 SkillsProPermissions of FilesDec, 01 2025
0132

Recursion in programming is a technique where a function calls itself to solve a problem. It typically involves two main components:

  1. Base Case: This is the condition under which the recursion stops. It prevents infinite loops by providing a simple case that can be solved directly.

  2. Recursive Case: This is where the function calls itself with a modified argument, gradually working towards the base case.

Example: Factorial Calculation

Here's a simple example in Python to calculate the factorial of a number using recursion:

def factorial(n):
    if n == 0:  # Base case
        return 1
    else:  # Recursive case
        return n * factorial(n - 1)

# Example usage
print(factorial(5))  # Output: 120

In this example:

  • The base case is when n is 0, returning 1.
  • The recursive case multiplies n by the factorial of n - 1.

Recursion is useful for problems that can be broken down into smaller, similar problems, such as tree traversals, searching algorithms, and more.

0 Comments

no data
Be the first to share your comment!