Showing posts with label fibonacci series program java. Show all posts
Showing posts with label fibonacci series program java. Show all posts

Tuesday, June 11, 2013

Fibonacci Series in Java

The first two numbers in a Fibonacci series is always 0 and 1. And each subsequent number is the sum of the previous two numbers. This is a very common series program given in ICSE board.
Below is the program written in Java that displays the Fibonacci series for a desired range:

import java.io.*;
class Fibonacci{
public static void main(String args[])throws IOException{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int range, i, f1=0, f2=1, f3;
System.out.print("Enter the range:");
range=Integer.parseInt(br.readLine());
if(range==1)
System.out.println(f1);
else if(range==2)
System.out.println(f1+"\t"+f2);
else if(range>2){
System.out.print(f1+"\t"+f2);
for(i=3;i<=range;i++){
f3=f1+f2;
System.out.print("\t"+f3);
f1=f2;
f2=f3;
}
System.out.println();
}
else
System.out.println("Range should be positive.");
}
}