Write a program to print Fibonacci series of n terms where n is input by user :

0 1 1 2 3 5 8 13 21 ..... 

In the Fibonacci series, a number is the sum of the previous 2 numbers that came before it.


import java.util.*;

public class Solutions {

   public static void main(String args[]) {

       Scanner sc = new Scanner(System.in);

       int n = sc.nextInt();

      

       int a = 0, b = 1;

          

       System.out.print(a+" ");

      

       if(n > 1) {

           //find nth term

           for(int i=2; i<=n; i++) {

               System.out.print(b+" ");

               //the concept below is called swapping

               int temp = b;

               b = a + b;

               a = temp;

           }

 

           System.out.println();

       }

   }   

}



Share to whatsapp

More Questions from Java Basic Codes Module 0

Write a function that calculates the Greatest Common Divisor of 2 numbers.


View

Write a function to calculate the factorial of a number.


View

Write a program to enter the numbers till the user wants and at the end it should display the count of positive, negative and zeros entered. 


View

Write a function that takes in the radius as input and returns the circumference of a circle.


View

Write a function which takes in 2 numbers and returns the greater of those two.


View

Write a function that takes in age as input and returns if that person is eligible to vote or not. A person of age > 18 is eligible to vote.


View

Two numbers are entered by the user, x and n. Write a function to find the value of one number raised to the power of another i.e. x^n.


View