Question 13
Which of the following is a possible value of num, such that it would make the code below print out only the first 5 digits? [3 marks]
Options:
- 15520164
- 15520514
- 15520814
- 15526814
- 15560814
Solution
Observe the for loop in the question - iterator variable digit takes on a digit from num as a string.
In each iteration, it first checks to see if that digit's value is greater than 5 - if so, it breaks the loop (think of it as a forced abort).
Otherwise, it goes on to print out that digit.
In this case, we need to find a number that does not abort until after the fifth digit. Here, only 15520814 fits, since the sixth digit in this number is greater than 5 whilst the first five are not.
- 15520164: breaks only after 6 digits
- 15520514: does not break, all digits are printed
- 15526814: breaks after 4 digits (premature break)
- 15560814: breaks after 3 digits (premature break)
Answer
15520814