CC-9 : Generate first N Fibonacci numbers.
Description:
Fibonacci numbers are a series where each number is the sum of the two previous numbers. The series starts from 0 and 1, so the series generated 0, 1, 1, 2, 3, 5, 8... Given an input number N, find the first N Fibonacci numbers.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| Number: 3 |
First 3 Fibonacci numbers: 0 1 1 |
| Number: 9 |
First 9 Fibonacci numbers: 0 1 1 2 3 5 8 13 21 |
Pseudocode:
generateFibonacci(n):
| If num==0, return 0; (base case). |
| If num==1, return 1. |
| Find the sum of recursive calls to generateFibonacci(n-1) and generateFibonacci(n-2). |
printFibonacci(n):
| • Iterate through using for loop with idx as iteration variable and values of idx ranging from 0 to n:
o Call generateFibonacci(idx) and print the return value.
|
Code:
private int generateFibonacci(int n){
if (n == 0) {
return 0;
}else if (n==1){
return 1;
}else {
return generateFibonacci(n-1)+ generateFibonacci(n-2);
}
}
public void printFibonacci(int n) {
for (int iIdx=0; iIdx < n;iIdx++) {
System.out.println(generateFibonacci(iIdx));
}
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |