1) A fibonacci series is defined as follows:-
Fb[0] = 0
Fb[1] = 1
Fb[i] = Fb[i – 1] + fb[i – 2] for i >= 2
Write a program that generates the first n (the user decides how many) fibonacci terms and prints them. The program should also print their sum. (Use array(s))
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static int[] generateFibonacci(int n){
int[] Fb = new int[n];
Fb[0] = 0;
Fb[1] = 1;
for (int i = 2; i < n; i++){
Fb[i] = Fb[i - 1] + Fb[i - 2];
}
return Fb;
}
public static int getSum(int array[]){
int sum = 0;
for (int i = 0; i < array.length; i++){
sum += array[i];
}
return sum;
}
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of fibonacci terms: ");
int n = scanner.nextInt();
int [] Fibonacci = new int[n];
Fibonacci = generateFibonacci(n);
System.out.println("Array of the first n Fibonacci numbers: " + Arrays.toString(Fibonacci));
System.out.println("The sum of the first n Fibonacci numbers: " + getSum(Fibonacci));
}
}
Comments
Leave a comment