+ 1
Help! Nested For Loops (Java)
Hi All, I’m still finding nested loops a little confusing and I have been told that the following code prints 10 when compiled and run but I can’t figure out why! I’m getting 3 so obviously going wrong somewhere, is anyone able to explain this to me please? class Test{ public static void main (String args []){ int c = 0; A: for(int i = 0; i < 2; i++){ B: for(int j = 0; j < 2; j++){ C: for(int k = 0; k < 3; k++){ c++ if(k>j) break; } } } System.out.println(c); } }
1 Antwort
+ 2
Explanation:Firstly,
when i=0,j=0,k=0
c=1
Then j=0,k=1
c=2
then the first loop breaks.
Now j=1 and k=0
c=3
when j=1 and k=1
c=4
when j=1 and k=2
c=5 then it again breaks.
now i becomes 1 and again The same thing continues .
so count becomes 5*2=10