
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements