Write a C Program to find Sum of Even and Odd Numbers from 1 to n with example.
C Program to find Sum of Even and Odd Numbers from 1 to n
This program allows the user to enter the maximum limit value. Next, this C program calculate the sum of even and odd numbers between 1 and the maximum limit value
TIP: We already explained the logic to check whether the given is Even or Not in C Program to Check Odd or Even article.
/* C Program to find Sum of Even and Odd Numbers from 1 to N */ #include<stdio.h> int main() { int i, number, Even_Sum = 0, Odd_Sum = 0; printf("\n Please Enter the Maximum Limit Value : "); scanf("%d", &number); for(i = 1; i <= number; i++) { if ( i%2 == 0 ) { Even_Sum = Even_Sum + i; } else { Odd_Sum = Odd_Sum + i; } } printf("\n The Sum of Even Numbers upto %d = %d", number, Even_Sum); printf("\n The Sum of Odd Numbers upto %d = %d", number, Odd_Sum); return 0; }
Within this c program to find sum of even and odd numbers example, For Loop will make sure that the number is between 1 and maximum limit value.
for(i = 1; i <= number; i++)
In the Next line, We declared the If statement
if ( number % 2 == 0 )
Any number that is divisible by 2 is Even number. If condition will check whether the remainder of the number divided by 2 is equal to 0 or not.
- If the condition is True, then it is an Even number, and the C Programming compiler will add i value to Even_Sum.
- If the condition is False, then it is an Odd number, the compiler will add i value to Odd_Sum.
Program to find Sum of Even and Odd Numbers in a Given Range
This C program allows the user to enter Minimum and maximum limit value. Next, the C program calculates the sum of even and odd numbers between Minimum value and maximum value.
/* C Program to find Sum of Even and Odd Numbers from 1 to N */ #include<stdio.h> int main() { int i, Minimum, Maximum, Even_Sum = 0, Odd_Sum = 0; printf("\n Please Enter the Minimum, and Maximum Limit Values : \n"); scanf("%d %d", &Minimum, &Maximum); for(i = Minimum; i <= Maximum; i++) { if ( i%2 == 0 ) { Even_Sum = Even_Sum + i; } else { Odd_Sum = Odd_Sum + i; } } printf("\n The Sum of Even Numbers betwen %d and %d = %d", Minimum, Maximum, Even_Sum); printf("\n The Sum of Odd Numbers betwen %d and %d = %d", Minimum, Maximum, Odd_Sum); return 0; }
Please Enter the Minimum, and Maximum Limit Values :
10
100
The Sum of Even Numbers betwen 10 and 100 = 2530
The Sum of Odd Numbers betwen 10 and 100 = 2475