Skip to main content

Conditional statements

If / else if / else

Ternary operator

A shorthand for simple if/else:

Switch statement

Useful when comparing one variable against multiple values:

Loops

For loop

While loop

Do-while loop

Executes at least once:

Nested loops

Essential for 2D problems, pattern printing, and brute force:

Pattern example: right triangle

Break and continue

Common patterns with conditions and loops

Check if a number is prime

Sum of digits

GCD (Euclidean algorithm)

Most brute-force solutions use nested loops. If the constraints are small (n ≤ 1000), an O(n²) solution with nested loops will work. If n ≤ 10⁷, you need O(n) or O(n log n).

Practice

Sheet 2: Conditions and Loops

Practice problems for this tutorial.