Home » C Programs » Sum of Odd and Even Numbers in C

The user must first specify the number up to which the total is to be calculated, which is saved in the variable num. Take the elements one by one from 1 to num using the for loop.

Divide each element by 2 and use an if, else statement to determine whether it is odd or even. Set the odd sum and even sum variables to zero. If the element is even, add the element to the variable even sum. Separately print the variables odd sum and even sum, then leave. Main method to find the sum of odd and even numbers in c

A for loop is a repetition control structure that allows us to create a loop that runs a set number of times. The loop allows us to do an arbitrary number of steps in a single line. A loop variable is used to regulate the loop in for loop.

In every programming language, a loop is one of the most important notions. Conditional statements are used to build loops in the C programming language. In C, a set of loop control statements is performed a number of times until the condition is met. In C, a do-while loop is an exit control loop.

```
//sum of odd and even numbers in c
#include <stdio.h>
void main()
{
int i, number, odd_sum = 0, even_sum = 0;
printf("Enter the value of number\n");
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("Sum of all odd numbers = %d\n", odd_sum);
printf("Sum of all even numbers = %d\n", even_sum);
}
```

Output

Enter the value of number

45

Sum of all odd numbers = 529

Sum of all even numbers = 506