C Program to find the sum of a Finite Series – Tutorial

Finding the sum of a series(finite or infinite) is a crucial part of computational mathematics.

Many mathematical functions can be simply expressed in the form of a series as shown below:

Exponential Series:

Sine Series:
\sin (x) = x - \frac{x^3}{3!} + \frac{x^5}{5!} - ....

Cosine Series:
\cos (x) = 1 - \frac{x^2}{2!} + \frac{x^4}{4!} - ....
NOTE: These can be obtained using the Taylor Series expansions.

In this post I will show you how to find the sum of a finite series efficiently.

Let’s consider the following series:
S(x)= 1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} + ....

Note: the no. of terms in this series is (n+1)

Now if you wanted to find the sum of the first 30 terms, then naively, you would try to run a loop and evaluate each term and thus find the sum. Though, doable, this method is not very efficient, especially if there are large numbers involved(like 20!).

A better way would be to find the ratio of consecutive terms and then use that to calculate the successive terms of the series and thus find the sum. This would eliminate the problem of needlessly working with large numbers, as the ratio of successive terms   would be relatively very small.

The approach would be something like this:

Find the ratio of the successive terms,

Now, using this, the successive terms can be found as:
….. and so on.

For a program to find the sum for the first n terms can be written as shown below:


******FINITE SERIES SUM**********
Series: S(x) = 1 + x + x/1 + (x^2/2!) + (x^3/3!) + ..... + (x^n/n!)
	int i,n;
	/*Initialize t0 with the value of the first term of the series */
	double t0=1;
	/*Declare more variables to be used */
	double x;
	double t1,R,sum=t0;
	printf("Enter the value of x: ");
	printf("Enter the number of terms to be summed(n): ");
	printf("\nThe sum is: %f",sum);

As you might have noticed by now, the above series is the exponential series, and you can check your results calculating the exponential of the function.


[wpedon id="7041" align="center"]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.