Skip to main content

Conditional statements

If / else if / else

int x;
cin >> x;

if (x > 0) {
    cout << "Positive";
} else if (x < 0) {
    cout << "Negative";
} else {
    cout << "Zero";
}

Ternary operator

A shorthand for simple if/else:
int a = 5, b = 3;
int mx = (a > b) ? a : b;  // mx = 5

Switch statement

Useful when comparing one variable against multiple values:
char grade;
cin >> grade;

switch (grade) {
    case 'A': cout << "Excellent"; break;
    case 'B': cout << "Good"; break;
    case 'C': cout << "Average"; break;
    default: cout << "Below average";
}

Loops

For loop

// Print 1 to n
for (int i = 1; i <= n; i++) {
    cout << i << " ";
}

// Print n to 1
for (int i = n; i >= 1; i--) {
    cout << i << " ";
}

// Step by 2
for (int i = 0; i < n; i += 2) {
    cout << i << " ";
}

While loop

// Read until end of input
int x;
while (cin >> x) {
    cout << x * 2 << "\n";
}

// Count digits
int n = 12345, digits = 0;
while (n > 0) {
    digits++;
    n /= 10;
}

Do-while loop

Executes at least once:
int n;
do {
    cin >> n;
} while (n <= 0); // Keep reading until positive

Nested loops

Essential for 2D problems, pattern printing, and brute force:
// Print a multiplication table
for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
        cout << i * j << "\t";
    }
    cout << "\n";
}

Pattern example: right triangle

// *
// **
// ***
// ****
for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= i; j++) {
        cout << "*";
    }
    cout << "\n";
}

Break and continue

// Break: exit the loop early
for (int i = 1; i <= 100; i++) {
    if (i * i > n) break;
    cout << i << " ";
}

// Continue: skip to next iteration
for (int i = 1; i <= n; i++) {
    if (i % 3 == 0) continue; // Skip multiples of 3
    cout << i << " ";
}

Common patterns with conditions and loops

Check if a number is prime

bool isPrime(int n) {
    if (n < 2) return false;
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) return false;
    }
    return true;
}

Sum of digits

int sumDigits(int n) {
    int sum = 0;
    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

GCD (Euclidean algorithm)

int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}
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.