Java 之 杨辉三角形

题目:打印杨辉三角形。

1.程序分析:  

    1        

    1 1      

   1 2 1     

  1 3 3 1    

 1 4 6 4 1 

1 5 10 10 5 1

特点:

 杨辉三角以正整数构成,数字左右对称,每行由1开始逐渐变大,然后变小,回到1。

 n行的数字个数为n个。

 n行数字和为2n − 1

 除每行最左侧与最右侧的数字以外,每个数字等于它的左上方与右上方两个数字之和。

 

编程实现:

 import java.util.*;

public class YangHui{

  public static void main(String args []){

    System.out.print("Plz input the rows of YangHui:");

    int row; //打印行数

    Scanner scanner = new Scanner(System.in);

    row = scanner.nextInt();

    int col = 2*row-1;

    int array[][] = new int[row][col];

 

    for(int i=0; i<row; i++){

      for(int j=0; j<col; j++){

        int mid = col/2;

        if(i==0 && j==mid){

          array[i][j] = 1; //三角形顶端的1

        }else if(i==0){

          array[i][j] = 0; //用0做空格打印标记

        }else if(i==row-1 && j==0){

          array[i][j] = 1; //左侧1

        }else if(i==row-1 && j==col-1){

          array[i][j] = 1;  //右侧1

        }else if(i>0 && j>0 && j<col-1){

          array[i][j] = array[i-1][j-1]+array[i-1][j+1]; //内部数的变化

        }

      }

    }

    for(int i=0; i<row; i++){

      for(int j=0; j<col; j++){

        if(array[i][j]==0){

          System.out.print(); //被标记为0,则输出空格

        }else{

          System.out.print(array[i][j]);

        }

      }

      System.out.println();

    }

  }

}

 

(左侧型):

public class YangHui{

  public static void main(String args []){

    int array[][] = new int[10][10]; //10行10列

    

    for(int i=0; i<array.length; i++){

      for(int j=0; j<=i; j++){

        if(j==0 || i==j){

          array[i][j] = 1;

        }else{

          array[i][j] = array[i-1][j-1]+array[i-1][j];

        }

        System.out.print(array[i][j]+"\t");

      }

      System.out.println("");

    }

  }

}

 

posted @ 2012-01-26 20:51  qin520  阅读(605)  评论(0编辑  收藏  举报