Best Fibonacci Program Using Java

One of the popular Java coding interview question, this question is very common and almost all the companies ask this type of question specially in campus selection, this type of question is used to check the candidates logical analysis capacity and basic understanding of programming. In earlier post, I had shared a list of Java written interview question and in this article going to show you different way to write Fibonacci program.

What is Fibonacci Series?
In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones."copied from the wiki
Example, 0,1,1,2,3,5,8,13,21,34,55,89...

package com.javamakeuse.poc;

import java.math.BigInteger;

public class Fibonacci {
 public static void main(String[] args) {

  printFibonacci(10);
 }

 public static void printFibonacci(int n) {
  BigInteger a = BigInteger.ZERO;
  BigInteger b = BigInteger.ONE;
  BigInteger c = a.add(b);
  System.out.println(a);
  System.out.println(b);
  for (int i = 0; i < n; i++) {
   c = a.add(b);
   System.out.println(c);
   a = b;
   b = c;
  }
 }
}

Output:
0
1
1
2
3
5
8
13
21
34
55
89

Comments

Popular posts from this blog

JSP Servlet Interview Questions For Freshers Series 1

Java Banking Finance Services and Insurance (BFSI) domain interview questions

Java program to check even or odd number