Average of first n odd naturals numbers?

In this article, we will learn how to find the average of the first n odd natural numbers using C programming. The first n odd natural numbers are 1, 3, 5, 7, 9, ... and so on. To get the ith odd number, we can use the formula 2*i - 1 (where i starts from 1).

Syntax

float averageOddNumbers(int n);

Algorithm

Begin
   sum := 0
   for i from 1 to n, do
      sum := sum + (2*i - 1)
   done
   return sum/n
End

Method 1: Using Loop to Calculate Sum

This approach calculates the sum of first n odd numbers using a loop and then finds the average −

#include <stdio.h>

float averageOddNumbers(int n) {
    int sum = 0;
    for (int i = 1; i <= n; i++) {
        sum += (2 * i - 1);
    }
    return (float)sum / n;
}

int main() {
    int n = 5;
    float average = averageOddNumbers(n);
    printf("First %d odd numbers: ", n);
    for (int i = 1; i <= n; i++) {
        printf("%d ", 2 * i - 1);
    }
    printf("\nAverage: %.2f<br>", average);
    return 0;
}
First 5 odd numbers: 1 3 5 7 9 
Average: 5.00

Method 2: Using Mathematical Formula

We can use the mathematical property that the sum of first n odd numbers equals n². Therefore, the average is simply n −

#include <stdio.h>

float averageOddNumbersFormula(int n) {
    /* Sum of first n odd numbers = n^2 */
    /* Average = Sum/n = n^2/n = n */
    return (float)n;
}

int main() {
    int n = 7;
    float average = averageOddNumbersFormula(n);
    printf("Average of first %d odd numbers: %.2f<br>", n, average);
    
    /* Verification using loop method */
    int sum = 0;
    for (int i = 1; i <= n; i++) {
        sum += (2 * i - 1);
    }
    printf("Verification - Sum: %d, Average: %.2f<br>", sum, (float)sum / n);
    return 0;
}
Average of first 7 odd numbers: 7.00
Verification - Sum: 49, Average: 7.00

Key Points

  • The ith odd number is given by the formula 2*i - 1 where i starts from 1.
  • The sum of first n odd numbers equals .
  • Therefore, the average of first n odd numbers is always equal to n.
  • The mathematical approach has O(1) time complexity compared to O(n) for the loop method.

Conclusion

The average of the first n odd natural numbers can be calculated efficiently using either a loop or the mathematical formula. The mathematical approach is optimal as it directly gives the result that the average equals n.

Updated on: 2026-03-15T11:01:29+05:30

329 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements