COMP1117B Tutorial 5: Loops
COMP1117B Tutorial 5: Loops
COMP1117B Tutorial 5
LOOPS
2
About this tutorial
Break statement:
The break statement terminates the
loop containing it.
Output
4
Break and continue
Continue statement:
The continue statement is used to skip
the rest of the code inside a loop for
the current iteration only.
Loop does not terminate but continues
on with the next iteration.
Output
5
Q1
A. 12
B. 9
C. 7
D. 8
8
Q2 Answer
A. 12
B. 9
C. 7
D. 8
9
Q3
A. 112233
B. 123123123
C. 111213212223313233
D. 112131212223313233
10
Q3 Answer
j can be 0, 1
A. abcd
B. 012
C. 0
D. ab
18
Q7 Answer
It is comparing the
ASCII code of the
characters
A. abcd
B. 012
C. 0
D. ab
19
Q8
A. abcd
B. 012
C. 0
D. ab
20
Q8 Answer
A. abcd
B. 012
C. 0
D. ab
21
Tutorial Exercise 5.1
22
Tutorial Exercise 5.1
Hints
There are two ways to handle the situation when there is no solution.
• Using a flag (Boolean) to record whether the solution has been found. flag is
set to False before the iteration and will be changed to True when the solution
is found.
• The loop needs to be stopped when the solution is found.
If the number of rabbits is greater than the number of heads at the end of the
loop, then there is no solution.
25
Tutorial Exercise 5.3
26
Tutorial Exercise 5.3
Hints
27
Tutorial Exercise 5.4
28
Tutorial Exercise 5.4