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
1 Like
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.
Answered By
3 Likes
Related Questions
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:
13Give 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);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]