Computer Science, asked by danish3654, 10 months ago

How to find the sum of Fibonacci series in java?​

Answers

Answered by SB142
4

import java.util.*;
public class Fibonacci
{
public static void main(String args[ ])
{
Scanner s=new Scanner(System.in);
System.out.print("Enter no. of terms:");
int n=s.nextInt();
int i, k1=0,k2=1,sum=0;
for(i=1;i<=n;i++)
{
System.out.print(k1+"+");
sum=k1+k2;
k1=k2;
k2=sum;
}
System.out.print("\n Sum is "+ sum);
}
}
Output: Enter no. of terms: ...
0+1+1+2+3+5.....+n
Sum is .....

SB142: Yes, u r right
SB142: I will try again and edit the answer.
SB142: ok
SB142: See, it can be corrected by replacing the last print line by this: System.out.print("Sum is "+sum-1);
SB142: Hope it works...
SB142: Try and tell. :-)
danish3654: i tried the same ( sum-1) btw in the o/p its printing the the value of sum minus 1. suppose sum= 4, so in the o/p its giving 4 - 1
danish3654: its shouldn't be displayed in that format.
SB142: so try using a variable x=sum-1; and then print itas "Sum is "+ x
danish3654: okay ..let me try
Answered by Anshuman706
0

Answer:public class fibonacci_series

{

public static void main(int n)

{

int a=0;

int b=1;

int s=0;

int c=0;

int i;

s=s+a+b;

System.out.print("The fibonacci series = "+a+","+b+",");

for(i=3;i<=n;i++)

{

c=a+b;

System.out.print(c+",");

a=b;

b=c;

s=s+c;

}

System.out.println("upto "+n+" terms completed");

System.out.println("\nThe sum of the fibonacci series upto "+n+" terms = "+s);

}

}

Explanation:

Similar questions