Print Fibonacci Series Based On User Input | Java Programs

Output:

*** Fibonacci Series ***

How many numbers you want in the sequence: 7
Fibonacci Series of 7 numbers: 0 1 1 2 3 5 8

Click Here For Java Online Compiler

Solution:

import java.util.Scanner;

class FibonacciSeriesUpto {

    public static void main(String[] args) {

        int howMany = 0;
        int num1 = 0;
        int num2 = 1;
        System.out.println("*** Fibonacci Series ***" + "\n");
        System.out.print("How many numbers you want in the sequence: ");
        Scanner sc = new Scanner(System.in);
        howMany = sc.nextInt();
        System.out.print("Fibonacci Series of " + howMany + " numbers: ");

        int i = 1;
        while (i <= howMany) {
            System.out.print(num1 + " ");
            int sumOfPrevTwo = num1 + num2;
            num1 = num2;
            num2 = sumOfPrevTwo;
            i++;
        }
    }
}
Share This :

Related Post



sentiment_satisfied Emoticon