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 = i + 2) osum = osum + i ; for(i = 2 ; i <= n ; i = i + 2) esum = esum + 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 process, here we’re using two for loops (one for calculating sum of even numbers and other for sum of odd). So let’s understand each loop separately.
- Calculating sum of odd numbers -
The first for loop is for calculating sum of odd numbers. Notice the loop carefully. The loop will execute for i = 1 to n, incrementing the value of i by 2 after each iteration and thus reducing the total number of iterations to n/2. In other words, this loop will only work for odd values of i i.e. for i = 1, 3, 5….. n (if n is odd). Inside the loop we simply add the value of loop variable i to the sum of odd numbers i.e. osum (that has been calculated so far) and storing the sum again in osum.
- Calculating sum of even numbers -
The second for loop is for calculating sum of even numbers. Notice this loop also carefully. The loop will execute for i = 2 to n, incrementing the value of i by 2 after each iteration and thus reducing the total number of iterations to n/2. In other words, this loop will only work for even values of i i.e. for i = 2, 4, 6….. n (if n is even). Inside the loop we simply add the value of loop variable i to the sum of even numbers i.e. esum (that has been calculated so far) and storing the sum again in esum.
After both loops are finished executing, we simply print the result back to user.
Also look at: Another approach to Find the Sum of Even and Odd Numbers using Single For Loop.