Find Fibonacci series upto given levels

Fibonacci series is the series of numbers in which next number is the sum of previous two numbers. For example, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, etc. The first two numbers of Fibonacci series are 0 and 1.

In the given program, we will print the series upto the levels given by user. After giving 5 as a command line argument it will display only first five numbers in the series.


PROGRAM
class Fibonacci {

 public static void main(String[] args) {

  int a=0,b=1,temp,n;
  System.out.println("Fibonacci series upto given levels");
  System.out.println(a);
  System.out.println(b);
  n = Integer.parseInt(args[0]);
  
  n = n - 2;
  while(n > 0) {
   
   temp = a + b;
   a = b;
   b = temp;
   n--;
   System.out.println(temp);
  }
 }
}
OUTPUT 1
C:\>javac Fibonacci.java
C:\>java Fibonacci 5
Fibonacci series upto given levels
0
1
1
2
3
OUTPUT 2
C:\>javac Fibonacci.java
C:\>java Fibonacci 10
Fibonacci series upto given levels
0
1
1
2
3
5
8
13
21
34

Comments

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.