C Program to Find the Sum of Even and Odd Numbers

In this C programming tutorial, we will write a program to find the sum of even and odd numbers from 1 to n, where n is a positive integer entered by the user. This program demonstrates the use of loops, conditional statements, and arithmetic operations in C programming.

Problem Statement:

Write a C program to find the sum of even and odd numbers from 1 to n, where n is a positive integer entered by the user.

Solution:

To solve this problem, we will use a for loop to iterate over the numbers from 1 to n. Inside the loop, we will use an if statement to check whether the current number is even or odd, and we will update the sum of even and odd numbers accordingly. Here’s the code for our solution:

#include <stdio.h>

int main() {
    int n, i, even_sum = 0, odd_sum = 0;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    for(i = 1; i <= n; i++) {
        if(i % 2 == 0) {
            even_sum += i;
        }
        else {
            odd_sum += i;
        }
    }

    printf("Sum of even numbers from 1 to %d is %d\n", n, even_sum);
    printf("Sum of odd numbers from 1 to %d is %d\n", n, odd_sum);

    return 0;
}

Output

  1. The stdio.h header file is included for standard input/output functions.
  2. The main() function is declared as the entry point of the program.
  3. The start, end, even_sum, and odd_sum variables are declared. even_sum and odd_sum are initialized to zero.
  4. The user is prompted to enter the starting number using printf() function.
  5. The user input is read and stored in the start variable using scanf() function.
  6. The user is prompted to enter the ending number using printf() function.
  7. The user input is read and stored in the end variable using scanf() function.
  8. A for loop is used to iterate through the numbers in the range from start to end.
  9. An if-else statement is used to determine whether each number is even or odd.
  10. If the number is even (i.e., the remainder when dividing by 2 is 0), the even_sum variable is updated to include the number.
  11. If the number is odd (i.e., the remainder when dividing by 2 is 1), the odd_sum variable is updated to include the number.
  12. Once the loop is complete, two printf() statements are called to display the sum of even and odd numbers in the given range.
  13. The main() function returns 0, which indicates that the program has executed successfully.

Explanation:

The program begins by including the stdio.h header file, which provides access to standard input/output functions. The main() function is then declared as the entry point of the program, and the start, end, even_sum, and odd_sum variables are declared.

Next, the user is prompted to enter the starting number and the ending number using the printf() function. The scanf() function is then used to read the user input and store it in the start