Chapter 2
HomeNow 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.
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.
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.
whileint i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
whilelet 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.
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.
// 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";
}
// 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);
}
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.
Input: first line is N, second line has N integers. Output: their sum.
Sample input: 5 4 7 1 9 3 Expected output: 24
#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;
}
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);
}
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.
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
#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;
}
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.
while loops repeat while a condition is true. for loops package initialization, condition, and increment.
for (int i = 0; i < n; i++) in C++, 0..n in Rust.
0..n is exclusive (0 to n-1), 0..=n is inclusive.