Loops — Nested Loops
I. In-Class Exercises
Programming Exercises
Sample Code
1#include "CTurtle.hpp"
2#include <bits/stdc++.h>
3using namespace std;
4using namespace cturtle;
5
6int main() {
7 // Create a canvas screen
8 TurtleScreen scr;
9 // Create a drawing turtle
10 Turtle turtle(scr);
11
12 int sides = 4;
13 int sideLength = 20;
14 double angle = 360.0 / sides;
15
16 for (int i = 0; i < 5; ++i) {
17 for (int j = 0; j < 5; ++j) {
18 for (int k = 0; k < sides; ++k) {
19 turtle.forward(sideLength);
20 turtle.right(angle);
21 }
22 turtle.forward(sideLength);
23 }
24 turtle.right(angle);
25 turtle.forward(sideLength);
26 turtle.right(angle);
27 turtle.forward(sideLength * 5);
28 turtle.right(angle * 2);
29 }
30
31 // Pause the program
32 system("pause");
33 // End of program
34 return 0;
35}1#include <bits/stdc++.h>
2using namespace std;
3
4int main() {
5 int n;
6 cin >> n;
7 int sum = 0;
8 for (int i = 1; i <= n; ++i) {
9 for (int j = 1; j <= i; ++j) {
10 sum += j;
11 }
12 }
13 cout << sum << endl;
14 return 0;
15}1#include <bits/stdc++.h>
2using namespace std;
3
4int main() {
5 int a, b;
6 cin >> a >> b;
7 int count = 0;
8 for (int i = a; i <= b; ++i) {
9 bool flag = true;
10 for (int j = 2; j * j <= i; ++j) {
11 if (i % j == 0) {
12 flag = false;
13 break;
14 }
15 }
16 if (flag) {
17 ++count;
18 }
19 }
20 cout << count << endl;
21 return 0;
22}1#include <bits/stdc++.h>
2using namespace std;
3
4int main() {
5 int n;
6 cin >> n;
7 int count = 0;
8 for (int i = 1; i <= n; ++i) {
9 for (int j = 1; j <= i; ++j) {
10 cout << char(count + 'A');
11 count = (count + 1) % 26;
12 }
13 cout << endl;
14 }
15 return 0;
16}1#include <bits/stdc++.h>
2using namespace std;
3
4int main() {
5 int n;
6 cin >> n;
7 for (int i = 1; i <= n; ++i) {
8 int number;
9 cin >> number;
10 int number0 = number;
11 int count = 0;
12 while (number) {
13 ++count;
14 number /= 10;
15 }
16 number = number0;
17 int sum = 0;
18 for (int j = 1; j <= count; ++j) {
19 int now = number % 10;
20 number /= 10;
21 int result = 1;
22 for (int k = 1; k <= count; ++k) {
23 result *= now;
24 }
25 sum += result;
26 }
27 if (sum == number0) {
28 cout << "T" << endl;
29 } else {
30 cout << "F" << endl;
31 }
32 }
33 return 0;
34}II. Knowledge Summary
✨ What are Nested Loops
Nested loops are structures where one loop is placed inside another. Each time the outer loop executes once, the inner loop completes a full cycle.
Real-life analogies:
- A building has 5 floors (outer loop), each floor has 4 classrooms (inner loop) — inspecting each room requires nested loops
- A clock's minute hand completes one rotation (outer), while the second hand completes 60 rotations (inner)
Syntax
for (int i = 0; i < outer_count; ++i) { // Outer loop
for (int j = 0; j < inner_count; ++j) { // Inner loop
// Loop body
}
}Execution Process
The execution process of nested loops:
- Outer loop variable
iis initialized - Check the outer condition; if true, enter the inner loop
- Inner loop variable
jis initialized; inner loop completes a full cycle - After the inner loop ends, update outer variable
i, go back to step 2 - When the outer condition is false, the entire nested loop ends
If the outer loop executes m times and the inner loop executes n times, the loop body executes a total of m × n times.
Nested Loop Flowchart
✨ Comprehensive Example: Multiplication Table
The outer loop controls rows (i from 1 to 9), the inner loop controls columns per row (j from 1 to i), with a newline after each row.
1for (int i = 1; i <= 9; ++i) { // Outer: control rows
2 for (int j = 1; j <= i; ++j) { // Inner: control columns
3 cout << j << "*" << i << "=" << i * j << "\t";
4 }
5 cout << endl; // Newline after each row
6}Output (first 3 rows):
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9✨ Comprehensive Example: Right Triangle Pattern
Input n, print a right triangle of n rows made of asterisks. Row i has i asterisks.
1int n;
2cin >> n;
3for (int i = 1; i <= n; ++i) { // Outer: control rows
4 for (int j = 1; j <= i; ++j) { // Inner: control asterisks per row
5 cout << "*";
6 }
7 cout << endl;
8}When n=4, output:
*
**
***
****✨ Notes
Keep the following points in mind when using nested loops:
- Inner and outer loops should not use the same loop variable name (e.g., both using
i), as this causes variable shadowing - Ensure each loop's condition can properly terminate, avoiding infinite loops
- Always use curly braces
{}to keep the code structure clear
✨ break and continue in Nested Loops
In nested loops, break and continue only affect the loop they are in, not the outer loop.
1for (int i = 1; i <= 3; ++i) {
2 for (int j = 1; j <= 5; ++j) {
3 if (j == 3) {
4 break; // Only terminates inner loop; outer continues
5 }
6 cout << i << "," << j << " ";
7 }
8 cout << endl;
9}Output:
1,1 1,2
2,1 2,2
3,1 3,2Each time the inner loop reaches j==3, break terminates it, but the outer loop continues, producing 3 rows.
1for (int i = 1; i <= 3; ++i) {
2 for (int j = 1; j <= 4; ++j) {
3 if (j == 2) {
4 continue; // Skip j==2, continue to next inner iteration
5 }
6 cout << i << "," << j << " ";
7 }
8 cout << endl;
9}Output:
1,1 1,3 1,4
2,1 2,3 2,4
3,1 3,3 3,4Each row skips the output for j==2, but the inner loop continues with j==3 and j==4.
III. Homework
Programming Exercises
- Letter Triangle: L1145
- Sum of Factorials: L1146
- Number Search Game: L1147
- Xiao Yang's X Matrix: L1148