Computer Applications
How many times will the following loop execute?
int a = 5;
while (a > 0) {
System.out.println(a-- + 2);
if (a % 2 == 0)
break;
}
Answer
1
Reason — Let's understand the execution of the loop step by step:
- Initially,
a = 5, soSystem.out.println(5 + 2);executes, andais decremented to4. - Now,
a % 2 == 0istrue(since4 % 2 == 0), so thebreakstatement is executed, exiting the loop. - Since the loop executes only once before breaking, the correct answer is 1 time.