Java Program to Find Fibonacci Numbers within a Range

Do you know, what is Fibonacci numbers..?
These are numbers like 0, 1,1,2,3,5,8,13,21. . . n (Learn more about Fibonacci numbers here)

This is a java console program to display Fibonacci numbers in a range.

Here class name is ‘fibonacci’, so you must save your java file with name as ‘fibonacci.java’.


import java.io.*;
class fibonacci
{
   long f1=0;
   long f2=1;
   long f3=0;
   int lower, upper;

void get() throws IOException
  {
     BufferedReader Br = new BufferedReader(new InputStreamReader(System.in));
     System.out.print("\n Enter the lower limit : ");
     lower=Integer.parseInt(Br.readLine());
System.out.print(" Enter the upper limit : ");
     upper=Integer.parseInt(Br.readLine());
System.out.println("\n Fibonacci numbers between " + lower + " and " + upper + " are following: " );
  }
void display()
  {  
      for(int i=lower;i<upper;i++)
       {
         if(f3 <= upper)
           {  
             if(f3 >=lower)
      {
                System.out.print("\t" + f3 );
      }
            f1=f2;
            f2=f3;
            f3=f1+f2;
           }
       }
  }

public static void main(String p[]) throws IOException
 {
   fibonacci fib = new fibonacci();
   fib.get();
   fib.display();
 }
}

Sample output:

Enter the lower limit : 10

Enter the upper limit : 150

Fibonacci numbers between 10 and 150 are following:

  13       21      35        55       89      144

Java Program to Find Fibonacci Numbers within a Range
    
.




No comments:

Post a Comment