C++ Fundamentals

Lesson 03 · 14 min

if / for / while — Control Flow

Loops, early returns, and the patterns you reuse in every DSA solution.

Control flow for problem solving

Early return mindset

In interviews, once you know the answer, return immediately. Don't keep scanning for fun.

for (int i = 0; i < n; i++) {
    if (found) return answer;
}

for-loop forms

for (int i = 0; i < n; i++) { /* index */ }
for (int x : nums) { /* value only */ }
for (int i = n - 1; i >= 0; i--) { /* reverse */ }

while for two pointers / windows

int L = 0;
for (int R = 0; R < n; R++) {
    // expand with R
    while (/* window invalid */) {
        // shrink from L
        L++;
    }
}

This for R + while L shape is sliding window. You'll live here later.

switch

Rare in DSA. Prefer if/else for clarity.

Rules to remember

  • Index loops: i from 0 to n-1 unless problem says 1-based.
  • Prefer range-for when you don't need the index.
  • Sliding window = expand right, shrink left while invalid.
  • Infinite loops need a clear exit — always change L/R or break.

Check yourself

1. Classic sliding-window skeleton uses:

Practice what you learned