Nested Loops
Part of the Fundamentals section of Coddy's C++ journey — lesson 48 of 74.
A nested loop is simply a loop inside another loop. The inner loop will complete all its iterations for each single iteration of the outer loop.
A good analogy for this is a clock: for each hour (outer loop), the minute hand (inner loop) must complete its full 60-minute cycle.
Example of a nested loop:
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 2; y++) {
std::cout << x << " " << y << std::endl;
}
}
// This will output:
// 0 0
// 0 1
// 1 0
// 1 1The outer loop (x) runs twice, and for each of those times, the inner loop (y) runs twice.
Challenge
BeginnerWrite a program that finds all pairs of numbers that add up to n using numbers from 1 to n - 1.
The program should show all possible combinations, including duplicate pairs in reverse order. For example, both "1 5" and "5 1" should be shown, as they are considered different arrangements of the same pair. Numbers can also be paired with themselves if their sum equals n.
For example if n = 6, the output should be:
1 5
2 4
3 3
4 2
5 1Because:
1 + 5 = 6
2 + 4 = 6
3 + 3 = 6
4 + 2 = 6
5 + 1 = 6Cheat sheet
A nested loop is a loop inside another loop. The inner loop completes all its iterations for each single iteration of the outer loop.
Basic nested loop structure:
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 2; y++) {
std::cout << x << " " << y << std::endl;
}
}
// Output:
// 0 0
// 0 1
// 1 0
// 1 1The outer loop runs completely, and for each iteration of the outer loop, the inner loop runs through all its iterations.
Try it yourself
#include <iostream>
int main() {
int n;
std::cin >> n;
// Write your code below
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - Else