C Program to Calculate the Sum of Odd & Even Numbers:
This is a C program to find the sum of odd and even numbers from 1 to N.
Problem Description
The program takes the number N and finds the sum of odd and even numbers from 1 to N.
Problem Solution
Take the number N upto which we have to find the sum as input.
Using for loop take the elements one by one from 1 to N.
Using if,else statements separate the element as even or odd.
Add the even and odd numbers separately and store it in different variables.
Print the sum separately and exit.
Program/Source Code
#include
void main()
{
int i, num, odd_sum = 0, even_sum = 0;
<....
Show More
This is a C program to find the sum of odd and even numbers from 1 to N.
Problem Description
The program takes the number N and finds the sum of odd and even numbers from 1 to N.
Problem Solution
Take the number N upto which we have to find the sum as input.
Using for loop take the elements one by one from 1 to N.
Using if,else statements separate the element as even or odd.
Add the even and odd numbers separately and store it in different variables.
Print the sum separately and exit.
Program/Source Code
#include
void main()
{
int i, num, odd_sum = 0, even_sum = 0;
printf("Enter the value of num\n");
scanf("%d", &num);
for (i = 1; i <= num; i++)
{
if (i % 2 == 0)
even_sum = even_sum + i;
else
odd_sum = odd_sum + i;
}
printf("Sum of all odd numbers = %d\n", odd_sum);
printf("Sum of all even numbers = %d\n", even_sum);
}
Program Explanation
User must first enter the number upto which he/she wants to find the sum and is stored in the variable num.
Using for loop take the elements one by one from 1 to num.
Use if,else statement for each element to find whether it is odd or even by dividing the element by 2.
Initialize the variables odd_sum and even_sum to zero.
If the element is even,then increment the variable even_sum with the current element.
If the element is odd,then increment the variable odd_sum with the current element.
Print the variables odd_sum and even_sum separately and exit.
Output:
Case 1:
Enter the value of num
10
Sum of all odd numbers = 25
Sum of all even numbers = 30
Case 2:
Enter the value of num
100
Sum of all odd numbers = 2500
Sum of all even numbers = 2550
show less