Sum of Series in Java
Add the series 1 through n in Java with sum += i inside a for loop. Scanner sets the limit; non-positive n prints zero, and large totals may overflow int.
1import java.util.Scanner;23public 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();89 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}
Sample Output
Enter n: 5 Sum = 15
sum is 0 initially, then 1, 3, 6, 10, 15. The final print displays only 15.
In this one
- Build a running sum
- Use += for accumulation
- Compare a loop with a direct formula
How it works
- 1
Read n.
- 2
Set sum to zero.
- 3
Visit i = 1 through n, adding i each time.
- 4
Print the accumulated sum.
Edge cases
Zero terms
Enter 0
The loop is skipped and the total remains 0.
Negative limit
Enter -3
The current code also prints 0. If only natural-number counts are allowed, reject negative n.
What's going on
Add the series 1 + 2 + 3 up to a chosen n using a loop. This is the repeated-addition version of the natural-number sum formula. It is useful when you want to watch a total grow or later change which terms are included.
Scanner is the keyboard reader. sum starts at zero. On each pass, i is added to the current sum using sum += i. That is a short form of sum = sum + i. The loop includes n because its condition is i <= n.
For n = 5, the totals become 1, 3, 6, 10, and 15. The answer is not just the final value of i; it is the saved total across all passes. Non-positive n runs no passes in this version. Very large totals may exceed int, so choose a larger type and input limits if you extend the exercise.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is the total after adding 1, 2, and 3?
Pick an answer to check it.
Question 2
What starting sum leaves addition unchanged?
Pick an answer to check it.
Questions people ask
Why not set sum = i each time?
That replaces the old total. += keeps the previous sum and adds the next term.
Does this include n?
Yes. The condition uses <= n.
Could I use n * (n + 1) / 2?
Yes for this exact series. A loop is easier to adapt when the terms follow a different rule.