Computer Applications
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;
}
Answer
The loop executes two times.
Output
20
22
Explanation:
Step-by-Step Execution of the Code
Initial Value of x
:x = 10
Iteration 1:System.out.println(x++ * 2);
x++
→ Use the current value ofx
(10), then incrementx
to 11.- Output:
10 * 2 = 20
if (x % 3 == 0)
:
x = 11
, so11 % 3 = 2
→ Condition isfalse
.
Iteration 2:System.out.println(x++ * 2);
x++
→ Use the current value ofx
(11), then incrementx
to 12.- Output:
11 * 2 = 22
if (x % 3 == 0)
:
x = 12
, so12 % 3 = 0
→ Condition istrue
.
break;
- The
break
statement exits the loop.
Related Questions
A student executes the following program segment and gets an error. Identify the statement which has an error, correct the same to get the output as WIN.
boolean x = true; switch(x) { case 1: System.out.println("WIN"); break; case 2: System.out.println("LOOSE"); }
Write the output of the following String methods:
String x= "Galaxy", y= "Games";
(a) System.out.println(x.charAt(0)==y.charAt(0));
(b) System.out.println(x.compareTo(y));
Predict the output of the following code snippet:
char ch='B', char chr=Character.toLowerCase(ch); int n=(int)chr-10; System.out.println((char)n+"\t"+chr);