A directory of Objective Type Questions covering all the Computer Science subjects.
Here you can access and discuss Multiple choice questions and answers for various compitative exams and interviews.

C program to calculate the sum of odd and even numbers/

C program to calculate the sum of odd and even numbers

Problem Description

This C program calculates the sum of odd and even numbers separately from 1 to n (value of n is entered by the user). The for loop starts with 1 and continue up to the number entered by the user. To check whether the number in the current iteration is odd or even, the modulus operator is used.

C program to calculate the sum of odd and even numbers - Source code

/*C program to find the sum of odd and even numbers from 1 to N */
#include <stdio.h>
int main()
{
int i, n;
int sum_odd = 0, sum_even = 0;
printf("Enter the number up to which you want to calculate sum\n");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
// to check whether number is odd or even
if (i % 2 == 0)
sum_even = sum_even + i;
else
sum_odd = sum_odd + i;
}
printf("Sum of all even numbers = %d\n", sum_even);
printf("Sum of all odd numbers = %d\n", sum_odd);
}

Program Output

Case 1:
Enter the number up to which you want to calculate sum
100
Sum of all even numbers = 2550
Sum of all odd numbers = 2500
Case 2:
Enter the number up to which you want to calculate sum
25
Sum of all even numbers = 156
Sum of all odd numbers = 169

Program Explanation

1. Two integer variables i and n are declared. Two integer variables sum_odd and sum_even are declared and initialized to 0.
2. For loop starts the first iteration with 1 and continue up to the number entered by the user (n).
3. To check whether the number in the current iteration is even or odd, modulus operator (%) is used. This operator divides the number by 2 and returns the remainder. If reminder returned is 0, the number is even otherwise it is odd.
4. The value of sum_even and sum_odd operators is updated inside the loop and printed when the loop ends.