CS102Unit11_NestedLoops
CS102Unit11_NestedLoops
Unit 11
Nested Loops
2
False init
condition False
condition
True What code can we put True
while Block in the body of a For Block
loop?
Statements Statements
Following Update
statements
Following
3
Nested Loops
• Loops can contain other loops in their body
False
cond1
while (cond1) { True
// code1
while(cond2) {
code1
// code 2 False
} cond2
// code3
}
True
code2
code3
Following
statements
4
Cond1: T T F False
cond1
while (cond1) { 1 9 15
// code1 2 10 True
Cond2: T T F
while(cond2) { 3 5 7 11 13 code1
Cond2: T F // code 2 12
4 6 False
}
// code3 8 14 cond2
} True
16 code2
code3
Following
statements
5
1 game
(and we repeat that {
1 turn
cout << "Enter guess: ";
over and over) cin >> guess;
}
– The body of the inner cout << "Win!" << endl;
cout << "Play again (y/n): ";
loop represents 1 turn cin >> again;
(and we repeat turn }
return 0;
after turn) }
6
Program Output:
8
Tips
• Nested loops often help us represent and
process multi-dimensional data
– 2 loops allow us to process data that corresponds
to 2 dimension (i.e. rows/columns)
– 3 loops allow us to process data that corresponds
to 3 dimensions (i.e. rows/columns/planes)
10
More Practice
• cpp/nestedloops/rectangle
• cpp/nestedloops/flag
• cpp/nestedloops/etox-range
• cpp/nestedloops/sphere
11
SOLUTIONS
12
i j
0 0
1
Program Output: 2
1 0
0 0
0 1
1
0 2 2
1 0
1 1
1 2
13
Program Output:
8 6 4 2 0
4 2 0
Done