
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find the average of first N natural numbers in C++
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
- Related Articles
- Average of first n even natural numbers?
- PHP program to find the average of the first n natural numbers that are even
- Find the sum of first $n$ odd natural numbers.
- Average of Squares of n Natural Numbers?
- Find the good permutation of first N natural numbers C++
- 8085 program to find the sum of first n natural numbers
- Program to find sum of first n natural numbers in C++
- Find m-th summation of first n natural numbers in C++
- Average of first n odd naturals numbers?
- Sum of first n natural numbers in C Program
- PHP program to find the sum of cubes of the first n natural numbers
- Find permutation of first N natural numbers that satisfies the given condition in C++
- Sum of sum of first n natural numbers in C++
- Sum of square-sums of first n natural numbers
- Find if given number is sum of first n natural numbers in C++

Advertisements