← Back to C++ Course | Chapter 4: Control Flow | Lesson 11 of 13

C++ for Loop

Introduction to For Loops

A for loop packs initialization, a condition, and an update step into one line — for (int i = 0; i < 10; i++) — making it the natural choice whenever you already know exactly how many times you need to repeat something. Compared to a while loop, keeping all three parts together makes the loop's start, stop, and progress conditions easy to see at a glance.

Example: Introduction to For Loops

cpp
#include <iostream>

int main() {
	for (int i = 0; i < 10; i++) {
		std::cout << i << " ";
	}
	std::cout << std::endl;
	return 0;
}

Loop Steps

The update step isn't limited to simple +1 increments — you can add any amount, multiply, or divide the counter each pass, which changes the loop from stepping linearly to stepping geometrically. This is exactly how algorithms that repeatedly halve or double a value, like binary search, structure their loop.

Example: Loop Steps

cpp
#include <iostream>

int main() {
	for (int i = 0; i < 20; i += 5) {
		std::cout << i << " ";
	}
	std::cout << std::endl;
	return 0;
}

Nested For Loops

Placing one for loop inside another lets the inner loop run to completion once for every single iteration of the outer loop, which is exactly the pattern behind processing a 2D grid — the outer loop walks rows while the inner loop walks columns within each row. The total number of iterations is the product of both loops' counts.

Example: Nested For Loops

cpp
#include <iostream>

int main() {
	for (int i = 1; i <= 2; i++) {
		for (int j = 1; j <= 2; j++) {
			std::cout << i << "," << j << " ";
		}
	}
	std::cout << std::endl;
	return 0;
}

Looping Over Arrays

Using a for loop's counter as an array index, like for (int i = 0; i < size; i++) cout << arr[i];, is one of the most common patterns in C++ for visiting every element in sequence. It gives you the index itself if you need it, unlike some alternatives that only give you the value.

Example: Looping Over Arrays

cpp
#include <iostream>

int main() {
	int arr[] = {10, 20, 30};
	int size = 3;
	for (int i = 0; i < size; i++) {
		std::cout << arr[i] << " ";
	}
	std::cout << std::endl;
	return 0;
}

Range-based For Loop

A range-based for loop, written for (int x : arr), iterates directly over each element's value without you managing an index at all, which removes an entire category of off-by-one bugs. It's the preferred style in modern C++ whenever you don't actually need the index, only the values themselves.

Example: Range-based For Loop

cpp
#include <iostream>

int main() {
	int arr[] = {10, 20, 30};
	for (int x : arr) {
		std::cout << x << " ";
	}
	std::cout << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.