Saturday 28 March 2015


PROGRAM 14 : TO CHECK WHETHER THE NUMBER ENTERED IS PART OF THE FIBONACCI SERIES.

(Fibonacci series starts with '0' and '1' and the next term is the sum of the previous two terms of series. It goes like this : 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21...................)

Example:


PROGRAM :

import java.util.Scanner;
public class isFibonacci
{
   public static void main(String args[])
   {
       Scanner sc = new Scanner(System.in);
       System.out.println("Enter a number:");
       int n = sc.nextInt();
       if(n<0) // THE NUMBER ENTERED SHOULD BE EQUAL TO OR GREATER THAN ZERO
       {
           System.out.println("negative number entered.");
        }
        else
        {
            int a = 0 , b = 1 , c = 0;
            while(c<n){ // THE SERIES GOES ON TILL IT REACHES THE SEARCH ELEMENT OR EXCEEDS IT.
                c = a + b; // THIRD TERM IS EQUAL TO SUM OF PRECEEDING TWO VALUES
                a = b; // SWAPPING POSITIONS OF VALUE
                b = c;
            }
       if(c==n)
           System.out.println("Output : The number belongs to Fibonacci Series.");
       else
           System.out.println("Output : The number does not belong to Fibonacci Series.");
     }
   }
}

No comments:

Post a Comment