__Fibonacci series in Java__Write a Java program to print Fibonacci series up to a given number or create simple Java program to calculate Fibonacci number is common Java questions on fresher interview and homework. Fibonacci series is also a popular topic on various programming exercises in school and colleges. Fibonacci series is series of natural number where next number is equivalent to the sum of previous two number e.g.

**fn = fn-1 + fn-2**. The first two numbers of Fibonacci series is always 1, 1. In this Java program example for Fibonacci series, we create a function to calculate Fibonacci number and then print those numbers on Java console. Another twist in this questions is that sometime interviewer asks to write a Java program for Fibonacci numbers using recursion, so it's better you prepare for both iterative and recursive version of Fibonacci number.

One more coding question which is quite popular is printing prime numbers in Java which I have discussed earlier. In this tutorial, we will see an example of both recursive and iterative algorithm for Fibonacci series in Java.

For more coding questions you can always look into Cracking the Code Interviews, one of the finest collections of code based questions from programming interviews. You will find data structure and algorithmic questions asked on companies like Amazon, Google, Microsoft, and Facebook on this book.

##
__Printing Fibonacci numbers in Java : Sample Code Example__

Here is complete code example of printing Fibonacci Series in Java. Fibonacci series is calculated using both Iterative and recursive method and written in Java programming language. We have two functions in this example, fibonacci(int number) and fibonacci2(int number).The first one *print Fibonacci series using recursion*and the second one using for loop or iteration.

You can test this code on your computer as well. One you create your Java source file, just compile and run. It will ask you to enter the number till which you want to see the series. Once you enter then a number, it will print the Fibonacci series in the console.

##
__Java Program to print Fibonacci Series __

import java.util.Scanner; /** * Java program to calculate and print Fibonacci number using both recursion * and Iteration. * Fibonacci number is sum of previous two Fibonacci numbers fn= fn-1+ fn-2 * first 10 Fibonacci numbers are 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 * * @author Javin */ public class FibonacciCalculator { public static void main(String args[]) { //input to print Fibonacci series upto how many numbers System.out.println("Enter number upto which Fibonacci series to print: "); int number = new Scanner(System.in).nextInt(); System.out.println("Fibonacci series upto " + number +" numbers : "); //printing Fibonacci series upto number for(int i=1; i<=number; i++){ System.out.print(fibonacci2(i) +" "); } } /* * Java program for Fibonacci number using recursion. * This program uses tail recursion to calculate Fibonacci number for a given number * @return Fibonacci number */ public static int fibonacci(int number){ if(number == 1 || number == 2){ return 1; } return fibonacci(number-1) + fibonacci(number -2); //tail recursion } /* * Java program to calculate Fibonacci number using loop or Iteration. * @return Fibonacci number */ public static int fibonacci2(int number){ if(number == 1 || number == 2){ return 1; } int fibo1=1, fibo2=1, fibonacci=1; for(int i= 3; i<= number; i++){ //Fibonacci number is sum of previous two Fibonacci number fibonacci = fibo1 + fibo2; fibo1 = fibo2; fibo2 = fibonacci; } return fibonacci; //Fibonacci number } } Output: Enter number upto which Fibonacci series to print: 12 Fibonacci series upto 12 numbers : 1 1 2 3 5 8 13 21 34 55 89 144

After asking to write simple Java program to print Fibonacci series and later asking for Fibonacci series using recursion, another important question interviewer ask is

**how do you improve your Fibonacci function both iterative and recursive one?**

A technique called memoization can be used to drastically improve performance of method which calculates Fibonacci number. if you look at the method it repetitive creates same Fibonacci number e.g. In order to calculate 10th Fibonacci number function first create first 9 Fibonacci number, this could be very time consuming if you just increase the upper limit from 10 to 10K.

In memoization programming technique, result of earlier calculation is cached and reused. So you don't need to create same Fibonacci number if you already have calculated it. You can learn more about improving the performance of algorithms by reading a good book on data structure and algorithms e.g. Introduction to Algorithms by Thomas Cormen.

You can write code for Fibonacci series with memoization by just using a HashMap and checking if Fibonacci number for a corresponding number is already exits or not and calculate only if it doesn't exist.

###
__Fibonacci Number in Java with Memoization__

Here is the code example of printing Fibonacci number with memoization technique :/* * Java Program to calculate Fibonacci numbers with memorization * This is quite fast as compared to previous Fibonacci function * especially for calculating factorial of large numbers. */ public static int improvedFibo(int number){ Integer fibonacci = cache.get(number); if(fibonacci != null){ return fibonacci; //fibonacci number from cache } //fibonacci number not in cache, calculating it fibonacci = fibonacci2(number); //putting fibonacci number in cache for future request cache.put(number, fibonacci); return fibonacci; }

//comparison of performance of Fibonacci number with memoization int number = 100000000; long startTime = System.nanoTime(); int result = fibonacci2(number); //fibonacci number with memoization long elapsedTime = System.nanoTime() - startTime; System.out.println("Time taken to calculate Fibonacci number upto 100M without memorization:" + elapsedTime); startTime = System.nanoTime(); result = improvedFibo(number); //Fibonacci number with memoization elapsedTime = System.nanoTime() - startTime; System.out.println("Time taken to calculate Fibonacci number upto 100M with memorization:" + elapsedTime); Output: Time taken to calculate Fibonacci number upto 100M without memoization:149479613 Time taken to calculate Fibonacci number upto 100M with memoization:118972384

Interesting point is that improved method only shows better performance for large numbers like 100M otherwise iterative version of Fibonacci method is faster. That could be explained by extra work done by improved method in terms of storing value in cache and getting it from there or am I missing something? For more such questions for interviews, you can refer book like Programming Interviews Exposed by Wrox publication.

That's all on

**writing Java program to calculate and print Fibonacci series**. Fibonacci number is good question for programming exercise but when asked as question in Java interview you just need to be more detailed and precise about what you are doing.

Other

**Java programming exercise**and homework:

I had a homework exercise to write a Java program to print Fibonacci series up-to 100. Can I use your Java program to print Fibonacci series, is using recursion in a homework or programming exercise is valid ?

ReplyDeleteRecursion is actually an academic technique rather than professional one. I have hardly see any production code which is written using recursin, until ofcourse laguage optimize them into tail recursive algorithm to prevent stackoverflowerror. For example, Scala is a tail recursive language but not Java.

DeleteI've used recursion many times as a professional.

Deleteas an example, whenever your data set is a graph or hierarchy, the total number of children for any node should be a recursive algorithm

Shouldn't that be called "memoization" ?

ReplyDeleteYes, the technique which caches values of previously calculated fibonacci numbers is known as

Delete"memoization", and NOT"memorization"(with r). Though I agree, second one sounds more reasonable as it keeps values in memory, does any one knows why it's other way around?The comments in your code are wrong : you are indeed using recursion, but not tail-recursion.

ReplyDeleteTail recursion means that the last action performed by the method is directly returning the value from the recursive call, without modifying it.

In your example, your function calls itself recursively twice, before adding the two return values and returning the result. Hence, you aren't performing tail recursion.

A correct tail recursion implementation would be :

public static int tailRecursiveFibonacci(long number) {

// Bootstrap

return tailRecursiveFibonacci(3, 1, 1, number - 3);

}

private static int tailRecursiveFibonacci(long currentRank, int antePreviousResult, int previousResult, long howManyMoreRanks) {

final int resultForCurrentRank = antePreviousResult + previousResult;

if (howManyMoreRanks == 0) return resultForCurrentRank;

return tailRecursiveFibonacci(currentRank + 1, previousResult, resultForCurrentRank, howManyMoreRanks - 1);

}

Actually, you don't need the HowManyMoreRanks parameter:

Deletepublic int fib2 (n){

return fib (n,1,1)

}

public int fib_internal2 (int n, int acc1, int acc2) {

if (n == 0 || n == 1)

return acc2

else

return fib_internal2 (n-1, acc2, acc1 + acc2)

}

There is overflow for 48th fibonacci number for int return type.

ReplyDeleteSee other comment about recursion vs tail recursion. The tail recursive solution carries everything it needs with it rather than leaving it behind to be recombined when the stack is unwound, thus does not need multiple stack frames and won't cause a stack overflow.

DeleteAnonymous is correct.. this program will overflow the moment it crosses integer bounds.. i think we should use double as the datatype to initialize the variables.

ReplyDeleteNot double, but surely can use long for calculating fibonacci series of a large number. Double or double is used for floating point numbers, while IMHO fibonacci seems an integral algorithm.

DeleteTwo words as string values are provided as input. The program should find and print the positions having matching alphabets as output.

ReplyDeleteExample input and output:

If the input is "engine angry", the output should be "2 3" (As n in second position and g in third position match)

If the input is "male level", the output should be "4" (As e in fourth position matches)

i need answer.......

import java.util.Scanner;

Deletepublic class Question

{

public static void main(String[] args)

{

System.out.println("Enter 1st String");

String str1=(new Scanner(System.in)).next();

System.out.println("Enter 2nd String");

String str2=(new Scanner(System.in)).next();

for(int i=0;i<str1.length();i++)

{

for(int j=0;j<str2.length();j++)

if(str1.charAt(i)==str2.charAt(j) && i==j)

System.out.println("Idex is"+(i+1));

}

}

}

import java.io.BufferedReader;

ReplyDeleteimport java.io.IOException;

import java.io.InputStreamReader;

public class buddyq {

public static void main(String[] args) throws NumberFormatException, IOException {

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("enter the number::::::::::");

int a=Integer.parseInt(br.readLine());

System.out.println("fibinocii numbers are:::::");

int f1, f2=0, f3=1;

for(int i=1;i<=a;i++){

System.out.print(" \n"+f3+"\n ");

f1 = f2;

f2 = f3;

f3 = f1 + f2;

}

}

}

"A technique called memorization can be used to drastically improve performance..." because formula F3=F2+F1 is very slow for large numbers (exponential complexity). Enjoy performance http://slorents.blogspot.com.au/2013/11/climb-ladder-with-n-step.html

ReplyDeleteYes, it's called memoization (with the 'r'): Dynamic Programming.

DeleteThe caching pattern is called "Memoization", not memorize.

ReplyDeletehttp://en.wikipedia.org/wiki/Memoization

Here is a smart-alec implementation:

ReplyDeletepublic class Fib

{

static final double a1 = (Math.sqrt(5) + 1)/2;

static final double a2 = (Math.sqrt(5) - 1)/2;

static final double sq5 = Math.sqrt(5);

public static double fib(int n)

{

double term2 = (n % 2 == 1) ? Math.pow(a2,n) : -Math.pow(a2,n);

return (Math.pow(a1,n) + term2)/sq5;

}

public static void main(String[] args)

{

if (args.length < 1)

{

System.err.println("Missing argument");

System.exit(1);

}

int n = 0;

try

{

n = Integer.parseInt(args[0]);

}

catch (Exception e)

{

System.err.println("Bad argument");

System.exit(1);

}

System.out.println("fib(" + n + ") = " + fib(n));

}

}

The reason I called it smart-alec is that it defeats the likely purpose of the interview challenge - demonstrate your understanding of recursion. Fibonacci sequence can be computed using a formula which you can derive by solving a characteristic equation, and the computation will outperform the recursive or iterative method for sufficiently large values of N.

Hi,

ReplyDeleteThere is faults in your code examples shown here.

The Fibonacci numbers starts with a 0.

The first 21 Fibonacci numbers Fn for n = 0, 1, 2, ..., 20 are:[16]

F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 F13 F14 F15 F16 F17 F18 F19 F20

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765

Please see Wiki page:

http://en.wikipedia.org/wiki/Fibonacci_numbers

i have d ful corect program

ReplyDeleteIf you were to write this program in answer to a request in an interview, be sure to be rejected, for several reasons:

ReplyDelete1) Neither the iterative version nor the recursive one are correct. Both will silently overflow. Worst, your benchmark is completely broken. Since you do not use the result, the compiler could as well not calculate anything. This is an optimization the Java compiler is able to do (although it will not do it on the first pass). If you had simply printed the result to the console, it would have make this optimization impossible. And by the way, you should have noticed that the result of your program is 1819143227. Is this in the expected range?

2) As 'Anonymous' said, your recursive function is not tail recursive. But beside this, Java is not a true recursive language, so no simple recursive version will work above 50 to 100. To write a truly recursive version, one has to write all the necessary code to store intermediate calculations on the heap instead of on the stack. This is a good exercise.

3) Your example of memoization is wrong since it does absolutely nothing. You are calling the fibonacci2 function only once with a single value. Obviously, it is not in the cache. So the times should be equal. The difference you see is only due to the fact that you are calling the "non optimized" version first. Try to call the optimized version first and you'll get the inverse result.

4) The program should produce a collection of fibonacci numbers. This should be independent of what you intend to do with theses numbers (for example print them to the console as a string, with spaces as separators).

Here is an example that gives the correct result:

import java.math.BigInteger;

import java.util.stream.Collectors;

import java.util.stream.Stream;

public class Fibonacci {

private static long number = 1000;

public static void main(String[] args) {

Stream fiboStream = Stream.iterate(new Tuple<>(BigInteger.ONE, BigInteger.ONE), x -> new Tuple<>(x._2, x._1.add(x._2))).limit(number).map(x -> x._1);

String result = fiboStream.map(BigInteger::toString).collect(Collectors.joining(" "));

System.out.println(result);

}

static class Tuple {

public final T _1;

public final U _2;

public Tuple(T t, U u) {

this._1 = t;

this._2 = u;

}

}

}

Great, now we have Fibonacci series implemented using Java 8 lambdas and Streams :)

Deleteexcept BigInteger::toString won't compile, toString is not a static method

DeleteWhat if I wanted to use non tail recursive to print Fibonacci numbers up to the value inputed?

ReplyDeleteWhat is recursive???

ReplyDeleterecursive means a function calls itself to calculate result. Many mathematical operations can be represented using recursion e.g. factorial of n is nothing but n* factorial(n-1), so you are calling same function again. This is recursion. In this program Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2), that's why its recursive.

Deletehi can i get the java program for this question:

ReplyDeleteWrite a program to calculate the sum of integers 1 to n for a given number n

recursively. The program should contain a method to do the calculation and a main

method to test your method with the numbers 8 and 10.

public BigInteger fibonacci(BigInteger init, int index) {

ReplyDeleteBigInteger result = BigInteger.valueOf(1);

if (index != 0) {

init = init.add(init.add(BigInteger.valueOf(1)));

index--;

result = fibonacci(init, index);

} else {

result = init;

}

return result;

}

This is the only approach in which you can get to 100 because the number is so big that int or long cannot hold it...

This post saved my ass. I used it to make my program for my Grade 12 Computer Science course for a project that was 2 weeks late. Of course, I had to make some alterations because I was putting it into a JFrame, and not just the normal output that is at the bottom when you normally run a program. But you really saved me here. Keep up the good work. Side note: It's an online class, and the content is not very descriptive, so I often have to teach myself. Recursion was particularly gruesome to find an explanation for that made sense to me.

ReplyDelete

ReplyDeleteclass fib_recursive {

static void fib(int prevPrev, int prev, int limit){

int next = prevPrev + prev ;

System.out.println(next);

if(next > limit)

return ;

fib(prev,next,limit);

}

public static void main(String args[]) {

fib(0,1,30) ;

}

}

import java.util.*;

ReplyDeleteclass FibSeries

{

public static void main(String[] args)

{

Scanner s=new Scanner(System.in);

System.out.println("Enter the value of n");

int n=s.nextInt();

int a=-1,b=1,temp;

for (int i=0;i<n ;i++ )

{

temp=b;

b=a+b;

a=temp;

System.out.println(b);

}

}

}

As i have studied so far, Recursion means a function calls itself. Here in your program, the function is not calling itself. Then how is it recursion?

ReplyDeleteI dont think interviewer is going to satisfy with this code.

Hello Arun, can you clarify which code? I can see it recursive?

Deletepackage AllianzTechInterview;

ReplyDeletepublic class FibonacciSeries {

public static void main(String[] args) {

// TODO Auto-generated method stub

int n1=0,n2=0,n3=1;

while(n3<=100)

{

n1=n2;

n2=n3;

n3=n1+n2;

System.out.println(n3);

}

}

}

int n1=0,n2=1,n3;

Deletewhile(n3<=100){

n3=n1+n2;

System.out.println(n3);

n1=n2;

n2=n3;

}

it will give desire output febonacci:0 1 1 2 3.....

int n1=0,n2=1,n3;

Deletewhile(n3<=100){

n3=n1+n2;

System.out.println(n3);

n1=n2;

n2=n3;

}

see it will work Exact febonacci:0 1 1 2 3 5......