Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
Sum of Series in C
Free C tutorial: compute the sum of a series in C with loops and recursion, and learn why factorial overflow breaks the obvious solution.
Computing the sum of a series in C looks easy until the numbers get large, and that is exactly why it is such a valuable lesson. In this lecture of our free C programming course we sum the alternating series x – x³/3! + x⁵/5! – … both with a loop and with recursion, then discover why the straightforward power-and-factorial approach silently produces nonsense. These are the same numerical problems you meet in embedded C programming when a small microcontroller has to calculate sine without a math library. Every example here is original, compiled and tested.
What You Will Learn
- How to read a series and write its general term as a formula
- How to sum a series in C using a loop and an alternating sign
- How to write the same sum recursively by passing the running term down the calls
- Why computing power and factorial separately overflows, with measured evidence
- How the term recurrence removes overflow and saves work
- How float, double and the choice of stopping rule affect accuracy on embedded targets
Prerequisites
- Functions with parameters and return values
- Loops and the conditional (ternary) operator
- Recursion basics from the previous two lectures
- Linking the math library with
-lmwhen usingsin()for comparison
Understanding the Series
The series we sum is x/1! – x³/3! + x⁵/5! – x⁷/7! and so on. The signs alternate, the powers are odd numbers and each denominator is the factorial of the same odd number. This is the Taylor series of the sine function when x is in radians, so we can check our program against the standard library result.
Finding the general term
To write a loop we need a formula for the k-th term. Counting from k = 1, the exponent is 2k – 1, the denominator is (2k – 1)! and the sign is positive for odd k and negative for even k.
| k | Exponent 2k – 1 | Sign | Term |
|---|---|---|---|
| 1 | 1 | + | x / 1! |
| 2 | 3 | – | x³ / 3! |
| 3 | 5 | + | x⁵ / 5! |
| 4 | 7 | – | x⁷ / 7! |
| 5 | 9 | + | x⁹ / 9! |
The Obvious Approach and Why It Fails
Most beginners compute each term independently: one helper raises x to a power, another computes the factorial, and the loop divides one by the other. The code is easy to read, so it is worth seeing exactly where it breaks.
static uint64_t ep_fact_u64(unsigned n)
{
uint64_t f = 1U;
for (unsigned i = 2U; i <= n; i++) {
f *= i;
}
return f;
}
static double ep_power(double x, unsigned n)
{
double p = 1.0;
for (unsigned i = 0U; i < n; i++) {
p *= x;
}
return p;
}
static double ep_sine_naive(double x, unsigned terms)
{
double sum = 0.0;
for (unsigned k = 1U; k <= terms; k++) {
unsigned e = 2U * k - 1U;
double sign = (k % 2U == 0U) ? -1.0 : 1.0;
sum += sign * ep_power(x, e) / (double)ep_fact_u64(e);
}
return sum;
}
The factorial of 20 is 2432902008176640000, which still fits in a 64-bit unsigned integer. The factorial of 21 does not fit, and the multiplication silently wraps around. In our test run the wrapped value of 21! came out as 14197454024290336768, which is wrong. C does not report this; unsigned overflow is defined as wrap-around, so the program carries on with garbage. The 11th term of the series already needs 21!, so a series with only 11 terms is enough to hit the problem.
With a 32-bit long, which is common on microcontrollers, the limit is much worse: 13! already overflows, so only about six terms of the series would be safe.
Measured damage
For small inputs the error is invisible, which makes the bug dangerous. We compared the naive method with the better method introduced in the next section and with the library sin().
| Input | Better method | Naive method | Library sin() |
|---|---|---|---|
| x = 1, 5 terms | 0.841471010 | 0.841471010 | 0.841470985 |
| x = 3, 12 terms | 0.141120008 | 0.141119997 | 0.141120008 |
| x = 6, 14 terms | -0.279415502 | -75.288052624 | -0.279415498 |
| x = 6, 20 terms | -0.279415498 | -910780456081.775146484 | -0.279415498 |
Read the last two rows carefully. Adding more terms should make the answer better, but the naive method gets dramatically worse because the wrapped factorials make late terms enormous instead of tiny. The sine of any angle must lie between -1 and 1, so a result of -910780456081 is clearly wrong, yet the program prints it without any warning.
The Term Recurrence: Compute Each Term From the Last
The fix is to notice that consecutive terms are closely related. To go from term k to term k + 1 the exponent grows by 2, which multiplies by x squared, and the factorial grows by two more factors, 2k and 2k + 1, which divides by their product. The sign flips. So:
Recurrence
next term = current term × (-x × x) / ((2k) × (2k + 1))
Every term is now computed with one multiplication and one division of numbers of moderate size. No factorial and no large power is ever built, so there is nothing to overflow, and the work per term is constant instead of growing with k.
Iterative Sum of Series in C
/* Iterative: build each term from the previous one */
static double ep_sine_iter(double x, unsigned terms)
{
double term = x; /* first term: x^1 / 1! */
double sum = 0.0;
for (unsigned k = 1U; k <= terms; k++) {
sum += term;
term *= -(x * x) / ((2.0 * k) * (2.0 * k + 1.0));
}
return sum;
}
Look at the two accumulators. The variable sum is explicitly initialized to zero. Forgetting that initialization is a classic bug: a local variable in C has an indeterminate value, so the first addition would start from random stack contents and the answer would be wrong in a way that changes from run to run. The sign is handled by the minus in front of x * x, which is cleaner than tracking a separate sign variable.
Recursive Sum of Series in C
To make a recursive version we turn the loop state (k, the current term) into parameters, exactly as in the previous lecture. The function returns the current term plus the sum of all remaining terms. The base case is when k has passed the requested number of terms.
/* Recursive: the running term is handed down the call chain */
static double ep_sine_rec_step(double x, double term, unsigned k, unsigned terms)
{
if (k > terms) {
return 0.0;
}
double next = term * (-(x * x)) / ((2.0 * k) * (2.0 * k + 1.0));
return term + ep_sine_rec_step(x, next, k + 1U, terms);
}
static double ep_sine_rec(double x, unsigned terms)
{
return ep_sine_rec_step(x, x, 1U, terms);
}
Unlike a loop, the additions here happen while the calls return, so no call can finish until every deeper call has finished. The recursion depth equals the number of terms. For a dozen terms this is harmless; for thousands of terms on a small device it would not be.
Complete Program, Build and Output
The full test program contains the three versions above and a main() that compares them with the library function. You can assemble it from the listings in this lecture; the important parts are the three functions and the printing loop shown here.
#include <stdio.h>
#include <stdint.h>
#include <math.h>
/* ep_sine_iter, ep_sine_rec, ep_sine_naive and helpers go here */
int main(void)
{
double x = 1.0;
printf("x = %.1f, 5 terms\n", x);
printf("iterative : %.9f\n", ep_sine_iter(x, 5U));
printf("recursive : %.9f\n", ep_sine_rec(x, 5U));
printf("naive : %.9f\n", ep_sine_naive(x, 5U));
printf("libm sin : %.9f\n\n", sin(x));
printf("x = 3.0, 1..8 terms (iterative)\n");
for (unsigned n = 1U; n <= 8U; n++) {
printf("n=%u %.9f\n", n, ep_sine_iter(3.0, n));
}
return 0;
}
$ gcc -std=c99 -Wall -Wextra -O0 -o ep_sine ep_sine.c -lm
$ ./ep_sine
x = 1.0, 5 terms
iterative : 0.841471010
recursive : 0.841471010
naive : 0.841471010
libm sin : 0.841470985
x = 3.0, 1..8 terms (iterative)
n=1 3.000000000
n=2 -1.500000000
n=3 0.525000000
n=4 0.091071429
n=5 0.145312500
n=6 0.140874594
n=7 0.141130627
n=8 0.141119654
The iterative and recursive results agree to every printed digit, which is what we expect since they perform the same arithmetic in the same order. The difference of 0.000000025 from the library value after five terms is truncation error: it is about the size of the first term we left out, which is x to the power 11 divided by 11!. Watch the partial sums for x = 3: they swing wildly at first (3, then -1.5) and settle toward the true value of 0.14112 as the terms shrink.
Accuracy: Terms, Range and Number Type
How many terms are enough?
A fixed term count is fine for a lecture, but real code usually stops when the next term is smaller than a chosen tolerance. The series for small x converges very quickly; for large x it needs many terms. We measured the iterative method at x = 20: with 20 terms it returned -5364.411846, while the correct sine is 0.912945. With 40 terms it matched. So for large angles the term count must grow, and rounding error from adding huge terms of opposite sign also grows.
| Technique | What it fixes | Typical use |
|---|---|---|
| Stop when the term is tiny | Wasted work or too few terms | General purpose |
| Reduce x into a small range first | Slow convergence and cancellation | Any angle beyond one turn |
| Use the term recurrence | Factorial and power overflow | Always |
| Fixed-point or lookup table | No floating point hardware | Small microcontrollers |
float or double on a microcontroller
Using float is common in embedded work because many Cortex-M4F parts have a single-precision hardware FPU but not a double-precision one, so double arithmetic runs in slow software. The trade-off is precision: float carries about seven significant decimal digits, so you cannot expect nine-digit agreement. If you use float, write constants with the f suffix, such as 2.0f, or the compiler may silently promote the expression to double.
Real-World Uses
- Motor control and audio: generating sine waves for PWM drive, inverters and tone synthesis when a full math library is too big or too slow.
- Sensor processing: converting angles from an IMU or encoder into components without calling heavy library code.
- Exponential and logarithm approximations: the same recurrence trick (build each term from the previous) works for many series used in calibration code.
- Teaching numerical thinking: this problem shows overflow, cancellation and truncation in one small example.
Common Mistakes and Troubleshooting
- Uninitialized sum. Always set the accumulator to 0 before the loop.
- Computing factorial and power separately. It overflows long before the series converges.
- Integer division by accident. Writing
1 / 2instead of1.0 / 2.0gives 0. Use floating point literals in the formula. - Wrong loop bounds. Using
k < termsinstead ofk <= termsdrops the last term. - Passing degrees instead of radians. The series expects radians. Multiply degrees by pi and divide by 180 first.
- Recursing for many terms. Each term adds a stack frame, so keep the term count small or use the loop.
Best Practices, Performance and Security
- Build each term from the previous one instead of recomputing powers and factorials.
- Initialize accumulators, and keep the type of every constant consistent with the variables.
- Compare against the library result in tests, and test large inputs as well as small ones.
- Performance: the loop does a constant amount of work per term, so total cost grows linearly with the number of terms; the naive method grows quadratically because each term recomputes a power and a factorial.
- Security and robustness: validate the term count before recursing on it, because a huge value supplied from outside would exhaust the stack.
Summary and Key Takeaways
- Write the general term first, then decide how to compute it.
- Factorial overflows a 64-bit integer at 21!, and silently, so avoid building big factorials.
- The recurrence next = term × (-x²) / ((2k)(2k + 1)) is faster and safe from overflow.
- Loop and recursive versions give identical results; recursion costs one frame per term.
- Reduce the input range and choose float or double deliberately on embedded targets.
Conclusion
This lecture started as a simple request to add up a series and ended with a core engineering lesson: a solution that is correct on paper can be wrong in a computer, and the way to find out is to test beyond the comfortable range. You wrote a loop version, a recursive version and a naive version, watched the naive version collapse, and replaced it with a recurrence that is both safer and cheaper. That habit of thinking about number ranges is essential in C programming for embedded systems. In the next lecture of this free embedded C course we apply recursion to two classic number problems, the highest common factor and the least common multiple.
Frequently Asked Questions
Which series does this program compute?
It computes the Taylor series of the sine function, with alternating signs and odd powers divided by odd factorials. The result approximates sin(x) for x in radians.
Why not just call sin() from math.h?
You should when the library is available and fast enough. Writing the series yourself teaches numerical thinking, and it is useful on small devices where the library is too large or too slow.
What happens when unsigned factorial overflows in C?
Unsigned arithmetic wraps around modulo 2 to the power of the bit width, with no error. That is why 21! is wrong in a 64-bit unsigned integer.
Is the recursive version better than the loop?
It gives the same answer, but it uses one stack frame per term. The loop uses constant memory, so it is the better choice for embedded programs.
How do I choose the number of terms?
Stop when the absolute value of the next term drops below a tolerance that suits your application, and reduce large angles into a small range first so fewer terms are needed.
Why did the series give a wrong answer at x = 20 with 20 terms?
For large x the terms grow before they shrink, so 20 terms are not enough, and large terms of opposite sign also lose precision when added. More terms or range reduction fixes it.
Next: Recursive HCF and LCM
Continue the free embedded C course with Euclid’s algorithm and see recursion shrink a problem faster than any loop you have written so far.
Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments