7.5 Activities
What numbers are output by the code segment? for ($c = 5; $c < 10; $c += 2) { echo $c; } a) 5, 7, 9 b) 5, 6, 7, 8, 9 c) Infinite loop
a (The loop terminates after $c is incremented to 11)
What is $c when the loop terminates? $c = 10; while ($c <= 20); { echo $c; $c += 5; } a) 25 b) 20 c) The loop never terminates.
c (The semicolon after the while condition creates an infinite loop. While loops should never have a semicolon after the condition.)
What condition causes the for loop to output the numbers 100 down to 50, inclusively? for ($c = 100; ______; $c--) { echo $c; } a) $c < 50 b) $c > 50 c) $c >= 50
c
What is $c when the loop terminates? $c = 10; while ($c <= 20) echo $c; $c += 5; a) 15 b) 20 c) The loop never terminates.
c (Even though $c += 5 is indented, only echo $c; is in the loop body because the while loop does not have { } surrounding both statements. Therefore, 10 is output repeatedly in an infinite loop)
What is the last number output by the loop? $c = 0; do { $c++; echo $c; } while ($c < 5);
5 (The numbers 1, 2, 3, 4, 5 are output. After 5 is output, the loop's condition is false, and the loop terminates.)
What conditional operator makes the do-while loop output 10, 20, 30, ..., 100? $c = 10; do { echo $c; $c += 10; } while ($c ___ 100);
<= (The loop executes when $c is 100 and terminates after $c is incremented to 110.)
What numbers are output by the code segment? for ($x = 1; $x <= 3; $x++) { // outer loop for ($y = 2; $y <= 4; $y++) { // inner loop echo $y; } } a) 2, 3, 4 b) 2, 3, 4, 2, 3, 4, 2, 3, 4 c) 2, 3, 4, 5, 6, 7, 8, 9, 10
b
Which loop always executes the loop body at least once? a) while b) do-while c) for
b
What condition makes the loop output even numbers 2 through 20? $c = 2; while (_____) { echo $c; $c += 2; } a) $c >= 20 b) $c <= 20 c) $c < 20
b (The last time this loop outputs a value is when $c is 20)
What are the first and last numbers output by the code segment? $c = 100; while ($c > 0) { echo $c; $c -= 10; } a) 100 and 0 b) 90 and 0 c) 100 and 10
c (loop terminates when $c is 0. At the start of the last iteration, $c is 10. $c is then decremented to 0. The loop condition is checked: 0< is false, and the loop terminates)