C++ Program for sum of arithmetic series


Given with ‘a’(first term), ‘d’(common difference) and ‘n’ (number of values in a string) and the task is to generate the series and thereby calculating their sum.

What is an Arithmetic series

Arithmetic series is the sequence of numbers with common difference where the first term of a series is fixed which is ‘a’ and the common difference between them is ‘d’.

It is represented as −

a, a + d, a + 2d, a + 3d, . . .

Example

Input-: a = 1.5, d = 0.5, n=10
Output-: sum of series A.P is : 37.5
Input : a = 2.5, d = 1.5, n = 20
Output : sum of series A.P is : 335

Approach used below is as follows

  • Input the data as the first term(a), common difference(d) and the numbers of terms in a series(n)
  • Traverse the loop till n and keep adding the first term to a temporary variable with the difference
  • Print the resultant output

Algorithm

Start
Step 1-> declare Function to find sum of series
   float sum(float a, float d, int n)
   set float sum = 0
   Loop For int i=0 and i<n and i++
      Set sum = sum + a
      Set a = a + d
   End
   return sum
Step 2-> In main()
   Set int n = 10
   Set float a = 1.5, d = 0.5
   Call sum(a, d, n)
Stop

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
// Function to find sum of series.
float sum(float a, float d, int n) {
   float sum = 0;
   for (int i=0;i<n;i++) {
      sum = sum + a;
      a = a + d;
   }
   return sum;
}
int main() {
   int n = 10;
   float a = 1.5, d = 0.5;
   cout<<"sum of series A.P is : "<<sum(a, d, n);
   return 0;
}

Output

sum of series A.P is : 37.5

Updated on: 18-Oct-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements