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.
n = int(input())total = 0for i in range(1, n + 1): print(i) total += iprint(total)const n = Number(require("fs").readFileSync(0, "utf8"));let total = 0;for (let i = 1; i <= n; i++) { console.log(i); total += i;}console.log(total);import { readFileSync } from "node:fs";const n: number = Number(readFileSync(0, "utf8"));let total: number = 0;for (let i = 1; i <= n; i++) { console.log(i); total += i;}console.log(total);import java.util.Scanner; public class Main { public static void main(String[] args) { int n = new Scanner(System.in).nextInt(); int total = 0; for (int i = 1; i <= n; i++) { System.out.println(i); total += i; } System.out.println(total); }}using System; class Program{ static void Main() { int n = int.Parse(Console.ReadLine()); int total = 0; for (int i = 1; i <= n; i++) { Console.WriteLine(i); total += i; } Console.WriteLine(total); }}#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';}#include <stdio.h> int main(void) { int n, total = 0; scanf("%d", &n); for (int i = 1; i <= n; i++) { printf("%d\n", i); total += i; } printf("%d\n", total); return 0;}n = Console.ReadLine().ToNumber();total = 0;for (i = 1; i <= n; i++){ Console.WriteLine(i); total += i;}Console.WriteLine(total);5
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.
breakleaves the loop andcontinueskips the rest of this lap.
Both affect only the innermost loop, so to leave a nested loop at once, use a flag variable orreturnfrom a function.
How each language writes it
| Python | for 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 |
|---|---|
| JavaScript | for (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; |
| TypeScript | Same as JavaScript |
| Java | for (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 |
| C | for (int i = 1; i <= n; i++) — there is no for-each form, so loop over indexes.while, do { } while |
| Craykon | for (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
In the C family and Craykon, double-check
Being off by one is the most common way a loop gets the wrong answer.
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.