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, anda
is decremented to4
. - Now,
a % 2 == 0
istrue
(since4 % 2 == 0
), so thebreak
statement is executed, exiting the loop. - Since the loop executes only once before breaking, the correct answer is 1 time.
Related Questions
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
Write a program in Java to find the Fibonacci series within a range entered by the user.
Sample Input:
Enter the minimum value: 10
Enter the maximum value: 20Sample Output:
13Convert the following for loop segment to an exit-controlled loop.
for (int x = 1, y = 2; x < 11; x += 2, y += 2) { System.out.println(x + "\t" + 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; }