Find N Arithmetic Means between A and B using C++.


Suppose we have three integers A, B and N. We have to find N arithmetic means between A and B. If A = 20, B = 32, and N = 5, then the output will be 22, 24, 26, 28, 30

The task is simple we have to insert N number of elements in the Arithmetic Progression where A and B are the first and last term of that sequence. Suppose A1, A2, …. An are n arithmetic means. So the sequence will be A, A1, A2, …. An, B. So B is the (N + 2)th term of the sequence. So we can use these formulae −

$$B=A+\lgroup N+2-1\rgroup*d$$

$$B-A=\lgroup N+2-1\rgroup*d$$

$$d=\frac{B-A}{\lgroup N+2-1\rgroup}$$

Example

 Live Demo

#include<iostream>
using namespace std;
void showMeans(int A, int B, int N) {
   float d = (float)(B - A) / (N + 1);
   for (int i = 1; i <= N; i++)
      cout << (A + i * d) <<" ";
}
int main() {
   int A = 20, B = 40, N = 5;
   showMeans(A, B, N);
}

Output

23.3333 26.6667 30 33.3333 36.6667

Updated on: 30-Oct-2019

57 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements