Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

Write a program to calculate and print the sum of the following series: Sum(x) = 2 – 4 + 6 – 8 + 10 - 12 … - 100

Program to demonstrate how to calculate and print the sum of the following series:
Sum(x) = 2 – 4 + 6 – 8 + 10 - 12 … - 100 in Java.


package com.hubberspot.java.series.problems;

public class Series {

    public static void main(String[] args) {

        int sumOfSeries = 0;
        
        int i = 2;
        
        while( i <= 100 ) {
            
            if(i % 4 == 0) { 
                
                sumOfSeries = sumOfSeries - i;
            
            }
            else {
                
                sumOfSeries = sumOfSeries + i;
            
            }
            
            i = i + 2;
        }
        
        System.out.println("Sum of the series : " + sumOfSeries);

    }

}


Output of the program : 

 
 
© 2021 Learn Java by Examples Template by Hubberspot