126k views
2 votes
g write a recursive function that prints out all the even numbers between x and y inclusive if x is odd then the print out will start at x 1

User AbhiNickz
by
5.7k points

1 Answer

1 vote

Answer:

The function written in python is as follows:

def EvenNumbers(x, y):

if (y < x):

return

if (y % 2 == 0):

EvenNumbers(x, y - 2)

else:

EvenNumbers(x, y - 1)

if (y % 2 == 0):

print(y)

Step-by-step explanation:

x represents the lower limit while y represents the upper limit.

So, the recursion will be repeated as long as x <= y

This defines the function

def EvenNumbers(x, y):

This checks if y < x. If yes, the recursion stops execution and return to the main

if (y < x):

return

The following if and else condition checks determines the appropriate range of the recursion.

if (y % 2 == 0):

EvenNumbers(x, y - 2)

else:

EvenNumbers(x, y - 1)

The above takes care of printing starting at x + 1 if x is odd

This checks and prints the even numbers in the range

if (y % 2 == 0):

print(y)

To call the function from main, make use of

EvenNumbers(x, y)

Where x and y are integers

e.g EvenNumbers(2,10), EvenNumbers(1,17), EvenNumbers(3,21)

See attachment

g write a recursive function that prints out all the even numbers between x and y-example-1
User VictorBian
by
6.6k points