You are here : Home / Core Java Tutorials / Interview Programs (beginner to advanced) in java / Level1 programs for (beginner)
In this programming tutorial we will Write a program to generate Fibonacci series in java.
Example of fibonacci series in java -
0 1 1 2 3 5 8 13 21 34 55 89.
First number of series is 0 & second number of series is 1.
So, logic behind the series generation is that the subsequent number generated is sum of previous two number of series.
Example of fibonacci series in java -
First number of series is 0 & second number of series is 1.
So, third number will be 0+1=1
So, fourth number will be 1+1=2
So, fifth number will be 2+1=3 and so on…
Logic of fibonacci series in java ->
temp will be sum of previous two number of series(first and second)
than make first equal to second.
and then make second equal to temp. [now first and second are last two number of series]
Full Program/SourceCode/Example of fibonacci series in java -> >
/** Copyright (c), AnkitMittal www.JavaMadeSoEasy.com */
public class FibonacciSeriesExampleInJava {
public static void main(String[] args) {
int n=10; //number of elements in series.
generateFibonacciSeries(n);
}
public static void generateFibonacciSeries(int n){
int first=0; //first number of series
int second=1; //second number of series
int temp;
System.out.print("FibonacciSeries: "+ first+" "+second+" ");
for(int i=0;i<n;i++){
temp=first+second;
first=second;
second=temp;
System.out.print(temp+" ");
}
}
}
/*OUTPUT
FibonacciSeries: 0 1 1 2 3 5 8 13 21 34 55 89
*/
|
So in this programming tutorial we learned how to write a program to generate Fibonacci sequence in java with logic explanation and example.
Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.
RELATED LINKS>
Labels:
Core Java
Level1 programs (beginners)