Fibonacci Series
Write a program to print the following series: 0+1+1+2+3+5+8+ .......... up to n terms.
/* This is a fibonacci series where starting from the third term,
every term can is the sum of its previous two terms. */
import java.io.*;
class Fibonacci{
public static void main(String args[])throws IOException{
//declare all the variables at the beginning
int n,i,a,b,c,sum;
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter the number of terms : ");
n=Integer.parseInt(br.readLine());
//initialize the first two terms
a=0;
b=1;
//set the sum as 0 initially.
sum=0;
//add the first two tems to sum
sum=sum+a+b;
//Generate fibonacci series by adding a and b and
//changing them each time the loop runs
for(i=1;i<=n-2;i++){
c=a+b;
sum=sum+c;
a=b;
b=c;
}//end of loop
System.out.print("Sum = "+sum);
}//end of main
}//end of class
Have something to say? Log in to comment on this post.
0 comments