Examveda
Examveda

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

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


This Question Belongs to Java Program >> Flow Control

Join The Discussion

Comments ( 9 )

  1. Amrit Bhattacharjee
    Amrit Bhattacharjee :
    2 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.

  2. Mosarrat Kamal
    Mosarrat Kamal :
    2 years ago

    It will print 1 2 3 for 3 times.
    Because (i = 0) and run till (i

  3. Vasanth Vel
    Vasanth Vel :
    2 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 .

  4. Vasanth Vel
    Vasanth Vel :
    2 years ago

    in line 6 :

  5. Kaivan Shah
    Kaivan Shah :
    2 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,......

  6. Gowtham Prabaharan
    Gowtham Prabaharan :
    5 years ago

    i think so it will be not be an infinte loop but it will prints 1 2 3 for 3 times.

  7. NITHU NITHYA
    NITHU NITHYA :
    5 years ago

    if anyone solve this question please explain it

  8. Atul Chopade
    Atul Chopade :
    7 years ago

    Ha na bhai solution to batana chahiye
    I think 3 times print 123

  9. Sonu Shaw
    Sonu Shaw :
    7 years ago

    How is this an infinite loop?
    Please anyone can explain?

Related Questions on Flow Control