Java Program To Calculate fibonacci series




Fibonacci series is the sequence of integer numbers in which every integer is the after the first two integers is the sum of two preceding integer numbers. The first two starting numbers could be 0 and 1 or 1 and 1 depending on the choice of user.

Below is the Java Program to calculate fibonacci series upto given number by user.


import java.util.Scanner;

public class Fibonacci {

            public static void main(String[] args) {

            int n1,n2,n3,lastnum;

            System.out.println("Enter the number upto which you want to calculate");

            Scanner sc=new Scanner(System.in);

             lastnum=sc.nextInt();

             n1=0;

             n2=1;

             n3=0;

             System.out.println(n1);

             System.out.println(n2);

             for(int i=0;i<lastnum;i++)
             {

                    n3=n1+n2;

                   System.out.println(n3);

                   n1=n2;

                   n2=n3;

              }

      }

}

Output
Enter the number upto which you want to calculate.

8
0
1
1
2
3
5
8
13
21
34



Explaination

  • import java.util.Scanner;-This Statement tells the compiler to import Scanner class to program which is contained in utils package. The Scanner class has a methods defined to accept input entered by user.

  • public class Fibonacci - is the name of the class.

  • public static void main(String[] args)- is the main() method which is the starting point of any Java Program.

  • Next we declared four integer variables named n1,n2,n3,lastnum, and opted user to enter the number upto which the user want to calculate fibonacci series. We used object of Scanner class to accept that number and stored in variable 'lastnum'.

  • Next we initialized n1 to 0, n2 to 1 and n3 to 0 respectively and printed those numbers on the console .

  • Next , using the for loop ,we initialized counter 'i' to 0 and the specified the condition that the for loop will continue to execute until the 'i' is less than the number entered by user stored in variable 'lastnum'.

  • In the loop, we added values in variable n1 and 'n2' and stored them in 'n3'. And then, we assigned value in 'n2 'to 'n1' and 'n3' to 'n2' respectively. The for loop continues to execute until the given condition becomes false. And the fibonacci series is printed on the Console/screen.
Java Program To Calculate fibonacci series Java Program To Calculate fibonacci series Reviewed by LanguageExpert on August 21, 2017 Rating: 5

No comments