Sum of Series in Java

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

BeginnerModule 3: Loop ProgramsExample 14 of 25
sum-of-series.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Enter n: ");
7 int n = sc.nextInt();
8
9 int sum = 0;
10 for (int i = 1; i <= n; i++) {
11 sum += i;
12 }
13 System.out.println("Sum = " + sum);
14 sc.close();
15 }
16}

Output

Enter n: 5
Sum = 15

What's going on

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