1,105,644 Community Members

While loop

Member Avatar
java123456
Newbie Poster
6 posts since Dec 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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

Member Avatar
stultuske
Posting Expert
5,325 posts since Jan 2007
Reputation Points: 938 [?]
Q&As Helped to Solve: 776 [?]
Skill Endorsements: 35 [?]
Featured
 
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.

Member Avatar
java123456
Newbie Poster
6 posts since Dec 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
maurice91
Newbie Poster
5 posts since Dec 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
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 three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: