Generate Fibonacci Series in Java

Write a program to display the first N Fibonacci numbers, and also find and display their sum. The value of N has to be input by the user.

Program:

import java.io.*;
class Fibonacci{
    public static void main(String args[])
    throws IOException{
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);
        System.out.print("N = ");
        int n = Integer.parseInt(br.readLine());
        long sum = 0;
        int a = 0;
        int b = 1;
        System.out.print("Fibonacci Series: ");
        for(int i = 1; i <= n; i++){
            long t = fibo(i);
            sum += t;
            System.out.print(t + "\t");
        }
        System.out.println("\nSeries sum = " + sum);
    }
    public static long fibo(int n){
        if(n == 1)
            return 0L;
        else if(n == 2)
            return 1L;
        else
            return fibo(n - 1) + fibo(n - 2);
    }
}

Leave a Reply

%d bloggers like this: