Answer to Question #316310 in Java | JSP | JSF for Jay

Question #316310

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))



1
Expert's answer
2022-03-26T08:42:50-0400
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));
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS