-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path89_nested_loops.txt
More file actions
75 lines (47 loc) · 1.35 KB
/
89_nested_loops.txt
File metadata and controls
75 lines (47 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
Section 09: Nested Loops
----------------------------------------------------------------------------------------
Nested Loops
- Loop nested within another loop
- Can be as many levels deep as the program needs
- Very useful with multi-dimensional data structures
- Outer loop vs Inner loop
Example 1
for (outer_val {1}; outer_val <= 2; ++ outer_val)
for (inner_val {1}; inner_val <= 3; ++inner_val)
cout << outer_val << ", " << inner_val << endl;
Note: inner loop loops "faster"
Example 2 - Multiplication Table
for (int num1 {1}; num1 <= 10; ++num1) {
for (int num2; num2 <= 10; ++num2) {
cout << num1 << " * " << num2
<< " = " << num1 * num2 << endl;
}
cout << "--------------------" << endl;
}
Displays 10 x 10 Multiplication Table
Example 3 - 2D Arrays - Set all Elements to 1000
int grid[5][3] {};
for (int row {0}; row < 5; ++row) {
for (int col {0}; col < 3; ++col) {
grid[row][col] = 1000;
}
}
Example 4 - 2D Arrays - Display Elements
for (int row {0}; row < 5; ++row) {
for (int col {0}; col < 3; ++col) {
cout << grid[row][col] << " ";
}
cout << endl;
}
Example 5 - 2D Vector - Display Elements
vector<vector<int>> vector_2d {
{1, 2, 3},
{10, 20, 30, 40},
{100, 200, 300, 400, 500}
};
for (auto vec: vector_2d) {
for (auto val: vec) {
cout << val << " ";
}
cout << endl;
}