Computer Applications
How many times will the following loop execute? Write the output of the code:
int a = 5;
while (a > 0) {
System.out.println(a-- + 2);
if (a % 3 == 0)
break;
}
Answer
Loop executes two times.
Output
7
6
Reason — Let's go through the Java program step by step to understand how it works:
Initial Value:
a = 5
Iteration 1:
System.out.println(a-- + 2);a--: Post-decrement is used, so the current value ofa(5) is used first, then decremented.- Output:
5 + 2 = 7 abecomes4
if (a % 3 == 0):4 % 3 = 1→ Condition is false, so the loop continues.
Iteration 2:
System.out.println(a-- + 2);a--: Current value ofa(4) is used, then decremented.- Output:
4 + 2 = 6 abecomes3.
if (a % 3 == 0):3 % 3 = 0→ Condition is true, so thebreakstatement exits the loop.
Therefore, the loop executes 2 times and the output is:
7
6
Related Questions
Rewrite the following do while program segment using for:
x = 10; y = 20; do { x++; y++; } while (x<=20); System.out.println(x * y );How many times will the following loop execute? Write the output of the code:
int x=10; while (true){ System.out.println(x++ * 2); if(x%3==0) break; }Which of the following are entry controlled loops?
(a) for
(b) while
(c) do..while
(d) switch
- only a
- a and b
- a and c
- c and d