We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,680 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

While loop

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

3
Contributors
3
Replies
6 Hours
Discussion Span
6 Months Ago
Last Updated
4
Views
java123456
Newbie Poster
6 posts since Dec 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 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.

stultuske
Industrious Poster
4,496 posts since Jan 2007
Reputation Points: 1,377
Solved Threads: 630
Skill Endorsements: 25

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

java123456
Newbie Poster
6 posts since Dec 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

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;
 }
maurice91
Newbie Poster
5 posts since Dec 2012
Reputation Points: 0
Solved Threads: 1
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page generated in 0.0643 seconds using 2.68MB