Chapter 2

Home

Your First Loop

Now that you can read input and write output, the next step is repetition. Loops let you process many numbers, run a calculation multiple times, and accumulate results. They're the engine of every algorithm.

Why Loops?

In competitive programming you're rarely processing just one thing. You might need to sum 1000 numbers, count how many are even, or keep reading until input ends. Without loops, you'd have to copy-paste the same line a thousand times.

Without a loop total = a1 + a2 + a3 + a4 ... total += a1000 ✗ 1000 lines of adding With a loop for each number:     total += number ✓ 3 lines, any size

The while Loop

A while loop keeps running as long as a condition is true. It's the simplest kind of loop — you check a condition, run the body, check again.

C++ — while

int i = 0;
while (i < 5) {
    cout << i << "\n";
    i++;
}

Rust — while

let mut i = 0;
while i < 5 {
    println!("{}", i);
    i += 1;
}

⚠️ Infinite loop

If the condition never becomes false, the loop runs forever. Always make sure something in the body changes the condition. Missing i += 1 is the most common beginner infinite-loop bug.

The for Loop

A for loop bundles three things into one line: a starting value, a condition to keep going, and what to do after each iteration. It's the most common loop in competitive programming.

C++

// i goes 0, 1, 2, 3, 4
for (int i = 0; i < 5; i++) {
    cout << i << "\n";
}

// i goes 1 through 10
for (int i = 1; i <= 10; i++) {
    cout << i << "\n";
}

Rust

// 0..5 is exclusive (0, 1, 2, 3, 4)
for i in 0..5 {
    println!("{}", i);
}

// 1..=10 is inclusive (1 through 10)
for i in 1..=10 {
    println!("{}", i);
}

Pattern: Summing Numbers

This is the first algorithmic pattern you should memorize. You have an accumulator (a variable that starts at 0), and you add each number to it.

Problem: Sum of N numbers

Input: first line is N, second line has N integers. Output: their sum.

Sample input:
5
4 7 1 9 3

Expected output:
24

C++

#include <bits/stdc++.h>
using namespace std;
int main() {
    int n; cin >> n;
    int total = 0;
    for (int i = 0; i < n; i++) {
        int x; cin >> x;
        total += x;
    }
    cout << total << "\n";
    return 0;
}

Rust

use std::io::{self, Read};
fn main() {
    let mut input = String::new();
    io::stdin().lock().read_to_string(&mut input).unwrap();
    let nums: Vec<i64> = input
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();
    let n = nums[0] as usize;
    let total: i64 = nums[1..=n].iter().sum();
    println!("{}", total);
}

Pattern: Counting

Instead of summing values, you count how many items have a certain property. The pattern is the same — an accumulator, a loop, and a condition.

Problem: Count evens

Input: first line is N, second line has N integers. Output: how many are even.

Sample input:
6
2 5 8 11 14 17

Expected output:
3

C++

#include <bits/stdc++.h>
using namespace std;
int main() {
    int n; cin >> n;
    int count = 0;
    for (int i = 0; i < n; i++) {
        int x; cin >> x;
        if (x % 2 == 0) count++;
    }
    cout << count << "\n";
    return 0;
}

Rust

use std::io::{self, Read};
fn main() {
    let mut input = String::new();
    io::stdin().lock().read_to_string(&mut input).unwrap();
    let nums: Vec<i64> = input
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();
    let n = nums[0] as usize;
    let count = nums[1..=n].iter().filter(|&x| x % 2 == 0).count();
    println!("{}", count);
}

💡 The modulo operator %

x % 2 == 0 checks if a number is even. It returns the remainder after dividing by 2. If the remainder is 0, the number divides evenly — it's even.

Key Takeaways

Practice