?
What will be the result of the following code?
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);
}
}
}
}
Join the Discussion
Login to post a comment or share your explanation.
LoginBecause (i = 0) and run till (i
i%=j // 0%1 = 0, 0%2 = 0, 0%3 = 0 it holds i value as 0 so the loop is infinite .
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 3 times print 123
Please anyone can explain?