Welcome to Java MCQ (Mulitple Choice Question) series. In this post, we will see one more quiz question on Java Loops.
What is the purpose of the continue statement in a loop?
a) To exit the loop immediatelyb) To skip the current iteration and move to the next iteration
c) To terminate the program
d) To execute a specific block of code
Answer:
b) To skip the current iteration and move to the next iterationExplanation:
The continue statement in a loop has a specific purpose. It is used to skip the rest of the current iteration and immediately start the next one.
When a continue statement is encountered within a loop, the loop stops its current iteration, updates its condition, and begins its next iteration, if applicable.
Here's a simple example in Java:
for(int i = 0; i < 10; i++) {
if(i % 2 == 0) {
continue; // skip even numbers
}
System.out.println(i); // this will only print odd numbers
}
In this example, when i is an even number, the continue statement causes the loop to skip the System.out.println(i); command. This effectively causes the loop to only print out the odd numbers since the print command is skipped every time i is even.
Comments
Post a Comment