Home > Backend Development > C++ > body text

Given an odd number, find the average of all odd numbers

PHPz
Release: 2023-09-03 15:49:05
forward
1290 people have browsed it

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.

Example

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

  • Using a loop
  • Using the formula

The program finds the average of odd numbers up to n, using a loop

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 -

Sample code

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;
}
Copy after login

Output

The average of odd numbers till 15 is 8.000000
Copy after login
Copy after login

Calculate using formula Average of odd numbers up to n

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 -

Sample code

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;
}
Copy after login

Output

The average of odd numbers till 15 is 8.000000
Copy after login
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!