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 an infinite loop using do while condition.


View

Find the maximum & minimum number in an array of integers.

[HINT : Read about Integer.MIN_VALUE & Integer.MAX_VALUE in Java]


View

Print the spiral order matrix as output for a given matrix of numbers.


View

For a given matrix of N x M, print its transpose in java.


View

Input a string from the user. Create a new string called ‘result’ in which you will replace the letter ‘e’ in the original string with letter ‘i’. 

Example : 

original = “eabcdef’ ; result = “iabcdif”

Original = “xyz” ; result = “xyz”


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

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


View