Average of odd numbers till a given odd number?

The average of odd numbers till a given odd number is calculated by finding the sum of all odd numbers from 1 to that number, then dividing by the count of odd numbers. This is a fundamental concept that demonstrates both iterative and mathematical approaches.

Syntax

Average = Sum of odd numbers / Count of odd numbers
Average = (n + 1) / 2    // Formula approach (where n is odd)

Example: Manual Calculation

For odd numbers till 9:

Odd numbers: 1, 3, 5, 7, 9

Sum: 1 + 3 + 5 + 7 + 9 = 25

Count: 5

Average: 25/5 = 5

Method 1: Using Loops

This approach iterates through numbers from 1 to n, identifies odd numbers, calculates their sum and count −

#include <stdio.h>

int main() {
    int n = 15;
    int count = 0;
    float sum = 0;
    
    printf("Odd numbers till %d: ", n);
    for (int i = 1; i <= n; i++) {
        if (i % 2 != 0) {
            printf("%d ", i);
            sum = sum + i;
            count++;
        }
    }
    
    float average = sum / count;
    printf("\nSum: %.0f<br>", sum);
    printf("Count: %d<br>", count);
    printf("Average of odd numbers till %d is %.2f<br>", n, average);
    return 0;
}
Odd numbers till 15: 1 3 5 7 9 11 13 15 
Sum: 64
Count: 8
Average of odd numbers till 15 is 8.00

Method 2: Using Mathematical Formula

For any odd number n, the average of odd numbers from 1 to n can be calculated using the formula: (n+1)/2 −

#include <stdio.h>

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

Comparison

Method Time Complexity Space Complexity Pros Cons
Loop Method O(n) O(1) Shows step-by-step calculation Slower for large numbers
Formula Method O(1) O(1) Instant calculation Requires mathematical understanding

Key Points

  • The formula (n+1)/2 works only when n is an odd number
  • For odd numbers 1 to n, there are (n+1)/2 odd numbers in total
  • The sum of first k odd numbers equals k²

Conclusion

Both methods effectively calculate the average of odd numbers till a given odd number. The loop method provides insight into the calculation process, while the formula method offers an efficient mathematical solution for immediate results.

Updated on: 2026-03-15T10:49:45+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements