双层for循环执行,里面的(第二个for)循环必须执行完它自己的所有内容才能返回到第一个for循环里面。
例如 冒泡排序。
int a[] = {24, 69, 80, 57, 13}, temp = 0;
for (int j = 0; j < a.length - 1; j++) {
for (int i = 0; i < a.length - 1 - j; i++) {
if (a[i] > a[i + 1]) {
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
例如杨辉三角
ublic class menu {
public static void main(String args[]) {
int[] yanghui[] = new int[10][];
for (int i = 0; i < yanghui.length; i++) {
yanghui[i] = new int[i+1];
for(int j=0;j< yanghui[i].length;j++){
if(j==0 || j==yanghui[i].length-1){
yanghui[i][j]=1;
}else{
yanghui[i][j]=yanghui[i-1][j]+yanghui[i-1][j-1];
}
}
}
for(int i=0;i<yanghui.length;i++){
for(int j=0;j<yanghui[i].length;j++){
System.out.print(yanghui[i][j]+"\t");
}
System.out.println();
}
}
}
从杨辉三角可以看出,第一行时打印几个数之后,返回到第一个for循环,然后执行第二行,打印几个数。