Loops
The for and while loops: repeating actions, counters and accumulating a result.
Loops let you repeat actions many times. Contest problems almost always require iterating over numbers, array elements or the characters of a string — all of that is done with loops.
A for loop has three parts: start; continuation condition; step. The classic form is a counter from 1 to n.
C++
A counter from 1 to 5
The most common loop technique is accumulation: create an accumulator variable (a sum, a product, a counter) and update it on every step.
The program below reads n, then n numbers, and computes their sum. Note that the sum is declared as long long — with many large numbers an int would overflow.
C++
Enter: 4, then 10 20 30 40
The second kind of loop is while: it repeats as long as the condition is true, and is handy when the number of steps is not known in advance.
C++
How many times is the number divisible by 2? Enter, for example: 96
Task: print all even numbers from 2 to 20 on one line separated by spaces.
Then solve the attached problems "Factorial" (accumulating a product) and "Sum of Array Elements" (accumulating a sum) — and mark the lesson as completed.