Beginner · loops
Sum from 1 to N
Read an integer N and print 1 + 2 + … + N. The classic first for loop — with a math shortcut hiding inside for later.
At a glanceAdd 1 through N with a for-loop and an accumulator; the closed form N(N+1)/2 gives the same answer in one step, and at N ≤ 10,000 the sum still fits in int.
Problem
Input: one integer N (1 ≤ N ≤ 10,000).
Output: the sum 1 + 2 + … + N.
Sample:
| Input | Output |
|---|---|
5 | 15 (1+2+3+4+5) |
Your solution
Custom input for "Run my input"
Judging runs in your browser against hidden tests. A runaway loop is cut off after 3 seconds — still, make sure every loop has an exit. Your code is saved in this browser as you type.
Stuck? Hints
Hint 1 — the accumulator pattern
You need a variable that starts at 0 and grows: int sum = 0; then inside the loop sum += i;. This "accumulator" pattern appears in half of all beginner problems.
Hint 2 — the loop bounds
for (int i = 1; i <= n; i++) — start at 1 (not 0: it adds nothing), end at <= n (N itself is included). Boundary checks like this are exactly what the judge tests.
Solution (try it first!)
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
cout << sum << endl;
return 0;
}
Loop solved it in N steps. The famous shortcut: n * (n + 1) / 2 gives the same answer in one step (Gauss, age 9). Note the division there is exact — see integer division for why that matters. Next: Maximum of Three.
Deep dive
Why this works
An accumulator (total += i) is the most reused loop shape in existence. The only real question per problem is what goes on the right-hand side.
The cost
O(n) with the loop; O(1) with Gauss's n(n+1)/2. For n = 10,000 that is 10,000 additions versus three arithmetic operations.
Where it goes wrong
n * (n + 1) / 2overflows int around n = 65,000. Divide by 2 first, or uselong long.- Starting the loop at
i = 0is harmless for a sum but silently wrong for a product — match the problem's range exactly, every time.
Next step
Multiply instead of add: Factorial.
Two things to remember
- Accumulator pattern: initialise, loop, fold in, return.
- n(n+1)/2 turns O(n) into O(1) — closed forms beat loops.
🐞 This version fails — open it and try
i < n drops the last term
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int total = 0;
for (int i = 1; i < n; i++) total += i;
cout << total << endl;
return 0;
}