All lessons
LESSON 17/53Repeating Things
Putting It Together
GOALUse input, a loop and a condition in one program.

You now know enough to solve a real task. This program reads N numbers and adds up only the even ones.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int sum = 0;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
if (x % 2 == 0) {
sum = sum + x;
}
}
cout << "Even sum = " << sum << endl;
return 0;
}> what you see
(input: 5\n1 2 3 4 6) Even sum = 12
//LINE BY LINE
Watch it run
Before the loop, sum = 0 and five numbers are waiting to be read.
How to start a problem
Staring at a new problem and not knowing where to begin is normal. This order almost always works.
- 1.Write down the input and output. What comes in? What must go out?
- 2.Work one example by hand. On paper, without a computer.
- 3.Write the steps in plain words. Not code — words.
- 4.Turn each step into code. One at a time.
- 5.Test it. Smallest case, largest case, zero, negatives.
When it does not work
- Print your variables:
cout << "i=" << i << endl;— see what is actually happening. - Fix only the compiler's first error. The rest are usually knock-on effects.
- Look one line above where it complains — that is where the semicolon is missing.
- If the answer is close but wrong, check your loop bounds (
<versus<=).