Home >Backend Development >C++ >What is the average of all even numbers preceding a given even number?

What is the average of all even numbers preceding a given even number?

王林
王林forward
2023-08-25 23:53:061043browse

What is the average of all even numbers preceding a given even number?

To find the average of the even numbers before a given even number, we will add up all the even numbers before the given number and then count the number of even numbers. Then divide the sum by the number of even numbers.

Example

The average of even numbers up to 10 is 6, that is

2 4 6 8 10 = 30 => 30/ 5 = 6

There are two ways to calculate the average of even numbers up to n, namely even.

  • Using loops
  • Using formula

Program to calculate the average of even numbers up to n using loops

In order to calculate until n To average the even numbers, we will add all the even numbers up to n and divide by the number of even numbers up to n.

Calculation program for the average of even natural numbers up to n -

Sample code

Real-time demonstration

#include <stdio.h>
int main() {
   int n = 14,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 even numbers till %d is %f",n, average);
   return 0;
}

Output

The average of even numbers till 14 is 8.000000

Use Formula to calculate the average of even numbers up to n

To calculate the average of even numbers up to n we can use the mathematical formula (n 2)/2 where n is an even number This is the given condition in our question .

Program to calculate the average of n even natural numbers -

Sample code

Real-time demonstration

#include <stdio.h>
int main() {
   int n = 15;
   float average = (n+2)/2;
   printf("The average of even numbers till %d is %f",n, average);
   return 0;
}

Output

The average of even numbers till 14 is 8.000000

The above is the detailed content of What is the average of all even numbers preceding a given even number?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete