Java Program to print first “n” Numbers in Fibonacci Series

Java Program to print first “n” Numbers in Fibonacci Series

Write a Java Program to display first “n” numbers in the Fibonacci series.

Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13 and so on

If the value of n is 5, then the expected output is 0, 1, 1, 2, 3

Logic is: f1 = 0, f2 = 1, f3 = f1 + f2

Video Tutorial:

Steps (Program logic):

1. Declare variables like n, f1, f2, f3.

2. Create an object of Scanner class to read the input from standard keyboard.

3. Check the value of n , if the value of n is 1 display f1 that is 0.

4. If the value of n is 2, display f1 and f2 that is 0 and 1.

5. If the value of n is greater than 2 then display f1, f2 and calculate the next number in the series using formula f3=f1+f2.

6. if the value of n is less than or equal 0 then display that the error message like invalid input.

Source code of Java Program to print first “n” Numbers in Fibonacci Series

import java.util.Scanner;
 /*
 Write a Java Program to display first "n" numbers in Fibonacci series
 Subscribe to Mahesh Huddar YouTube Channel for more Videos
 Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13 and so on
 Logic: f1 = 0, f2 = 1, f3 = f1 + f2 
 */
 public class Fibonacci 
 {
     public static void main(String args[])
     {
         int n, f1 = 0, f2 = 1, f3;
         Scanner input = new Scanner(System.in);
         System.out.print("Enter the value of n:");
         n = input.nextInt();
         System.out.print("Fibonacci series is: ");
         if (n == 1)
         {
             System.out.print(f1);
         }
         else if (n == 2)
         {
             System.out.print(f1 +" "+ f2);
         }
         else if (n > 2)
         {
             System.out.print(f1 +" "+ f2+" ");
             for (int i = 3; i<=n; i++) 
             {
                 f3 = f1 + f2;
                 System.out.print(f3+" ");
                 f1 = f2;
                 f2 = f3;
             }
         }
         else
         {
             System.out.print("Invalid Input - Enter the value of n greater than 0");
         }
     }
 }  

Output:

Case 1:

Enter the value of n: 1
Fibonacci series is: 0

Case 2:

Enter the value of n: 2
Fibonacci series is: 0 1

Case 3:

Enter the value of n: 5
Fibonacci series is: 0 1 1 2 3

Case 4:

Enter the value of n: -10
Fibonacci series is: Invalid Input – Enter the value of n greater than 0

If you like the tutorial share it with your friends. Like the Facebook page for regular updates and YouTube channel for video tutorials.

Leave a Comment

Your email address will not be published.