Here’s a C program that calculates the sum of all even and odd numbers that falls in a range from 1 to some limit say n with output and proper explanation. The program uses for loop.

# include <stdio.h> # include <conio.h> void main() { int n, i, osum = 0, esum = 0 ; clrscr() ; printf("Enter the limit : ") ; scanf("%d", &n) ; for(i = 1 ; i <= n ; i++) { if(i % 2 == 0) esum = esum + i ; else osum = osum + i ; printf("\nThe odd numbers sum is : %d", osum) ; printf("\n\nThe even numbers sum is : %d", esum) ; getch() ; }

**Output of above program is**

Enter the limit : 10

The odd numbers sum is : 25

The even numbers sum is : 30

**Explanation of above program**

The program takes a number n as limit and calculates the sum of all even and odd numbers within that limit. Although there can be different ways to do this calculation, in this process here we’re calculating modulo 2 of numbers to decide whether that number is even or odd and then adding that number to appropriate variable. So let’s understand how this program works.

The for loop will execute for i = 1 to n and in each iteration we’re checking if the loop variable i is even or odd by the following expression -

**i % 2**

If the value of above expression is 0 that means that value of i is even so we add that i to the sum of even numbers i.e. esum.

If the value of above expression is not 0 that mean the value of i is odd so we add that i to the sum of odd numbers i.e. osum.

In this way, the sums of even and odd numbers are calculated and then printed back to the user.

Also look at:Another approach to Find the Sum of Even and Odd Numbers using Two For Loops.