Fibonacci Series Program – Java

Write a Java program to calculate Fibonacci Series up to n numbers.

- Advertisement -

It is a series in which the next term is the sum of the preceding two terms. For Example: 0 1 1 2 3 5 8 13……. Let’s write a Java program to calculate the Fibonacci series.

package Rootuser;
public class Fibonacci {
public static void main(String[] args) {
//initializing the constants
int n = 100, t1 = 0, t2 = 1;
System.out.print("Upto " + n + ": ");
//while loop to calculate fibonacci series upto n numbers
while (t1<= n)
{
if(t1!=n){
System.out.print(t1 + " + ");
} else{
System.out.print(t1);
}
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
}
}

 

- Advertisement -

On executing the above code, the output looks like :

Upto 100: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 + 89

 

 

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More