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;
}
Java Iterative Stmts
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.
Answered By
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 );
Define a class to accept a number and check whether it is a SUPERSPY number or not. A number is called SUPERSPY if the sum of the digits equals the number of the digits.
Example1:
Input: 1021 output: SUPERSPY number [SUM OF THE DIGITS = 1+0+2+1 = 4, NUMBER OF DIGITS = 4 ]
Example2:
Input: 125 output: Not an SUPERSPY number [1+2+5 is not equal to 3]
Give the output of the following program segment. How many times is the loop executed?
for(x=10; x>20;x++) System.out.println(x); System.out.println(x*2);