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.
Hi Tanmay,
Grazie! Grazie! Grazie! Your blog is indeed quite interesting around C Programming Tutorial! I agree with you on lot of points!
Getting memory violation error when i use string function "strlwr", what wrong in step 3, please help, I am new to c language
char *a="SAM";
char *c;
c=strlwr(a);
printf("%s",c);
If the data is expensive to compare, the number of comparisons used even by a binary search might be too many. So instead of looking at the data themselves, you’ll condense (hash) the data to an integer (its hash value) and keep all the data with the same hash value in the same place. This task is carried out by using the hash value as an index into an array.
Very useful article, if I run into challenges along the way, I will share them here.
Kind Regards,
Kevin