Java 这个For循环如何以这种方式打印?
我正在学习编码,今天我尝试了这个程序Java 这个For循环如何以这种方式打印?,java,Java,我正在学习编码,今天我尝试了这个程序 for (cnt = 1; cnt <= 6; cnt++) { for (int j = cnt; j <= 6; j++) { System.out.print("*"); } System.out.println(); } 你能给我解释一下吗?那是因为int j=cnt其中cnt增加,所以第二个循环的迭代次数会随着cnt的增加而减少。考虑一下这个< BR> 当cnt=1时,第二个
for (cnt = 1; cnt <= 6; cnt++) {
for (int j = cnt; j <= 6; j++) {
System.out.print("*");
}
System.out.println();
}
你能给我解释一下吗?那是因为
int j=cnt
其中cnt
增加,所以第二个循环的迭代次数会随着cnt
的增加而减少。考虑一下这个< BR>
当cnt=1
时,第二个循环将打印6次当
cnt=2
时,第二个循环将比之前少打印一次。等等这就是它要打印的内容:
******
*****
****
***
**
*
*
的数量每行减少一个。当cnt
=1时
j = 1 => Print * => The line becomes *
j = 2 => Print * => The line becomes **
j = 3 => Print * => The line becomes ***
j = 4 => Print * => The line becomes ****
j = 5 => Print * => The line becomes *****
j = 6 => Print * => The line becomes ******
After this line breaks
当cnt
=2时
j = 2 => Print * => The line becomes *
j = 3 => Print * => The line becomes **
j = 4 => Print * => The line becomes ***
j = 5 => Print * => The line becomes ****
j = 6 => Print * => The line becomes *****
After this line breaks
因此,经过两次cnt
迭代后,您将获得以下模式:
******
*****
这样,
cnt
的迭代将上升到6
,您将得到反向金字塔模式,您的外部循环正在生成行。内部循环打印j-cnt*符号。由于cnt在打印的每一行都在上升,因此j-cnt在每次外循环迭代中都在下降。因此,它每一行打印的符号越来越少。在外循环的第一次迭代中,cnt
值是1
,j
在内循环中被分配了cnt
的值,即1
,因此内循环将从1
迭代到6
,这是六颗星
在外循环的第二次迭代中,cnt
的值是2
,内环中的j
被分配了cnt
的值,即2
,因此内环将从2
迭代到6
,这是五颗星
在外循环的第三次迭代中,cnt
的值是3
,内环中的j
被分配了cnt
的值,即3
,因此内环将从3
迭代到6
,这是四颗星
在外循环的第六次迭代中,
cnt
值为6
,内循环中的j
被分配了cnt
的值,即6
,因此内循环将从6
迭代到6
,这是一颗星。j
用cnt
的值初始化。每次增加cnt
,这意味着j
用更高的值初始化,因此需要更少的迭代次数才能达到6
。
******
*****