外层循环显示行数,内层循环显示列数,把菱形分为上下两个部分,菱形由*和空格构成,用i表示外层循环, j表示内层循环前半部分,k表示内层循环后半部分。推出2*i+j=10,由此得出j= 10-2*i,而k=2*i-1。
1.菱形上半部分:
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 10-2*i; j++) {
System.out.print(" ");
}
for (int k = 1; k <= 2*i-1; k++) {
System.out.print("* ");
}
System.out.println();
}
2.菱形下半部分:
for (int i = 1; i <= 4; i++) {
for (int k = 1; k <= 2*i; k++) {
System.out.print(" ");
}
for (int j = 1; j <= 9-2*i; j++) {
System.out.print("* ");
}
System.out.println();
}
3.效果展示:
![](https://i-blog.csdnimg.cn/blog_migrate/4cfcd575359f789d55ccfcbabf6a8ff8.png)