C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Sum of Series Program - Java Programs

Write a program to calculate and print the sum of each of the following series:
(a) Sum (S) = 2 – 4 + 6 – 8 + … – 20.
(b) Sum (S) = x / 2 + x / 5 + x / 8 + x / 11 + … + x / 20 where the value of x is to be input by the user.

import java.util.Scanner; class Series{ public static void main(String args[]){ Scanner in = new Scanner(System.in); int s1 = 0; double s2 = 0.0; for(int i = 2; i <= 20; i += 2){ if(i % 4 == 0) s1 -= i; else s1 += i; } System.out.println("Series 1 sum: " + s1); System.out.print("x = "); double x = Double.parseDouble(in.nextLine()); for(int i = 2; i <= 20; i += 3) s2 += x / i; System.out.println("Series 2 sum: " + s2); } }

Output

 
 OUTPUT : 
 
Series 1 sum: -10
x = 5
Series 2 sum: 5.480805958747134