Sharpen your understanding of break and continue statements in loops with this focused quiz. Explore how these control flow tools affect loop execution, handle special cases, and improve code efficiency in programming.
In a while loop that prints numbers 1 to 10, which statement will immediately exit the loop when the current number equals 5?
Explanation: The 'break' statement exits the loop entirely as soon as the specified condition is met, halting further iterations. 'continue' would skip only the current iteration instead of exiting the loop. 'exit' and 'stop' are not valid ways to break out of a loop in this context, making them incorrect.
Given a for loop iterating over numbers 1 to 5, which statement will skip printing the number 3, but continue printing others?
Explanation: The 'continue' statement skips the current loop iteration and moves to the next one, effectively leaving out number 3 from being printed while continuing. 'break' would completely exit the loop instead of skipping one iteration. 'stop' and 'repeat' are both invalid in this context and will not work as intended.
In nested loops, what is the effect of a break statement inside the inner loop?
Explanation: A break statement inside the inner loop will only terminate the execution of that loop, after which control moves to the next iteration of the outer loop. It does not end the entire program, so option two is wrong. Option three describes the continue statement, not break. Option four is not how break operates in nested loops.
How can a continue statement be combined with a conditional to skip even numbers in a loop printing values 1 to 6?
Explanation: Placing continue inside a condition that checks for even numbers causes those iterations to skip the print statement, omitting even numbers from output. Running continue after printing still prints all values. Break would terminate the loop prematurely, and using continue without a condition would skip every number or cause logical issues.
What is the main difference between break and continue statements within loops?
Explanation: Break ends the loop at once, while continue only skips the rest of the current iteration and continues looping. The second option misrepresents their behaviors, as only break exits the whole loop. Option three has their roles switched, and the last option is incorrect as these statements serve different purposes.