Fibonacci Series in Java

13 Mar

What are Fibonacci Numbers?

Fibonacci numbers are a sequesnce of numbers in which the first number of the sequence is 0,the second number is 1, and each subsequent number is equal to the sum of previous two numbers, yielding the sequence 0,1,1,2,3,5,8,….

Recurrence Relation

Program

package com.bundle.algos;

public class FibonacciSeries {
public static void main(String args[]){
// enter the number n
int number = 20;
for(int i = 0;i<=number;i++){
int fibonacci = fibonacciSeries(i);
System.out.println(“fibonacci of ” + i + “: ” + fibonacci);
}
}

public static int fibonacciSeries(int n){
if(n == 0){
return 0;
}
else if(n==1){
return 1;
}else{
return (fibonacciSeries(n-1) + fibonacciSeries(n-2));
}
}
}

Reference : you can read more about Fibonacci series from here

Advertisement

Tags: , , ,

8 Responses to “Fibonacci Series in Java”

  1. swagatmishra March 13, 2009 at 1:10 am #

    you can also print the fibonacci series by using indirect recursion instead of using a loop.
    good post

    • hhimanshu March 13, 2009 at 2:48 am #

      Thanks!
      Are you talking about the first loop in main where I am incrementing “i” ?

  2. swagatmishra March 13, 2009 at 8:43 pm #

    yeah i am talking about the 1st loop

  3. hhimanshu March 14, 2009 at 8:50 am #

    okay! that was just to make output clear. Thanks for your inputs!

  4. laxmi March 29, 2010 at 8:51 am #

    plz need help in prog in java

    • hhimanshu March 29, 2010 at 9:10 am #

      yes, please let me know what help you need, I’ll try

      • laxmi March 29, 2010 at 9:15 am #

        Write a function named largestAdjacentSum that iterates through an array computing the sum of adjacent elements and returning the largest such sum. You may assume that the array has at least 2 elements.
        If you are writing in Java
        int largestAdjacentSum(int[ ] a)

        Examples:

        if a is return
        {1, 2, 3, 4} 7 because 3+4 is larger than either 1+2 or 2+3
        {18, -12, 9, -10} 6 because 18-12 is larger than -12+9 or 9-10
        {1,1,1,1,1,1,1,1,1} 2 because all adjacent pairs sum to 2
        {1,1,1,1,1,2,1,1,1} 3 because 1+2 or 2+1 is the max sum of adjacent pairs

  5. laxmi March 29, 2010 at 9:16 am #

    need help coding in java for this prob

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.