Loops & Direct Simulations
Master the three loop structures in C++, loop controls, nested loops, and core loop patterns for competitive programming.
Loops & Direct Simulations
Loops are how you tell the computer to repeat work. In competitive programming, the simplest approach to many problems is a direct simulation — just code exactly what the problem describes, step by step, using loops.
The Three Loop Structures
for Loop
Use when you know the number of iterations in advance:
for (int i = 0; i < n; i++) {
// runs n times: i = 0, 1, 2, ..., n-1
}
The for loop has three parts: initialization, condition, and update — all in one line. This makes it the most common loop in competitive programming.
while Loop
Use when the number of iterations depends on a condition:
int x = 100;
while (x > 0) {
x /= 2; // halve x until it reaches 0
}
do-while Loop
Runs at least once, then checks the condition:
int n;
do {
cin >> n;
} while (n <= 0); // keeps asking until n is positive
Loop Controls: break & continue
break
Exits the loop immediately:
for (int i = 0; i < n; i++) {
if (a[i] == target) {
cout << "Found at index " << i << "\n";
break; // stop searching
}
}
continue
Skips the rest of the current iteration and jumps to the next one:
for (int i = 0; i < n; i++) {
if (a[i] % 2 == 0) continue; // skip even numbers
cout << a[i] << " "; // prints only odd numbers
}
Nested Loops
When you need to iterate over combinations or 2D structures:
// Print all pairs (i, j) where i < j
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
cout << a[i] << " " << a[j] << "\n";
}
}
Complexity warning: Nested loops multiply their complexities. Two loops of n iterations each give O(n²). Three give O(n³). Always check whether the total work fits within the time limit (typically ~10⁸ operations per second).
Core Loop Patterns
Counting
int count = 0;
for (int i = 0; i < n; i++) {
if (a[i] > 0) count++;
}
Accumulation
long long sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i];
}
Finding Minimum/Maximum
int mn = a[0];
for (int i = 1; i < n; i++) {
if (a[i] < mn) mn = a[i];
}
Linear Search
int idx = -1;
for (int i = 0; i < n; i++) {
if (a[i] == target) {
idx = i;
break;
}
}
Simulation
Many problems just ask you to simulate a process:
// Problem: Given n, repeatedly divide by 2 until odd. Count steps.
int steps = 0;
while (n % 2 == 0) {
n /= 2;
steps++;
}
cout << steps << "\n";
Summary
- Prefer
forwhen the iteration count is known - Prefer
whilewhen the termination depends on a condition breakexits the loop;continueskips to the next iteration- Nested loops multiply complexities — O(n²) for two levels, O(n³) for three
- Direct simulation: code exactly what the problem says, step by step
Prefer reading offline? Download the full book as a PDF.
Download Free Book