Program for sum of geometric series in C

In C programming, calculating the sum of a geometric series involves finding the total of terms where each term is obtained by multiplying the previous term by a constant ratio. A geometric series follows the pattern: a, ar, ar2, ar3, ..., where 'a' is the first term, 'r' is the common ratio, and 'n' is the number of terms.

Syntax

float sumGeometric(float a, float r, int n);

Parameters

  • a − First term of the geometric series
  • r − Common ratio between successive terms
  • n − Number of terms in the series

Method 1: Iterative Approach

This method calculates the sum by iterating through each term and adding them one by one −

#include <stdio.h>

// Function to calculate sum of geometric series
float sumGeometric(float a, float r, int n) {
    float sum = 0;
    float term = a;
    
    for (int i = 0; i < n; i++) {
        sum += term;
        term *= r;
    }
    return sum;
}

int main() {
    float a = 1.0;    // First term
    float r = 0.5;    // Common ratio
    int n = 5;        // Number of terms
    
    printf("First term (a): %.1f<br>", a);
    printf("Common ratio (r): %.1f<br>", r);
    printf("Number of terms (n): %d<br>", n);
    printf("Sum of geometric series: %.6f<br>", sumGeometric(a, r, n));
    
    return 0;
}
First term (a): 1.0
Common ratio (r): 0.5
Number of terms (n): 5
Sum of geometric series: 1.937500

Method 2: Mathematical Formula

For better efficiency, we can use the mathematical formula: Sum = a × (1 - rn) / (1 - r) when r ? 1 −

#include <stdio.h>
#include <math.h>

float sumGeometricFormula(float a, float r, int n) {
    if (r == 1.0) {
        return a * n;  // When ratio is 1, sum = a * n
    }
    return a * (1 - pow(r, n)) / (1 - r);
}

int main() {
    float a = 2.0;    // First term
    float r = 2.0;    // Common ratio
    int n = 8;        // Number of terms
    
    printf("Example with a=%.1f, r=%.1f, n=%d<br>", a, r, n);
    printf("Sum using formula: %.6f<br>", sumGeometricFormula(a, r, n));
    
    return 0;
}
Example with a=2.0, r=2.0, n=8
Sum using formula: 510.000000

Comparison

Method Time Complexity Space Complexity Precision
Iterative O(n) O(1) Good
Formula O(1) O(1) Depends on pow()

Key Points

  • The iterative approach is more intuitive and avoids potential floating-point precision issues with pow().
  • The formula approach is more efficient for large values of n.
  • Handle the special case when r = 1 to avoid division by zero.

Conclusion

Both methods effectively calculate the geometric series sum. The iterative approach is safer for precision, while the formula method is more efficient for mathematical applications with large n values.

Updated on: 2026-03-15T12:59:12+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements