Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

How to print even Fibonacci numbers

Educative Answers Team

The Fibonacci sequence can be implemented using recursion. An illustration of a recursion tree is shown below:

%0 node_1 fib(5) node_2 fib(4) node_1->node_2 node_3 fib(3) node_1->node_3 node_1577726604844 fib(3) node_2->node_1577726604844 node_1577726620200 fib(2) node_2->node_1577726620200 node_1577726702498 fib(2) node_1577726604844->node_1577726702498 node_1577726732636 fib(1) node_1577726604844->node_1577726732636 node_1577726761027 fib(1) node_1577726702498->node_1577726761027 node_1577726713501 fib(0) node_1577726702498->node_1577726713501 node_1577726692584 fib(1) node_1577726620200->node_1577726692584 node_1577726683361 fib(0) node_1577726620200->node_1577726683361 node_1577726698379 fib(2) node_3->node_1577726698379 node_1577726705115 fib(1) node_3->node_1577726705115 node_1577726765267 fib(1) node_1577726698379->node_1577726765267 node_1577726739678 fib(0) node_1577726698379->node_1577726739678
Recursion tree for the 5th term of Fibonacci sequence

An additional check for an even number can be combined with the same algorithm to print only even Fibonacci numbers.

Implementation

#include <iostream>
using namespace std;

// Recursive algorithm:
int evenFibonacci(int n){
  if(n == 0 || n == 1)
    return n;

  return evenFibonacci(n - 1) + evenFibonacci(n - 2);
}

int main() {
  // The number of even Fibonacci numbers to print:
  int n = 5;

  int x;
  for(int i = 0; n > 0; i++){
    x = evenFibonacci(i);
    
    // Check if the number returned is even:
    if(x % 2 == 0){
      cout << x << " ";
      n--;
    }
  }
  
  return 0;
}

RELATED TAGS

Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring