Java Program to print Fibonacci series upto n terms

Fibonacci.txt

File size: 846 Bytes

File content type: text/plain

Category: Practical Files

Subject: Java Programming

/** * * @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,

Last Updated: July 16, 2022

Related