Download Our Beta Android App And Help Us Build Awesome Stuff!  Download Now.

Java Program to print Fibonacci series upto n terms

Fibonacci.txt
File size: 846 Bytes

File content type: text/plain

Category: Assignment

Course: B.Tech., ISC Board, and ICSE Board

Semester: 5

/**
 *
 * @program To print fibonacci series upto n terms
 *
 * Fibonacci Series: 0,1,1,2,3,5,8,13,21...
 * Each term is the sum of previous two terms
 */

import java.io.*;

public class Fibonacci {

    public static void main(String args[]) throws IOException {

        BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Enter number of terms to print");
        int n = Integer.parseInt(obj.readLine());

        for(int a = 0,b = 1,i = 1; i<=n ; i++) {
            if(i==1)
                System.out.print("0, ");
            else if(i==2)
                System.out.print("1, ");
            else {
                int c = a + b;
                System.out.print(c + ", ");
                a = b;
                b = c;
            }
        }
    }
}
Sample Input/Output

Enter number of terms to print
11
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,

Added by passhojao

Comments