227k views
4 votes
Write code that uses a for loop to compute the sum of the even integers from 2 to 100 , inclusive. Declare a variable named evenSum to store the result.

User Juniperi
by
7.4k points

1 Answer

6 votes

Final answer:

To sum the even integers from 2 to 100, declare an integer variable evenSum, then use a for loop to iterate and add all even numbers to evenSum. The loop will increment by 2 to only consider even numbers, resulting in the final sum being stored in evenSum.

Step-by-step explanation:

To calculate the sum of even integers from 2 to 100, inclusive, using a for loop, you first need to declare a variable to store the sum. Next, you will write a for loop that iterates through the numbers in the specified range. Within the loop, use a condition to check if the number is even and, if so, add it to the sum. Below is the code that accomplishes this:

int evenSum = 0;
for (int i = 2; i <= 100; i += 2) {
evenSum += i;
}

This code snippet initializes evenSum to 0 and increments the loop counter i by 2 in every iteration, starting from 2. This ensures that only even numbers are summed, as the increment to i skips all odd numbers. The final result, which is the sum of all even numbers from 2 to 100, will be stored in evenSum after the loop completes.

User Adrocknaphobia
by
7.2k points