Welcome to the Java Loops Coding Quiz. In this quiz, we present 10 coding MCQ questions to test your coding knowledge on the Java Loops (for loop, while loop, do-while-loop) topic. Each question has a correct and brief explanation.
1. What is the output of the following Java code snippet?
for (int i = 0; i < 5; i++) {
if (i == 2) {
break;
}
System.out.print(i + " ");
}
Answer:
Explanation:
The break statement exits the loop when i equals 2. Thus, only 0 and 1 are printed.
2. What does this Java code snippet output?
int i = 0;
while (i < 3) {
System.out.print(i + " ");
i++;
}
Answer:
Explanation:
The loop prints i and increments it each time until i is less than 3.
3. Identify the output of the following code:
int count = 0;
do {
count++;
} while (count < 3);
System.out.println(count);
Answer:
Explanation:
The do-while loop increments count until it is less than 3. It stops when count becomes 3.
4. What will be printed by this Java code?
for (int i = 0; i < 5; i++) {
if (i % 2 == 0) {
continue;
}
System.out.print(i + " ");
}
Answer:
Explanation:
The continue statement skips the current iteration of the loop when i is even. Thus, only the odd numbers 1 and 3 are printed.
5. What does this code snippet output?
int i = 1;
while (i <= 5) {
System.out.print(i + " ");
i++;
}
Answer:
Explanation:
The while loop iterates as long as i is less than or equal to 5, printing numbers from 1 to 5.
6. What is the result of executing this code?
int sum = 0;
for (int i = 0; i <= 4; i++) {
sum += i;
}
System.out.println(sum);
Answer:
Explanation:
The for loop calculates the sum of numbers from 0 to 4, resulting in 10.
7. What will the following Java code snippet output?
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == j) {
break;
}
System.out.print(i + "" + j + " ");
}
}
Answer:
Explanation:
The break statement exits the inner loop when i equals j. It results in pairs where i is not equal to j.
8. What does the following code snippet print?
int i = 5;
while (i > 0) {
i--;
if (i == 2) {
continue;
}
System.out.print(i + " ");
}
Answer:
Explanation:
The continue statement skips the print statement when i is 2. The loop prints 4, 3, 1, and then 0.
9. Determine the output of this Java code:
int x = 0;
for (int i = 10; i > 0; i--) {
x += i;
}
System.out.println(x);
Answer:
Explanation:
The for loop adds the numbers from 10 to 1, resulting in a total of 55.
10. What is the result of the following code snippet?
int i = 0;
do {
i++;
if (i == 4) {
break;
}
} while (i < 7);
System.out.println(i);
Answer:
Explanation:
The do-while loop increments i until it reaches 4, where the break statement exits the loop.
Comments
Post a Comment
Leave Comment