Advertisements
Advertisements
Question
Write the program to find the sum of the following series:
S = a − a3 + a5 − a7 + ..................... to n
Answer in Brief
Solution
import java.util.*;
public class Q3e
{public static void main(String args[])
{int a, n, cnt = 1;
double term, sum = 0;
Scanner obj = new Scanner(System.in);
System.out.printIn("Enter the value of a");
a = obj.nextInt();
System.out.printIn("Enter the value of n");
n = obj.nextInt();
for (int i = 1; i <= n; i = i + 2)
{term = Math.pow(a, i);
System.out.printIn(term); // optional print
if (cnt % 2 == 0)
sum = sum − term;
else
sum = sum + term;
cnt++;
}
System.out.printIn("Sum of the series is " + (float) sum);
}}
shaalaa.com
Is there an error in this question or solution?
Chapter 1.09: Iterative Constructs in Java - EXERCISES [Page 124]