WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Software Engineering · Basic · question 3 of 100

Can you explain the concept of recursion and provide a simple example?

📕 Buy this interview preparation book: 100 Software Engineering questions & answers — PDF + EPUB for $5

Recursion is a programming technique where a function calls itself to solve a problem. It is a powerful and elegant way to solve complex problems by breaking them down into smaller sub-problems that are easier to solve. Recursion is widely used in computer programming and is particularly useful for solving problems with a defined structure, such as searching trees or sorting arrays.

A simple example of recursion is calculating the factorial of a number. The factorial of a number is the product of all positive integers up to and including that number. For example, the factorial of 4 is 4 x 3 x 2 x 1 = 24.

The factorial function can be defined recursively as follows:

n! =
1, if  n = 0 
n times (n-1)!, if  n > 0 

In other words, the factorial of 0 is 1, and the factorial of any positive integer n is n multiplied by the factorial of n-1.

Here is an implementation of the factorial function in Python:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

When the factorial function is called with a positive integer n, it recursively calls itself with n-1 until it reaches the base case of n=0, at which point it returns 1. The products of each recursive call are multiplied together to give the final result.

Recursion is a powerful and flexible technique that can be used to solve a wide variety of problems in computer programming. However, it is important to be cautious when using recursion, as it can easily lead to infinite loops or stack overflow errors if not implemented correctly.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Software Engineering interview — then scores it.
📞 Practice Software Engineering — free 15 min
📕 Buy this interview preparation book: 100 Software Engineering questions & answers — PDF + EPUB for $5

All 100 Software Engineering questions · All topics