Java核心知识(三)---for循环算法
Java核心知识---for循环算法
王利华2012-5
一、for 循环模式
for(int x=0;x<10;x++) //外层循环
{
for(int j=0;j<10;j++) //内层循环
}
二、内外循环关系
三、几种实例
算法准备:
for(x=0;x<9;x++)
for(j=0;j<9;j++)
(1)打印
*
* *
* * *
分析:有三行,三列/三行五列
本例采取三行三列
For(x=0;x<3;x++)
{
For(j=0;j<x;j++)
{
System.out.print("*"+" ");
}
System.out.println();
}
(2)打印
* * *
* *
*
For(x=3;x<3;x--)
{
For(j=0;j<x+1;j++)
{
System.out.print("*"+" ");
}
System.out.println();
}
(3)打印
1
1 2
1 2 3
For(int x=0;x<3;x++)
{
For(int y=1;y<x;y++)
{
System.out.print(y);
}
System.out.println();
}
(4)打印99乘法表
For(int x=0;x<9;x++)
{
For(int y=1;y<=x+1;y++)
{
System.out.print(y+“x”+(x+1)+”=”+y*(x+1))
}
System.out.println();
}
优化代码
For(int x=1;x<=9;x++)
{
For(int y=1;y<=x;y++)
{
System.out.print(y+”*”+x+”=”+y*x+”\t”);
}
System.out.println();
}