Add up the even numbers up to n.
What to build
A loop with a decision inside it.
Requirements
- Read
n. - Print the sum of the even numbers from 1 to
n.
Input
One whole number n.
Output
One number.
Constraints
n is from 1 to 100000. The sum can be larger than an int can hold.
Example
Input:
6
Output:
12
Why it works
A loop visits each number once, and the condition picks out those that count. A long long total has room for the largest answer.
Examples
Example 1 · Input
6
Expected output
12
Example 2 · Input
1
Expected output
0
Hints
Hint 1
Loop from 1 to n.
Hint 2
i % 2 == 0 tests for an even number.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
long long sum = 0;
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
sum += i;
}
}
cout << sum << endl;
return 0;
}