Advertisements
Advertisements
Question
Write the program in Java to find the sum of the following series:
S = 1 + 1 + 2 + 3 + 5 + ...................... to n terms
Answer in Brief
Solution
import java.util.*;
public class Q2a
{ public static void main(String args[])
{
Scanner obj = new Scanner(System.in);
int a = 0, b = 1, c = 0, sum = 0, n;
System.out.printin("FIBONACCI SERIES");
System.out.printin("Enter the value of n....that is, the number of terms");
n = obj.nextInt();
System.out.print(a + "," + b + ",");
sum = a + b;
for (int i = 1; i <= (n - 2); i++) // n-2 since 2 terms are printed outside loop |
{ c = a + b; :
System.out.print(c + ",");
sum += c;
a = b;
b = c;
}
System.out.println("\n Sum of the above series = " + sum);
}}
shaalaa.com
Is there an error in this question or solution?
Chapter 1.09: Iterative Constructs in Java - EXERCISES [Page 124]