开发者

Understanding for-nested loop

 public static void main(String[] args)  {

     int count, innerCount;
     for(count=0;count<=3;count++)
     {
         System.out.println("Count is" + count);
         for(innerCount=0; innerCount<count;innerCount++)
             System.out.print("Hi, innerCount is"+ innerCount);
     }
 }

}

Output:

Count is0

Count is1

Hi, innerCount is0Count is2

Hi, innerCount is0Hi, innerCount is1Count is3

Hi, innerCount is0Hi, innerCount is1Hi, innerCount is2

Can someone explain this for nested loop to me, please? When it is Count = 0 and 1 why is it not print开发者_JS百科ing out any innerCounts? Also howcome innercounts are printing right next to Count? Thanks.


When it is Count = 0 and 1 why is it not printing out any innerCounts?

It is. When count is 0, the inner loop never executes its body, because the innerCount<count condition is never true (0<0 is false). When count is 1, the inner loop executes once, when innerCount is 0 (printing "Hi, innerCount is0"), because 0<1 is true. It doesn't execute a second time because 1<1 is false.

Also howcome innercounts are printing right next to Count? Thanks.

Because you're using System.out.print, which doesn't append newlines. System.out.println appends newlines, if you want to use that.


It prints out Count = 0 and Count = 1 first because your condition in the inner loop is innerCount < count so it is skipped the first time since both innerCount and count = 0.

System.out.print doesn't append newlines. Use System.out.println instead.


innerCount<count is your problem

make it <= and you will get a printout for 0

as someone already pointed out, you do get a result when count = 1 already

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜