Sum of Series

Compute the sum of the series 1 + 2 + ... + n using a loop.

BeginnerTopic: Module 3: Loop Programs
Back

Java Sum of Series Program

This program helps you to learn the fundamental structure and syntax of Java programming.

Try This Code
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter n: ");
        int n = sc.nextInt();

        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        System.out.println("Sum = " + sum);
        sc.close();
    }
}
Output
Enter n: 5
Sum = 15

Understanding Sum of Series

We accumulate sum in a loop; this is the iterative version of the formula-based sum.

Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.

Table of Contents