Friday, October 7, 2016

Find the nth Fibonacci number in C/C++ Language

There are multiple ways to achieve that. Following are the 3 methods to find nth Fibonacci number.
Algorithm: We know that
Fib (n) = fib (n-1) + fib (n-2)
Our program will stop if one of the following conditions are met:
n = 2 || n = 1

Method – 1: iteratively using for loop

Code

#include<iostream>
#include<conio.h>
using namespace std;

int fib(int n);

int main()
{

      int n, answer;
      cout << "Enter number to find: ";
      cin >> n;

      cout << "\n\n";

      answer = fib(n);

      cout << answer << " is the " << n << "th Fibonacci number\n";
      getch();
      return 0;
}

int fib(int n)
{
  int u = 0;
  int v = 1;
  int i, t;

  for(i = 2; i <= n; i++)
  {
    t = u + v;
    u = v;
    v = t;
  }
  return v;
}

Output


Method – 2: Using recursion

Code

#include<iostream>
#include<conio.h>
using namespace std;

int fib(int n);

int main()
{

      int n, answer;
      cout << "Enter number to find: ";
      cin >> n;

      cout << "\n\n";

      answer = fib(n);

      cout << answer << " is the " << n << "th Fibonacci number\n";
      getch();
      return 0;
}

int fib (int n)
{
      cout << "Processing fib(" << n << ")... ";

      if (n < 3 )
      {
         cout << "Return 1!\n";
         return (1);
      }
     
      else
      {
        cout << "Call fib(" << n-2 << ") and fib(" << n-1 << ").\n";
        return( fib(n-2) + fib(n-1));
      }
}

Output


Method – 3: Using recursion

Code

#include<iostream>
#include<conio.h>
using namespace std;

int fib(int n);

int main()
{

      int n, answer;
      cout << "Enter number to find: ";
      cin >> n;

      cout << "\n\n";

      answer = fib(n);

      cout << answer << " is the " << n << "th Fibonacci number\n";
      getch();
      return 0;
}
int fib(int n)
{
  if (n < 2)
    return n;
  else
    return fib(n-1) + fib(n-2);
}

Output


1 comment :

  1. Nice post!!thanks for sharing good post. java vogue have good collection for improve program skill visit Programming Questions And Answers

    ReplyDelete

Note: Only a member of this blog may post a comment.

Copyright 2017. All Rights Reserved. Privacy Policy / Terms And Conditions / Sitemap / Contact