Fibonacci Series in Java

This Java code defines a class Fibonacci that contains a main method. The main method prompts the user to enter a number and reads the input using a Scanner object. The code then generates the Fibonacci series up to the entered number using a for loop.

Inside the loop, the code initializes three variables a, b and c with the values -1, 1 and 0 respectively. For each iteration of the loop, the code calculates the sum of the previous two numbers in the series (a and b) and stores it in c. It then prints the value of c using the System.out.println method.

After printing c, the code updates the values of a and b to prepare for the next iteration. The value of b is assigned to a and the value of c is assigned to b.

Source Code

import java.util.Scanner;
//Write a program to find the fibonacci series of given number.
public class Fibonacci {
    public static void main(String args[])
        Scanner in = new Scanner(;
        System.out.println("Enter The Number : ");
        int n=in.nextInt();//5
        int a=-1,b=1,c;
        for(int i=1;i<=n;i++)//1<=5 2<=5 3<=5 4<=5  5<=5  6<=5
            c=a+b;//-1+1=>0  1+0=>1  0+1=1  1+1=2  1+2=3
            System.out.println(c); //0  1  1 2  3
            a=b;//1 0  1  1  2
            b=c;//0 1  1  2  3


Enter The Number :
To download raw file Click Here

Basic Programs