Checking the Number is Present in Fibonacci Series

 

äWAP to accept a Number and check whether the number is present in Fibonacci Series or Not.

The Fibonacci series is a series where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence is 0 followed by 1.

import java.util.*;
class Fibonacci_Series_check
{
    public static void main(String[] args)
    {
            int a=0, b=1, c=0,n,f=0;      //here f is a Flag Variable
            Scanner sc=new Scanner(System.in);
            System.out.print("Enter a number : ");
            n=sc.nextInt();      //Accepting Number from the user           
            System.out.println(a);       // Display initial value '0'
            System.out.println(b);       //Display initial value '1'
            if(n==0)    //checking the accepted value is 0 then flag variable will be 1
               f=1;
            while(c<n)  //Loop will be excuted till the value of c less then accepted value which is n
            {
                c=a+b;  //adding the value of a & b into c
                System.out.println(c);   // display the value stored in c
                if(c==n)   //Now checking the equality with accepted value and c
                    f=1;    // if condition is true then flag variable will be 1
                //swaping the value
                a=b;
                b=c;
            }
            if(f==1) //Checking the value of f is 1 or 0
                System.out.println("The Number is present in Fibonacci Series"); //display if condition is true
            else
                System.out.println("The Number is not-present in Fibonacci Series"); //display if condition is false
    }
}

No comments

Powered by Blogger.