Beginner · loops + accumulator
Sum from 1 to N
Read n and print 1 + 2 + … + n. The accumulator pattern in its purest form — and a chance to meet Gauss's shortcut.
Problem
Input: one integer n (1 ≤ n ≤ 10,000).
Output: a single line with the sum of all integers from 1 to n.
Sample:
| Input | Output |
|---|---|
5 | 15 |
Your solution
Custom input for "Run my input"
Judging runs entirely in your browser. Your code is saved locally as you type.
Stuck? Hints
Hint 1 — the accumulator
Declare int sum = 0; before the loop. Each pass does sum += i; — that's the pattern you'll reuse in every aggregation you ever write.
Hint 2 — or skip the loop entirely
Gauss: the sum of 1..n is n * (n + 1) / 2. Try proving to yourself why n * (n + 1) is always even.
Solution (try first!)
int n = int.Parse(Console.ReadLine());
int sum = 0;
for (int i = 1; i <= n; i++)
{
sum += i;
}
Console.WriteLine(sum);
// Gauss's formula — O(1), no loop
int n = int.Parse(Console.ReadLine());
Console.WriteLine(n * (n + 1) / 2);
Watch the integer division in the formula version: n * (n + 1) / 2 divides the product, which is always even — so no fraction is ever lost. Next up: Maximum of Three.