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:


#include <stdio.h>

void printEven(int n){
  if(n <= 0)                //if n becomes less than equal to 0
    return ;
  if( n%2 == 0){
    printEven(n-2);         //if n is even go for smaller values of n and finally print all
    printf("%d ",n);
  }
  else
    printEven(n-1);          //if n is odd recurse for n-1 values as it will be even
}

int main()
{
  int t;
  scanf("%d",&t);
  while(t--){
    int n;
    scanf("%d",&n);
    printEven(n);
    printf("\n");
  }
  return 0;
}

#include <bits/stdc++.h>
using namespace std;

void printEven(int n){
  if(n <= 0)            //if n becomes less than equal to 0
    return ;
  if( n%2 == 0){
    printEven(n-2);      //if n is even go for smaller values of n and finally print all
    cout<<n<<" ";
  }
  else
    printEven(n-1);       //if n is odd recurse for n-1 values as it will be even
}

int main()
{
  int t;cin>>t;
  while(t--){
    int n;cin>>n;
    printEven(n);
    cout<<"\n";
  }

  return 0;
}

import java.util.*;
import java.io.*;

public class Main {
  static void printEven(int n){
    if(n <= 0)            //if n becomes less than equal to 0
      return ;
    if( n%2 == 0){
      printEven(n-2);      //if n is even go for smaller values of n and finally print all
      System.out.print(n + " ");
    }
    else
      printEven(n-1);       //if n is odd recurse for n-1 values as it will be even
  }

  public static void main(String args[]) throws IOException {
    Scanner sc = new Scanner(System.in);
    int t = sc.nextInt();
    while(t != 0){
      int n = sc.nextInt();
      printEven(n);
      System.out.println();
      t--;
    }
  }
}

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 *