Print Fibonacci Series | Coding ninga Striver A2z
Problem statementGiven an integer ‘n’, return first n Fibonacci numbers using a generator function
Example:
Input: ‘n’ = 5 Output: 0 1 1 2 3
Code:
public class Solution {
public static int[] generateFibonacciNumbers(int n) {
if(n <= 0){
return new int[0];
}
else if(n == 1){
return new int[]{0};
}
else{
int fib[] = new int [n];
fib[0] = 0;
fib[1] = 1;
for(int i = 2;i<n;i++ ){
fib[i] = fib[i-1]+fib[i-2];
}
return fib;
}
}
}
Basic Java code for print Fibonacci series:-->
class HelloWorld {
public static void main(String[] args) {
int n = 15;
int f = 0 , s = 1;
for(int i = 0 ; i<n;i++){
System.out.println(f);
int tn = f+s;
f = s;
s = tn;
}
}
}
output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
No comments: