Start New Discussion within our Software Development Community

hey guys , I don't understand why the outPUT is that for the code below.. can someone please explin me how it works. Thank you.

class example{
    public static void main (String[]args){
        int i = 1,j;
        while (i<=3){
            j=i;
            while(j<=4){
                System.out.println(j+"  "+i);
                j=j+2;
            }
            i=i+1;
            }
        }

    }

HERE IS THE OUTPUT
1 1
3 1
2 2
4 2
3 3

read the code, write down (in pseudo code) step by step what it does, and what values are assigned, that 'll help understanding it.

I'll go through the code for you, it's really straightforward.

Start:

int i = 1, j;

while( i<= 3){
 j = i;

 while(j <= 4){
   system.out.println( 1 1 )
   j = j + 2;
 }

Now:(j = 3, i = 1)

Next:

while(j <= 4){
   system.out.println( 3 1 )
   j = 3 + 2;
 }

Now: j = 5 so while loop exits and i increases by 1
(j = 5, i = 2)

Next:

 while( i<= 3){
 j = i;

 while(j <= 4){
   system.out.println( 2 2 )
   j = j + 2;
 }

Now: (j = 4, i = 2)

 Next:
  while(j <= 4){
   system.out.println( 4 2 )
   j = j + 2;
 }
This article has been dead for over six months. Start a new discussion instead.