Friday 1 January 2021

Python Program to Determine Whether a Given Number is Even or Odd Recursively

 This is a Python Program to determine whether a given number is even or odd recursively.

Problem Description

The program takes a number and determines whether a given number is even or odd recursively.

Problem Solution

1. Take a number from the user and store it in a variable.
2. Pass the number as an argument to a recursive function.
3. Define the base condition as the number to be lesser than 2.
4. Otherwise call the function recursively with the number minus 2.
5. Then return the result and check if the number is even or odd.
6. Print the final result.
7. Exit.

Program/Source Code

Here is source code of the Python Program to determine whether a given number is even or odd recursively. The program output is also shown below.

def check(n):
    if (n < 2):
        return (n % 2 == 0)
    return (check(n - 2))
n=int(input("Enter number:"))
if(check(n)==True):
      print("Number is even!")
else:
      print("Number is odd!")
Program Explanation

1. User must enter a number and store it in a variable.
2. The number is passed as an argument to a recursive function.
3. The base condition is that the number has to be lesser than 2.
4. Otherwise the function is called recursively with the number minus 2.
5. The result is returned and an if statement is used to check if the number is odd or even.
6. The final result is printed.

Runtime Test Cases
 
Case 1:
Enter number:124
Number is even!
 
Case 2:
Enter number:567
Number is odd!

No comments:

Post a Comment