Python Program to Check Even or Odd using Recursion

1. Introduction

Determining whether a number is even or odd is a common task in programming. Typically, this can be done using the modulus operator. However, in this blog post, we're going to take a more conceptual approach by using recursion. Recursion is a method of solving problems where a function calls itself as a subroutine. This approach can make some algorithms easier to implement and understand.

2. Program Steps

1. Define a function that takes a single integer as an argument.

2. Check if the number is 0 (base case for even) or 1 (base case for odd).

3. If neither, recursively call the function with the number decremented by 1.

4. Return the result of evenness or oddness.

3. Code Program

def is_even_or_odd(num):
    # Base case for even
    if num == 0:
        return "Even"
    # Base case for odd
    elif num == 1:
        return "Odd"
    # Recursive step
    else:
        # Use the absolute value to handle negative numbers
        return is_even_or_odd(abs(num) - 1)

Output:

# For an even number
print(is_even_or_odd(10))  # Output: Even
# For an odd number
print(is_even_or_odd(11))  # Output: Odd

Explanation:

1. The function is_even_or_odd is defined to take one parameter, num.

2. It checks if num is 0, in which case it returns "Even", the base case for even numbers.

3. If num is 1, it returns "Odd", the base case for odd numbers.

4. If num is neither 0 nor 1, the function calls itself with abs(num) - 1, ensuring that the function can handle negative numbers and will eventually reach the base case.

5. This process repeats until the base case is met, and the function returns the appropriate string indicating whether the original number was even or odd.

Comments