C++ Program to Calculate Sum of Geometric Progression

In this tutorial, we will learn and write a program to find the sum of GP series in C++. Before that, you may go through the following topics in C++ programming:

The program takes the first term, the common ratio and the number of terms as input and calculates the GP on a separate function.


C++ Program to Calculate Sum of Geometric Progression

#include <iostream>
using namespace std;

void gpFunc(float, float, int);

int main()
{
  int n;
  float a, r;

  cout << "Enter the first term (a): ";
  cin >> a;

  cout << "Enter the common ratio (r): ";
  cin >> r;

  cout << "Enter the no. of terms (n): ";
  cin >> n;

  //calling function
  gpFunc(a, r, n);
}

void gpFunc(float a, float r, int n)
{
  float sum = 0, temp = a;

  for (int i = 1; i < n; i++)
  {
    sum = sum + temp;
    temp = temp * r;
  }

  cout << "\nSum of geometric progression: " << sum;
}

Output:

Enter the first term (a): 1
Enter the common ratio (r): 2
Enter the no. of terms (n): 10

Sum of geometric progression: 511