二维数组打印杨辉三角

大家好,今天我给大家分享一下用二维数组打印杨辉三角形。

杨辉三角形:                1

                               1            1

                        1             2            1

                  1            3               3         1

             1          4            6         4             1

      1           5            10         10           5         1

在这里我们只打印六行,代码如下:

public class TestYH{
	
	public static void main(String[] args){
		
		int rows = 6;
		
		int[][] yh = new int[rows][];

		//创建多个不同长度的二维数组
		for(int i = 0 ; i < rows ; i++){
			yh[i] = new int[i+1];
		}
		
		//完成初始值的赋值(每行的首位都是1)
		for(int i = 0 ; i < yh.length ; i++){ // i = 2
			yh[i][0] = 1;
			yh[i][i] = 1;
		}
		
		//计算
		for(int i = 2 ; i < yh.length ; i++){
			for(int j = 1 ; j < i ; j++){
				//当前位置的值 = 上一行的同列 + 上一行的前一个列
				yh[i][j] = yh[i-1][j] + yh[i-1][j-1];
			}
		}

		for(int i = 0 ; i < yh.length ; i++){
			
			for(int j = rows - 1 ; j > i ; j--){//满足4次
				System.out.print("\t");
			}
			
			
			for(int j = 0 ; j < yh[i].length ; j++){
				System.out.print( "\t"+ yh[i][j] +"\t");
			}
			System.out.println();
			
		}
		
	}
	
}

 

你可能感兴趣的:(二维数组打印杨辉三角)