ChallengeChallenge

Print the sum of all even numbers from 1 to 100

Note

To determine if a number is even, you can utilize the modulus operator (%). This operator yields the remainder of division between the first number and the second. Consequently, if number % 2 == 0, then number is even. 


java

Main.java

  1. 1. Create a variable to store the sum and initialize it to 0;
  2. 2. Use a loop to iterate from 1 to 100;
  3. 3. Within the loop, check if the current number is even;
  4. 4. If the number is even, add it to the sum variable;
  5. 5. After the loop finishes, print the final sum.

package com.example;

public class Main {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            if (i % 2 == 0) {
                sum = sum + i;
            }
        }
        System.out.println("The sum of even numbers from 1 to 100 is: " + sum);
    }
}
      

Everything was clear?

Section 3. Chapter 7