Press "Enter" to skip to content

Fibonacci Numbers up to a Limit : Java

Java program for fibonacci numbers



Do you know, what is Fibonacci numbers..? 
These are numbers like 0, 1,1,2,3,5,8,13,21. . . . . . . . . .
How do you get these numbers . .?

First take numbers 0 and 1 as static. (Now numbers are 0, 1)

Last element is 1; its left element is 0, so add them, 0 + 1 = 1 (Now numbers is 0, 1, and 1)

Last element is 1, its left element is 1, so add them, 1 + 1 = 2 (Now numbers are: 0, 1, 1, and 2)

Last element is 2, its left element is 1, so add them, 2 + 1 = 3 (Now numbers are: 0, 1, 1, 2, and 3)

Last element is 3, its left element is 2, so add them, 3 + 2 = 5 (Now numbers are: 0, 1, 1, 2, 3, and 5)

Last element is 5, its left element is 3, so add them, 5 + 3 = 8 (Now numbers are: 0, 1, 1, 2, 3, 5, and 8)

– – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – – –

Now let’s write a java program to print Fibonacci numbers up to a limit:

(Learn how to Compile and Run a Java file)

import java.io.*;
class fibonacci
{
   long f1=0;
   long f2=1;
   long f3=0;
   int n;
void get() throws IOException
  {
     BufferedReader Br = new BufferedReader(new InputStreamReader(System.in));
     System.out.print("Enter a limit : ");
     n=Integer.parseInt(Br.readLine());
 }
void display()
  {    
      for(int i=0;i<n;i++)
       {  
         if(f3 <= n)
 
  {
         System.out.println(f3);
         f1=f2;
         f2=f3;
         f3=f1+f2;
 
  }
       }
  }
 
public static void main(String p[]) throws IOException
{
 fibonacci f = new fibonacci();
 f.get();
 f.display();
}
} 

Output

Java program for fibonacci numbers

Java program to print “N” Fibonacci  numbers:

import java.io.*;
class fibonacci
{
   long f1=0;
   long f2=1;
   long f3=0;
   int n;
void get() throws IOException
  {
     BufferedReader Br = new BufferedReader(new InputStreamReader(System.in));
     System.out.print("How many numbers : ");
     n=Integer.parseInt(Br.readLine());
 }
void display()
  {    
      for(int i=0;i<n;i++)
       {  
           System.out.println(f3);
           f1=f2;
           f2=f3;
           f3=f1+f2;
 }
  }
 
public static void main(String p[]) throws IOException
   {
      fibonacci f = new fibonacci();
      f.get();
      f.display();
   }
}

Output

Java program for fibonacci numbers

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *