Sum of Series Program in Python, C and Java (x and n)

The sum of series program is one of the most common loop questions in school and college practicals. You are given a value of x and a value of n, and you have to print the sum of a series such as 1 + x + x² + … + xⁿ. In this guide you will learn the sum of series program in Python, C and Java for four popular series, including the alternating series and the factorial series. Every program was run and tested, and a free interactive tool lets you watch the loop build the sum term by term.

★ Series Sum Programs using Loops

Pick a series, enter x and n, and watch the loop build the sum term by term.

Graphical view

Bars show the running total after each term (red = negative).

Code

Output

Note: if the exact value ends in 5 at the 5th decimal place, C and Python round to even while Java rounds up, so the last digit can differ.

Complete output

Prints the title, the code in the selected language and the complete output.

What You Will Learn

Problem Statement

Write a program to input the value of x and n and print the sum of the following series.
  1. 1 + x + x² + x³ + x⁴ + … + xⁿ
  2. 1 − x + x² − x³ + x⁴ − … xⁿ
  3. x + x²/2 + x³/3 + x⁴/4 + … + xⁿ/n
  4. x + x²/2! + x³/3! + x⁴/4! + … + xⁿ/n!

Here x can be any real number and n is a whole number that tells how many terms to add. The symbol n! means factorial of n, for example 4! = 4 × 3 × 2 × 1 = 24.

How to Solve Any Series Problem

Do not start by writing code. First answer three questions on paper:

  1. What is the i-th term? For example, the i-th term of Series 3 is xi / i.
  2. How can I get the next term from the previous one? Usually by multiplying by x (and sometimes dividing by i).
  3. What should the total start with? If the series begins with the constant 1, start the total at 1. If it begins with x, start the total at 0.

The table below shows the answers for all four series. Every program in this post follows it.

Seriesi-th termTotal starts atVariables needed
1xi1term
2(−1)i × xi1term, sign
3xi / i0power
4xi / i!0power, fact

The loop always runs for i from 1 to n, and the total is updated once in every pass. That is why the time complexity of all four programs is O(n).

The Four Series Programs

Each program reads x and n from the user, runs one loop, and prints the sum with 4 digits after the decimal point. Open the C and Java programs by clicking on their titles.

Series 1: 1 + x + x² + x³ + … + xⁿ

This is the simplest series. The first term is 1, and every next term is the previous term multiplied by x. So instead of calculating the power of x again and again, we keep one variable term and multiply it by x in every pass of the loop.

Logic:

  • Start: total = 1 and term = 1.
  • Loop: i from 1 to n.
  • Each pass: term = term * x, then total = total + term.

Python program

x = float(input("Enter x: "))
n = int(input("Enter n: "))
total = 1
term = 1
for i in range(1, n + 1):
    term = term * x
    total = total + term
print(f"Sum = {total:.4f}")
C program
#include <stdio.h>
int main() {
    int n;
    double x;
    printf("Enter x: ");
    scanf("%lf", &x);
    printf("Enter n: ");
    scanf("%d", &n);
    double total = 1, term = 1;
    for (int i = 1; i <= n; i++) {
        term = term * x;
        total = total + term;
    }
    printf("Sum = %.4f\n", total);
    return 0;
}
Java program
import java.util.Scanner;
public class Series {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter x: ");
        double x = sc.nextDouble();
        System.out.print("Enter n: ");
        int n = sc.nextInt();
        double total = 1, term = 1;
        for (int i = 1; i <= n; i++) {
            term = term * x;
            total = total + term;
        }
        System.out.printf("Sum = %.4f%n", total);
    }
}

Sample output:

Enter x: 2
Enter n: 5
Sum = 63.0000

Dry run for x = 2 and n = 3:

iterm (x^i)Added to totaltotal
start1–1
1223
2447
38815

Quick check: this is a geometric series, so for x ≠ 1 the answer must equal (xn+1 − 1) / (x − 1). For x = 2 and n = 5 that is (64 − 1) / 1 = 63, which matches the output above.

Series 2: 1 − x + x² − x³ + … xⁿ

This series looks like Series 1, but the signs alternate: plus, minus, plus, minus. The easiest way to handle that is a variable sign that flips between 1 and -1 in every pass. The term variable still holds xi, and the sign decides whether it is added or subtracted.

Logic:

  • Start: total = 1, term = 1 and sign = 1.
  • Loop: i from 1 to n.
  • Each pass: term = term * x, sign = -sign, then total = total + sign * term.

Python program

x = float(input("Enter x: "))
n = int(input("Enter n: "))
total = 1
term = 1
sign = 1
for i in range(1, n + 1):
    term = term * x
    sign = -sign
    total = total + sign * term
print(f"Sum = {total:.4f}")
C program
#include <stdio.h>
int main() {
    int n;
    double x;
    printf("Enter x: ");
    scanf("%lf", &x);
    printf("Enter n: ");
    scanf("%d", &n);
    double total = 1, term = 1;
    int sign = 1;
    for (int i = 1; i <= n; i++) {
        term = term * x;
        sign = -sign;
        total = total + sign * term;
    }
    printf("Sum = %.4f\n", total);
    return 0;
}
Java program
import java.util.Scanner;
public class Series {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter x: ");
        double x = sc.nextDouble();
        System.out.print("Enter n: ");
        int n = sc.nextInt();
        double total = 1, term = 1;
        int sign = 1;
        for (int i = 1; i <= n; i++) {
            term = term * x;
            sign = -sign;
            total = total + sign * term;
        }
        System.out.printf("Sum = %.4f%n", total);
    }
}

Sample output:

Enter x: 2
Enter n: 5
Sum = -21.0000

Dry run for x = 2 and n = 3:

iterm (x^i)signAdded to totaltotal
start11–1
12-1-2-1
24143
38-1-8-5

Quick check: for x ≠ -1 the sum must equal (1 − (−x)n+1) / (1 + x). For x = 2 and n = 5 that is (1 − 64) / 3 = -21, which matches the output above.

Series 3: x + x²/2 + x³/3 + … + xⁿ/n

Here the numerator is xi and the denominator is simply i. We keep a variable power that stores xi, and divide it by i only at the time of adding. Notice that the series starts from x itself, so the total starts from 0 and not from 1.

Logic:

  • Start: total = 0 and power = 1.
  • Loop: i from 1 to n.
  • Each pass: power = power * x, then total = total + power / i.

Python program

x = float(input("Enter x: "))
n = int(input("Enter n: "))
total = 0
power = 1
for i in range(1, n + 1):
    power = power * x
    total = total + power / i
print(f"Sum = {total:.4f}")
C program
#include <stdio.h>
int main() {
    int n;
    double x;
    printf("Enter x: ");
    scanf("%lf", &x);
    printf("Enter n: ");
    scanf("%d", &n);
    double total = 0, power = 1;
    for (int i = 1; i <= n; i++) {
        power = power * x;
        total = total + power / i;
    }
    printf("Sum = %.4f\n", total);
    return 0;
}
Java program
import java.util.Scanner;
public class Series {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter x: ");
        double x = sc.nextDouble();
        System.out.print("Enter n: ");
        int n = sc.nextInt();
        double total = 0, power = 1;
        for (int i = 1; i <= n; i++) {
            power = power * x;
            total = total + power / i;
        }
        System.out.printf("Sum = %.4f%n", total);
    }
}

Sample output:

Enter x: 2
Enter n: 5
Sum = 17.0667

Dry run for x = 2 and n = 3:

ipower (x^i)Added to total (power / i)total
start1–0
1222
2424
382.66676.6667

Did you know? When |x| is less than 1 and n becomes very large, this sum approaches −ln(1 − x). You can see this in the table at the end of this post.

Series 4: x + x²/2! + x³/3! + … + xⁿ/n!

This is the same idea as Series 3, but the denominator is the factorial i!. We keep two running variables: power for xi and fact for i!. Both are updated from their previous values, so we never need a separate factorial function. Like Series 3, the total starts from 0.

Logic:

  • Start: total = 0, power = 1 and fact = 1.
  • Loop: i from 1 to n.
  • Each pass: power = power * x, fact = fact * i, then total = total + power / fact.

Python program

x = float(input("Enter x: "))
n = int(input("Enter n: "))
total = 0
power = 1
fact = 1
for i in range(1, n + 1):
    power = power * x
    fact = fact * i
    total = total + power / fact
print(f"Sum = {total:.4f}")
C program
#include <stdio.h>
int main() {
    int n;
    double x;
    printf("Enter x: ");
    scanf("%lf", &x);
    printf("Enter n: ");
    scanf("%d", &n);
    double total = 0, power = 1, fact = 1;
    for (int i = 1; i <= n; i++) {
        power = power * x;
        fact = fact * i;
        total = total + power / fact;
    }
    printf("Sum = %.4f\n", total);
    return 0;
}
Java program
import java.util.Scanner;
public class Series {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter x: ");
        double x = sc.nextDouble();
        System.out.print("Enter n: ");
        int n = sc.nextInt();
        double total = 0, power = 1, fact = 1;
        for (int i = 1; i <= n; i++) {
            power = power * x;
            fact = fact * i;
            total = total + power / fact;
        }
        System.out.printf("Sum = %.4f%n", total);
    }
}

Sample output:

Enter x: 2
Enter n: 5
Sum = 6.2667

Dry run for x = 2 and n = 3:

ipower (x^i)fact (i!)Added to total (power / fact)total
start11–0
12122
24224
3861.33335.3333

Did you know? As n grows, this sum gets closer and closer to ex − 1. For x = 1 it approaches e − 1 = 1.7183. You can see this in the table at the end of this post.

One Program for All Four Series

Because all four series use the same powers of x, a single loop can calculate all four sums at once. This is a handy answer when the question asks you to print the sum of all the series in one program.

Python program

x = float(input("Enter x: "))
n = int(input("Enter n: "))
s1 = 1
s2 = 1
s3 = 0
s4 = 0
term = 1
sign = 1
fact = 1
for i in range(1, n + 1):
    term = term * x
    sign = -sign
    fact = fact * i
    s1 = s1 + term
    s2 = s2 + sign * term
    s3 = s3 + term / i
    s4 = s4 + term / fact
print(f"Series 1 sum = {s1:.4f}")
print(f"Series 2 sum = {s2:.4f}")
print(f"Series 3 sum = {s3:.4f}")
print(f"Series 4 sum = {s4:.4f}")
C program
#include <stdio.h>
int main() {
    int n, sign = 1;
    double x;
    printf("Enter x: ");
    scanf("%lf", &x);
    printf("Enter n: ");
    scanf("%d", &n);
    double s1 = 1, s2 = 1, s3 = 0, s4 = 0, term = 1, fact = 1;
    for (int i = 1; i <= n; i++) {
        term = term * x;
        sign = -sign;
        fact = fact * i;
        s1 = s1 + term;
        s2 = s2 + sign * term;
        s3 = s3 + term / i;
        s4 = s4 + term / fact;
    }
    printf("Series 1 sum = %.4f\n", s1);
    printf("Series 2 sum = %.4f\n", s2);
    printf("Series 3 sum = %.4f\n", s3);
    printf("Series 4 sum = %.4f\n", s4);
    return 0;
}
Java program
import java.util.Scanner;
public class Series {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter x: ");
        double x = sc.nextDouble();
        System.out.print("Enter n: ");
        int n = sc.nextInt();
        int sign = 1;
        double s1 = 1, s2 = 1, s3 = 0, s4 = 0, term = 1, fact = 1;
        for (int i = 1; i <= n; i++) {
            term = term * x;
            sign = -sign;
            fact = fact * i;
            s1 = s1 + term;
            s2 = s2 + sign * term;
            s3 = s3 + term / i;
            s4 = s4 + term / fact;
        }
        System.out.printf("Series 1 sum = %.4f%n", s1);
        System.out.printf("Series 2 sum = %.4f%n", s2);
        System.out.printf("Series 3 sum = %.4f%n", s3);
        System.out.printf("Series 4 sum = %.4f%n", s4);
    }
}

Sample output (x = 2, n = 5):

Enter x: 2
Enter n: 5
Series 1 sum = 63.0000
Series 2 sum = -21.0000
Series 3 sum = 17.0667
Series 4 sum = 6.2667

More sample runs:

xnSeries 1Series 2Series 3Series 4
2563.0000-21.000017.06676.2667
0.5101.99900.66700.69310.6487
145.00001.00002.08331.7083

Other Ways to Write the Program

Method 2: Using pow() and a factorial

You can also calculate xi and i! directly in every pass. In Python the power operator is ** and the factorial comes from the math module. This is shown for Series 4.

import math
x = float(input("Enter x: "))
n = int(input("Enter n: "))
total = 0
for i in range(1, n + 1):
    total = total + x ** i / math.factorial(i)
print(f"Sum = {total:.4f}")

In C use pow(x, i) from math.h, and in Java use Math.pow(x, i). The programs are shorter to explain, but the factorial grows very fast, so for a large n the number can become too big to store in an int or long.

Method 3: Optimised version of Series 4 (no factorial at all)

Notice that each term of Series 4 can be made from the previous term: the i-th term equals the previous term × x / i. So we can keep one variable term and never calculate a factorial.

x = float(input("Enter x: "))
n = int(input("Enter n: "))
total = 0
term = 1
for i in range(1, n + 1):
    term = term * x / i
    total = total + term
print(f"Sum = {total:.4f}")

This gives the same answer as the first method but is faster and does not overflow for large values of n.

What Happens When n Grows?

Series 3 and Series 4 are not just practice questions. They are the beginning of two famous infinite series. The more terms you add, the closer the sum gets to a fixed number.

Series 4 with x = 1 approaches e − 1 = 1.7183:

nSum
11.0000
21.5000
31.6667
51.7167
101.7183

Series 3 with x = 0.5 approaches −ln(1 − 0.5) = ln 2 = 0.6931:

nSum
10.5000
20.6250
50.6885
100.6931
200.6931

Common Mistakes

  1. Using ^ for power in C or Java. In these languages ^ is the XOR operator, not power. Use pow() / Math.pow(), or the term-update method used in this post.
  2. Integer division. If both numbers are int, 1 / 2 becomes 0. Declare total, power and fact as double so that power / i keeps its decimal part.
  3. Wrong starting value of the total. Series 1 and 2 begin with the constant 1, so the total starts at 1. Series 3 and 4 begin with x, so the total starts at 0.
  4. Starting the loop from 0. With i starting at 0 you add an extra term and, in Series 3, you divide by zero. Start from 1.
  5. Forgetting to flip the sign. In Series 2 the line sign = -sign must run in every pass, before the total is updated.
  6. Naming a variable sum in Python. sum is a built-in function. Use a name like total so that you do not hide it.

Practice Questions

  1. Print the sum of the series 1 + x²/2! + x⁴/4! + … up to n terms. Hint: the power of x increases by 2 each time, so multiply by x * x and divide by two new numbers.
  2. Print the sum of x − x³/3! + x⁵/5! − … up to n terms. Hint: combine the sign idea of Series 2 with a step of 2 in the power.
  3. Print the sum of 1 + 1/2 + 1/3 + … + 1/n.
  4. Print the sum of 1/1² + 1/2² + 1/3² + … + 1/n².
  5. Print the sum of the series 1 + (1+2) + (1+2+3) + … + (1+2+…+n).

Frequently Asked Questions

What is a series in programming?

A series is a list of terms that follow a rule and are added together. In a program we repeat the rule inside a loop and keep adding every new term to a variable called the total.

How do I find the next term of a series?

Look at how one term changes into the next one. In Series 1 the next term is the previous term multiplied by x. In Series 4 it is the previous term multiplied by x and divided by i.

Why do we update the term instead of calculating x to the power i every time?

Multiplying the previous term by x is a single step, while calculating a fresh power every time repeats a lot of work. It also avoids calling pow(), whose result is a double in C and Java.

Why does x^n give a wrong answer in C and Java?

Because ^ is the bitwise XOR operator in these languages. To calculate a power use pow() in C and Math.pow() in Java.

What is the difference between Series 3 and Series 4?

Series 3 divides xi by i, while Series 4 divides xi by i factorial. Because i! grows much faster than i, the terms of Series 4 become tiny very quickly.

What happens if n is 0?

The loop does not run at all, so the program prints the starting value of the total: 1 for Series 1 and 2, and 0 for Series 3 and 4.

What is the time complexity of these programs?

All of them have one loop that runs n times, so the time complexity is O(n) and they use only a few variables, so the extra space is O(1).

Can I use a while loop instead of a for loop?

Yes. Set i = 1 before the loop, run the loop while i is less than or equal to n, and increase i by 1 at the end of each pass.

Leave a Comment

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

Scroll to Top