Fibonacci series in java | codeyourslf
In this article we are going to learn how to find the fibonacci number using java programming language with 2 different approaches.
Approach :- 1 "fibonacci number using for loop in java"
package CodeYourslf.allPrograms.fibonacciNumber;
import java.util.Scanner;
public class usingForLoop {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number: ");
int num = sc.nextInt();
int n1 = 0, n2 = 1, n3;
System.out.print(n1 +" "+n2);
for(int i = 2; i <= num; i++){
n3 = n1 + n2;
System.out.print(" "+n3);
n1 = n2;
n2 = n3;
}
}
}
output
Approach:- 2 "fibonacci number using while loop in java"
package CodeYourslf.allPrograms.fibonacciNumber;
import java.util.Scanner;
public class usingWhileLoop {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number: ");
int num = sc.nextInt();
int n1 = 0, n2 = 1, n3;
System.out.print(n1 +" "+n2);
int i = 2;
while(i <= num){
n3 = n1 + n2;
System.out.print(" "+n3);
n1 = n2;
n2 = n3;
i++;
}
}
}
Code Explanation
- In Fibonacci series the 3rd number is the addition of previous two numbers.
- This Fibonacci series start with 0 followed by 1 and here the 3rd number will be 0+1 = 1, and now again the next number will be 1 + 1 = 2 and so on
- -Ex:- 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21
Approach:-1
- Here I have used for loop to find the Fibonacci series upto a given number in java.
- Previously I have assigned two variables n1 = 0 and n2 = 1, now the n3 is the 3rd variable i.e n3 = n1 + n2.
- Now we make the n2 as n1 and n3 as n2. It will go upto num and print the Fibonacci series.
Approach:- 2
- To find a Fibonacci series, the logic part is same as the for loop.
- we just assign the i outside the while loop and increment i inside the loop i.e i++.
- If you learn something new from this article please share with your friends
- If you have any query or doubt in your mind, please comment down below π.