{ }codelper

Learn › C++

Control flow · 06

Loops

Do the same thing many times: for and while.

A loop runs the same code many times.
The example below prints the numbers from 1 to n one by one, adds them up, and prints the total at the end.

#include <iostream> int main() {    int n, total = 0;    std::cin >> n;    for (int i = 1; i <= n; i++) {        std::cout << i << '\n';        total += i;    }    std::cout << total << '\n';}
stdin
5
stdout
1
2
3
4
5
15

Key points

  • The most common shape is "from 1 to n".
    You choose a start value, a condition to keep going, and how much changes each lap.
  • Accumulating a value as you go (total += i) is the basis of sum, count and maximum problems.
  • To walk through a list or string item by item, there is a shorter form that hands you each value directly, with no index.
  • A while loop looks only at a condition and keeps going as long as it is true.
  • break leaves the loop and continue skips the rest of this lap.
    Both affect only the innermost loop, so to leave a nested loop at once, use a flag variable or return from a function.

How each language writes it

Pythonfor i in range(1, n + 1): — the end value of range is not included.
Step: range(10, 0, -2); each item: for x in nums:; condition: while cond:.
There is no do-while
JavaScriptfor (let i = 1; i <= n; i++), step with i -= 2.
Each item: for (const x of nums).
while (cond) { }, do { } while (cond);.
To leave an outer loop, use a label: break outer;
TypeScriptSame as JavaScript
Javafor (int i = 1; i <= n; i++), each item: for (int x : nums).
while, do { } while.
Labels (break outer;) work too
C#for (int i = 1; i <= n; i++), each item: foreach (var x in nums).
while, do { } while
C++for (int i = 1; i <= n; i++), each item: for (int x : nums).
while, do { } while
Cfor (int i = 1; i <= n; i++) — there is no for-each form, so loop over indexes.
while, do { } while
Craykonfor (i = 1; i <= n; i++), each item: foreach (x in nums), condition: while (cond) { }.
Leave with break, skip with continue.
There is no do-while.
In a scene (animation) while pauses one frame per lap, but in console solutions it runs without pausing

Common mistakes

A while loop that never changes its condition

i = 1
while i <= 5:
    print(i)

→ It never ends, printing 1 forever

Put the line that changes the condition (i += 1, i++) in the body.

Using i after the loopJava · C# · C · C++ · JavaScript · TypeScript · Craykon

for (int i = 0; i < 3; i++) { }
printf("%d\n", i);

→ An error — an i created in the for exists only inside the loop

If you need it afterwards, create it before the loop.
Python's i stays around with its last value.

Looping over values with for … inJavaScript · TypeScript

const nums = [10, 20];
for (const x in nums) console.log(x);

→ 0, 1 — the indexes, not the values (and as strings "0", "1")

Loop over values with for (const x of nums).

How languages differ
Python's range(a, b) does not include b, so 1 to n is range(1, n + 1).
In the C family and Craykon, double-check i <= n versus i < n.
Being off by one is the most common way a loop gets the wrong answer.

Practice