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

2 Comments

  1. Brice Tsinnie Brice Tsinnie 9th April 2020

    Thanks to my father who shared with me concerning this blog, this blog is genuinely awesome.

  2. Claudette Ware Claudette Ware 18th June 2020

    Your style is very unique compared to other people I’ve read stuff from. Thanks for posting when you’ve got the opportunity, Guess I’ll just bookmark this blog.

Leave a Reply

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