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?

王林
Release: 2023-08-25 23:53:06
forward
1095 people have browsed it

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

Output

The average of even numbers till 14 is 8.000000
Copy after login
Copy after login

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

Output

The average of even numbers till 14 is 8.000000
Copy after login
Copy after login

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!

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