Sunday, 11 October 2015

Java code to generate Fibonacci series

Requirement: I want to write a Java program to create a Fibonacci series.
In mathematics, the Fibonacci numbers or Fibonacci sequence are the numbers in the following integer sequence:[1][2]
    1,1,2,3,5,8,13,21,34,55,89,144,........
or (often, in modern usage):
    0,1,1,2,3,5,8,13,21,34,55,89,144,.......
 The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The next number is found by adding up the two numbers before it. The 2 is found by adding the two numbers before it (1+1).

Solution: The Java code for the above requirement is shown below:

Program:
package com.susanto;

import java.util.Scanner;

public class FibonacciSeries {
      public static void main(String args[]) {
            int firstNumber = 0;
            int secondNumber = 1;
            int nextNumber;
            int i;
            Scanner s = new Scanner(System.in);
            System.out.print("Enter number of elements : ");
            int totalNumber = s.nextInt();
            System.out.print(firstNumber + " " + secondNumber);
            for (i = 2; i < totalNumber; ++i)
            {
                  nextNumber = firstNumber + secondNumber;
                  System.out.print(" " + nextNumber);
                  firstNumber = secondNumber;
                  secondNumber = nextNumber;
            }
      }
}

Output:
Enter number of elements : 15
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Hence, the solution to our requirement.


Thanks & Regards,
Susanto Paul