Write a program to print fibonacci series upto n terms


  • The program starts by importing the Scanner class to allow user input.
  • In the main method, a Scanner object named "input" is created to read input from the user.
  • The user is prompted to enter the number of Fibonacci numbers they want to generate.
  • The input is read from the user using the nextInt() method of the Scanner object and stored in the variable "num".
  • The variables "a", "b", and "c" are initialized to 0, 1, and 0 respectively.
  • The program then enters a for loop that runs "num" times. The loop index "i" is used to keep track of the number of iterations.
  • Inside the loop, the current value of "c" is printed using the println() method of the System.out object.
  • The value of "a" is assigned to "b".
  • The value of "b" is assigned to "c".
  • The value of "a" plus "b" is assigned to "c".
  • The loop continues until it has run "num" times, at which point the program ends.
  • The output of the program is a list of Fibonacci numbers. The first two numbers in the sequence are 0 and 1, and each subsequent number is the sum of the two previous numbers.

Source Code

import java.util.Scanner;
class Fibonacci
{
	public static void main(String args[])
    {
        Scanner input = new Scanner(System.in);		
        System.out.print("Enter The Fibonacci Number : ");
        int num = input.nextInt();
		int a=0, b=1, c=0, i;		
        System.out.println("Fibonacci Numbers ... ");
		for(i=1; i<=num; i++)
		{
		   System.out.println(c);
			a = b;
			b = c; 
			c = a + b; 
		}
     }
}

Output

Enter The Fibonacci Number : 10
Fibonacci Numbers ...
0
1
1
2
3
5
8
13
21
34

Example Programs