Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# three for Loops?

sonir shah
Ranch Hand
Posts: 435
What will the following program print?

Answer : It will print 3
Can any one explain me how do we get such an output? specially when there are 3 for loops nested one in one?
Sonir

DC Dalton
Ranch Hand
Posts: 287
I have found the best way to attack any loop question like this is by writing up a small chart on paper & incrementing your variables like that. Keeping track of this by eye can be flustering. In this example the values going thru the loops are as follows: i-k repectively. Remeber when the condition is true the prog breaks(first line after the if since no braces are used, when false it increments counter.
000 (0-0>0)false counter 1
001 (1-0>0) true counter=1
011 (1-1>0) false counter=2
012 (2-1>0) true counter=2
022 (2-2>0) false counter=3
After that you start dropping out of the loops because you have incremented k, j to 3 (respectively) The outer loop then increments but the inner variables are already 3 so nothing happens in those loops.
[ January 13, 2002: Message edited by: DC Dalton ]

patrick tang
Ranch Hand
Posts: 44
I think the value of i in outer instead j in middle is incremented after every "break middle" statement.
pls see the following code

the result will be
i=0 j=0 k=0 counter=1
i=0 j=0 k=1
i=1 j=0 k=0 counter=2
i=1 j=0 k=1
i=2 j=0 k=0 counter=3
i=2 j=0 k=1
3
[ January 13, 2002: Message edited by: patrick tang ]

sonir shah
Ranch Hand
Posts: 435
Hey guys
I am still not clear with the concept.I tried working it out on a paper.
i=0,j=0,k=0 (0-0>0) false
i=0,j=0,k=1(1-0>0)true--->counter 1;
i=0,j=1,k=1(1-1>0)false
i=0,j=1,k=2(2-1>0)true---->counter 2;
1=0;j=2,k=2(2-2>0)false
I am thorough till here.Can any one explain me the steps from now with reasons..

Sonir

DC Dalton
Ranch Hand
Posts: 287
Well when your wrong your wrong, (serves me right for trying to answer a question while studying!) The label is used with the break to terminate THAT loop and any inside of it. So as I was so correctly corrected i increments NOT the inner variables.
Put printlns after each for statement and after the counter increment & you will see the results step by step. This is what comes out:
F:\JavaProgs>java LoopTest
i is: 0
j is: 0
k is: 0
Counter is: 1
k is: 1
i is: 1
j is: 0
k is: 0
Counter is: 2
k is: 1
i is: 2
j is: 0
k is: 0
Counter is: 3
k is: 1
3
So the final answer is 3.
[ January 13, 2002: Message edited by: DC Dalton ]