Computer Applications
Write the program in Java to find the sum of the following series:
S = 2 - 4 + 6 - 8 + ……. to n
Java
Java Iterative Stmts
48 Likes
Answer
import java.util.Scanner;
public class KboatSeries
{
public void computeSeriesSum() {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
int sum = 0;
for (int i = 1, j = 2; i <= n; i++, j = j + 2) {
if (i % 2 == 0) {
sum -= j;
}
else {
sum += j;
}
}
System.out.println("Sum=" + sum);
}
}
Variable Description Table
Program Explanation
Output
Answered By
14 Likes
Related Questions
Write the program in Java to find the sum of the following series:
S = 1 + (1*2) + (1*2*3) + ……. + (1*2*3* ……. * n)
Write the program in Java to find the sum of the following series:
S = 1 + 1 + 2 + 3 + 5 + ……. to n terms
Write the program in Java to display the first ten terms of the following series:
1, 12, 123, 1234,
Write the program in Java to find the sum of the following series:
S = 1 + (1+2) + (1+2+3) + ……. + (1+2+3+ ……. + n)