Find the average of first N natural numbers in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a number n. Our task is to find the average of first N natural numbers.

Average of numbers is defined as the sum of all numbers divided by the total number of numbers.

Average of N natural numbers is defined as the sum of first N natural numbers divided by N.

Let's take an example to understand the problem,

Input : N = 23
Output : 12

Explanation

1 + 2 + 3 + ... + 22 + 23 = 276
276 / 23 = 12

Solution Approach

To find the average of the number we will use the formula for average which is,

Average = sum(N) / N

Average = (1 + 2 + 3 + ... + N) / N

We know that sum of N natural number is given by the formula,

$N^*(N+1)/2$

The average is,

Average = N*(N+1)/2*N = (N + 1)/2

Using this formula we can find the average of first N natural numbers.

Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
float calcAverage(int n) {
   return (float)( ((float)n + 1 )/2 );
}
int main() {
   int N = 45;
   cout<<"The average of first "<<N<<" natural numbers is "<<calcAverage(N);
   return 0;
}

Output

The average of first 45 natural numbers is 23
raja
Updated on 27-Jan-2022 09:08:26

Advertisements