java - Why is my nested for loop not displaying Hello World 2 -


here nested loop.

int c = 1; (int d = 0; d < 10; d++) {     if (c == 6) {         system.out.println("hello world 1");     } else if (c == 7) {         system.out.println("hello world 2");     }     (int e = 0; e < 5; e++) {         system.out.println("this nested loop :" +c);         c++;     } } 

this console printing out.

this nested loop :1 nested loop :2 nested loop :3 nested loop :4 nested loop :5 hello world 1 nested loop :6 nested loop :7 nested loop :8 

and continues printing until reach's 50 , not display hello world 2.

let me add comments current code. read code going through steps 1 7 in order.

int c = 1; (int d = 0; d < 10; d++) {     // 1. when here first time, c = 1, both if false     // 4. now, c equal 6 first if true, "hello world 1" printed     // 7. now, c equal 11, both if false, nothing printed...     if (c == 6) {         system.out.println("hello world 1");     } else if (c == 7) {         system.out.println("hello world 2");     }     (int e = 0; e < 5; e++) {         // 2. reach here, c incremented 5 times.         // 5. c incremented again 5 times         system.out.println("this nested loop :" +c);         c++;     }     // 3. when we're here, c 1 6 (incremented 5 times in step 2)     // 6. when we're here second time, c 11 (6 incremented 5 times in step 5) } 

basically, @ start of first for, c 1, 6, 11... never 7, "hello world 2" never printed.


Comments