Average of even numbers till a given even number?

To find the average of even numbers till a given even number, we need to sum all the even numbers up to that number and divide by the count of even numbers.

Syntax

average = sum_of_even_numbers / count_of_even_numbers

Example

Average of even numbers till 10 is calculated as −

Even numbers: 2, 4, 6, 8, 10
Sum: 2 + 4 + 6 + 8 + 10 = 30
Count: 5
Average: 30 ÷ 5 = 6

There are two methods for calculating the average of even numbers till n (where n is even) −

  • Using Loops − Iterate and sum all even numbers
  • Using Formula − Apply mathematical formula (n+2)/2

Method 1: Using Loops

This approach iterates through all numbers from 1 to n, identifies even numbers, calculates their sum and count, then computes the average −

#include <stdio.h>

int main() {
    int n = 14, count = 0;
    float sum = 0;
    
    for (int i = 2; i <= n; i += 2) {
        sum = sum + i;
        count++;
    }
    
    float average = sum / count;
    printf("Even numbers till %d: ", n);
    for (int i = 2; i <= n; i += 2) {
        printf("%d ", i);
    }
    printf("\nSum: %.0f, Count: %d<br>", sum, count);
    printf("Average of even numbers till %d is %.2f<br>", n, average);
    
    return 0;
}
Even numbers till 14: 2 4 6 8 10 12 14 
Sum: 56, Count: 7
Average of even numbers till 14 is 8.00

Method 2: Using Formula

For even numbers till n (where n is even), the average can be calculated using the mathematical formula: (n + 2) / 2

#include <stdio.h>

int main() {
    int n = 14;
    
    if (n % 2 != 0) {
        printf("Please enter an even number.<br>");
        return 1;
    }
    
    float average = (float)(n + 2) / 2;
    printf("Using formula: (%d + 2) / 2 = %.2f<br>", n, average);
    printf("Average of even numbers till %d is %.2f<br>", n, average);
    
    return 0;
}
Using formula: (14 + 2) / 2 = 8.00
Average of even numbers till 14 is 8.00

Comparison

Method Time Complexity Space Complexity Advantages
Loop Method O(n) O(1) Shows calculation steps
Formula Method O(1) O(1) Instant result, efficient

Conclusion

Both methods effectively calculate the average of even numbers. The formula method (n+2)/2 is more efficient for direct calculation, while the loop method provides better understanding of the underlying process.

Updated on: 2026-03-15T10:50:01+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements