1.11M Members

While loop

 
0
 

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

 
0
 

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

 
0
 

i did that but i still don't undesrtand it.

 
1
 

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;
 }
You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: