ExamVeda
Login
Home
This question belongs to Java Program Flow Control
Flow Control
?

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);
		  }
	    }
      }
}

Answer & Solution
Correct Answer: Option C
Let's discuss the solution. Join the discussion
Examveda
Question posted by Examveda
Community

Join the Discussion

9 Comments
Amrit Bhattacharjee
Amrit Bhattacharjee 4 years ago
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.
Mosarrat Kamal
Mosarrat Kamal 5 years ago
It will print 1 2 3 for 3 times.
Because (i = 0) and run till (i
Vasanth Vel
Vasanth Vel 5 years ago
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 .
Vasanth Vel
Vasanth Vel 5 years ago
in line 6 :
Kaivan Shah
Kaivan Shah 5 years ago
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,......
Gowtham Prabaharan
Gowtham Prabaharan 7 years ago
i think so it will be not be an infinte loop but it will prints 1 2 3 for 3 times.
NITHU NITHYA
NITHU NITHYA 7 years ago
if anyone solve this question please explain it
Atul Chopade
Atul Chopade 9 years ago
Ha na bhai solution to batana chahiye
I think 3 times print 123
Sonu Shaw
Sonu Shaw 9 years ago
How is this an infinite loop?
Please anyone can explain?