Write a Java program to print Nth Fibonacci series.

 Problem: - Write a Java program to print the Nth Fibonacci series.

Solution: - The Fibonacci series is the sequence where each number is the sum of the previous two numbers. The 1st two numbers of the Fibonacci series are 0 and 1 to generate the Fibonacci series.
For example:- 0 1 1 2 3 5 8 13 ......
Java code: -

package com.codeforsolution.java.logical;
import java.util.Scanner; public class FibonacciSeriesExample { public static void main(String[] args) { int num1 = 0; int num2 = 1; System.out.println("Enter number to print the fibonacci series till Nth term "); Scanner input = new Scanner(System.in); int count = input.nextInt(); input.close(); printFibnocci(num1, num2, count); } private static void printFibnocci(int num1, int num2, int count) { System.out.print(num1 +" " + num2); int num3 = 0; for(int i = 2; i < count; i++) { num3 = num1 + num2; System.out.print(" "+num3); num1 = num2; num2 = num3; } } }

Output: -  

Enter a number to print the Fibonacci series till the Nth term

10

0 1 1 2 3 5 8 13 21 34

Post a Comment (0)
Previous Post Next Post