C Program to find the sum of all even numbers & odd numbers

For a better understanding of this C program example, we always recommend you to learn the basic topics of C programming listed below:

What is Odd and Even number? How to check it?

In this C program, the user enters the maximum limit value "n". Next, calculate the sum of even and odd numbers between 1 and the maximum limit value. An even number is a number that is divisible by 2., for example, 2, 4, 6, etc., and an odd number is a number that is not divisible by 2, for example, 1, 3, 5, 7, etc. In this c program, to calculate the sum of odd and even numbers separately, we need two separate sums as output, one for odd sum, and one for even sum. First, we have to check if the given number is odd or even; if the number is odd, we should add that to an odd sum, and if it is an even number, it gets added to an even sum.

How Odd and Even number check implemented in C?

We use a C program that accepts the user input in the integer data format. We initialize the sum for even numbers and odd numbers. Open a for loop from 1 to the number of integers the user input and increment the loop by one. Use the mod operator by 2 with the number, and we check if the remainder is zero or not. If that is zero, we add that number to the even sum or add that to the odd sum. Finally, after all the iterations of the 'for loop,' we print the result of the two sums separately. 


STEP 1: Include the Header Libraries into the C program to use the built-in functions.

STEP 2: Initialize the variables for Even Sum and Odd Sum as Zero and define the other variables.

STEP 3: Accepts the user input for the numbers and save that into a variable using printf and scanf.

STEP 4: Open 'For loop' from 1 to the number that the user input and increment the loop by one.

STEP 5: Use the Mod operator to check the Remainder is Zero or not with 2.

STEP 6: Use an if-else condition to check the Remainder is Zero or not.

STEP 7: If the Remainder is not Zero, add that number to Odd Sum else to Even Sum.

STEP 8: Print the result of two Sums separately using printf in the C programming language. 

C Source Code

                                          #include <stdio.h>

void main() {
  int i, N, oddSum = 0, evenSum = 0; // declares oddsum, evensum, i, n as integer. Defines oddsum and evensum as zero
  printf("Enter the value of N\n"); // accepts the value of N
  scanf("%d", & N);
  for (i = 1; i <= N; i++) {
    if (i % 2 == 0)
      evenSum = evenSum + i; // for loop to check whether the number is odd or even and add to the respective sum
      oddSum = oddSum + i;
  printf("Sum of all odd numbers  = %d\n", oddSum); // display the odd and even sum
  printf("Sum of all even numbers = %d\n", evenSum);



Enter the value of N

Sum of all odd numbers  = 25
Sum of all even numbers = 30


Enter the value of N

Sum of all odd numbers  = 625
Sum of all even numbers = 650