Complementary task for topic: 2

M Nemeth · 2023-08-29 15:21:04.611220'

Loops: For loop: Print II.

Loops: For loop: Print II.

Task: Calculate the sum of even numbers from 1 to 100:
Write a C program that uses a for loop to calculate the sum of all even numbers from 1 to 100. Display the final sum using printf().

Hint: -

Solution
#include 

int main() {
    int sum = 0;
    int i;
    
    for (i = 2; i <= 100; i += 2) {
        sum += i;
    }
    
    printf("The sum of even numbers from 1 to 100 is: %d\n", sum);
    
    return 0;
}



Explanation
In this example, the program uses a for loop to iterate from 2 to 100, incrementing i by 2 in each iteration. This ensures that only even numbers are considered. The loop variable i is initialized to 2, and the loop continues as long as i is less than or equal to 100.

Inside the loop, the program adds the value of i to the sum variable to calculate the cumulative sum of even numbers.
< < previous    next > >