What will be the result of the following code?
public class Test{
static public void main(String args[]){ //line 2
int i, j;
for(i=0; i<3; i++){
for(j=1; j<4; j++){
i%=j;
System.out.println(j);
}
}
}
}
public class Test{
static public void main(String args[]){ //line 2
int i, j;
for(i=0; i<3; i++){
for(j=1; j<4; j++){
i%=j;
System.out.println(j);
}
}
}
}
A. 1 2 3 1
B. 1 2 3 2
C. Repeatedly print 1 2 3 and cause infinite loop.
D. Compilation fails because of line 2
E. None of these
Answer: Option C
Join The Discussion
Comments ( 9 )
Related Questions on Flow Control
What is the purpose of the "if" statement in Java?
A. To execute a block of code conditionally
B. To create loops
C. To declare variables
D. To define methods
A. No output
B. Error
C. Hello
D. 5
It is an infinite loop because in the line, i %=j which means i = i %j, the value of i is being is set to 0, when i =1, j=1 or i = 2, j = 2. Thus, it makes an infinite loop.
It will print 1 2 3 for 3 times.
Because (i = 0) and run till (i
in line 6:
i%=j // 0%1 = 0, 0%2 = 0, 0%3 = 0 it holds i value as 0 so the loop is infinite .
in line 6 :
Solution:
i = 0, j = 1 line 1
i%=j -> i = i%j = 0%1 = 0 line 2
print(j) -> 1 line 3
i = 0, j = 2 line 4
i%=j -> i = i%j = 0%2 = 0 line 5
print(j) -> 2 line 6
i = 0, j = 3 line 7
i%=j -> i = i%j = 0%3 = 0 line 8
print(j) -> 3 line 9
i = 1, j = 1 line 10
i%=j -> i = i%j = 1%1 = 0 line 11
print(j) -> 1 line 12
i = 1, j = 2 line 13
i%=j -> i = i%j = 0%2 = 0 (NOTE: i is not 1 it is 0 now refer line 11) line 14
print(j) -> 2 (NOTE: We are printing value of 'j' and not 'i') line 15
i = 1, j = 3 line 16
i%=j -> i = i%j = 1%3 = 0 (NOTE: i is not 1 it is 0 now refer line 11) line 17
print(j) -> 3 (NOTE: We are printing value of 'j' and not 'i') line 18
This goes on for values of i from 2,3,4,5,......
i think so it will be not be an infinte loop but it will prints 1 2 3 for 3 times.
if anyone solve this question please explain it
Ha na bhai solution to batana chahiye
I think 3 times print 123
How is this an infinite loop?
Please anyone can explain?