Home > Article > Backend Development > Given an odd number, find the average of all odd numbers
The average of odd numbers up to a given odd number is a simple concept. You just need to find the odd numbers up to that number, then add them and divide by that number.
If you want to find the average of odd numbers up to n. Then we will find the odd numbers from 1 to n and add them together and divide by the number of odd numbers.
The average of odd numbers up to 9 is 5, i.e.
1 3 5 7 9 = 25 => 25/5 = 5
There are two ways to calculate the average of odd numbers up to n, where n is an odd number
In order to calculate until To average the odd numbers of n, we will add all the numbers up to n and divide by the number of odd numbers up to n.
Program for calculating the average of odd natural numbers up to n -
Real-time demonstration
#include <stdio.h> int main() { int n = 15,count = 0; float sum = 0; for (int i = 1; i <= n; i++) { if(i%2 != 0) { sum = sum + i; count++; } } float average = sum/count; printf("The average of odd numbers till %d is %f",n, average); return 0; }
The average of odd numbers till 15 is 8.000000
To calculate the average of odd numbers up to n, we can use the mathematical formula (n 1)/2, where n is odd, is a given in our problem.
Program to calculate the average of odd natural numbers up to n -
Live demonstration
#include <stdio.h> int main() { int n = 15; float average = (n+1)/2; printf("The average of odd numbers till %d is %f",n, average); return 0; }
The average of odd numbers till 15 is 8.000000
The above is the detailed content of Given an odd number, find the average of all odd numbers. For more information, please follow other related articles on the PHP Chinese website!