You can find the sum of all even numbers from 1 to 100 in Java using a simple loop and addition.
Java Code Example
Here's a Java code example demonstrating how to calculate the sum:
public class SumEven {
public static void main(String[] args) {
int sum = 0;
for (int i = 2; i <= 100; i = i + 2) {
sum = sum + i;
}
System.out.println("The sum of even numbers from 1 to 100 is: " + sum);
}
}
Explanation
- Initialization: We initialize a variable
sum
to 0. This variable will store the sum of the even numbers. - Looping through Even Numbers: A
for
loop starts from 2 (the first even number) and goes up to 100 (inclusive). The loop increments by 2 in each iteration (i = i + 2
), ensuring that only even numbers are considered. - Adding to the Sum: Inside the loop, the current even number
i
is added to thesum
variable. - Printing the Result: After the loop finishes, the final value of
sum
(which now holds the sum of all even numbers from 1 to 100) is printed to the console.
Alternative Approach (Starting from 10, as in the reference)
The provided reference code starts the loop from 10, which calculates the sum of even numbers between 10 and 100 (inclusive). Here is that code:
public class Sum {
public static void main(String[] args){
int sum=0;
for(int i=10; i<=100; i=i+2){
sum = sum + i;
}
System.out.println(sum);
}
}
This code calculates the sum of all even numbers from 10 to 100 (inclusive). If the objective is strictly from 1 to 100, the first example is preferred.