CONCEPTS USED:

Recursion

DIFFICULTY LEVEL:

Easy

PROBLEM STATEMENT(SIMPLIFIED):

Given a number N, your task is to print all even numbers (>0) from 1 to N using recursion.

See original problem statement here

For Example:

Input :  N = 7

Output : 2 4 6

SOLVING APPROACH:

  1. Check if the value of N is even, recursively go on checking for other values of N-2 and print this value by referring some online coding classes.

  2. If the value of N is odd, recursively go on checking for (N-1) as (N-1) would be even.

  3. If at any point, N becomes (<=0), simply return.

ALGORITHM:

if (n <= 0)
    exit

if (n is even) 
    check for (n-2) and print n

if (n is odd) 
    check for (n-1)

STATE SPACE TREE:

SOLUTIONS:

[TABS_R id=979]
[forminator_quiz id=”1007″]

Previous post Matrix and combination
Next post Shubhaluxumy loves Binary Number

Leave a Reply

Your email address will not be published. Required fields are marked *