楊輝三角形,直角楊輝三角形

來源:互聯網
上載者:User

楊輝三角形,直角楊輝三角形

利用二維數組列印一個楊輝三角

 

案例介紹

①設計列印輸出一個8行的楊輝三角形

②找出楊輝三角形的特點

 

案例設計

①二維數組的聲明和使用

②使用for迴圈來對數組進行賦值和輸出

 

實施方案

①聲明一個8行8列的數組

②第一列和對角線值為1,其它列的值是其正上方元素和其左上方元素之和。

③對數組進行賦值並列印輸出

1 public class YangHui{ 2 public static void main(String []args){ 3 int row=8;//行數 4 int[][] p=new int[row][row]; 5 //賦值 6 for(int i=0;i<p.length;i++) 7 { 8 for(int j=0;j<=i;j++) 9 {10 //第一列和對角線列的元素為111 if(j==0||j==i)12 {13 p[i][j]=1;14 }15 else16 {17 //其它元素的值是其正上方與其左上方元素之和18 p[i][j]=p[i-1][j]+p[i-1][j-1];19 }20 }21 }22 23 //列印輸出24 for(int i=0;i<p.length;i++)25 {26 for(int j=0;j<=i;j++)27 {28 System.out.print(p[i][j]+" ");29 }30 System.out.println();31 }32 }33 }View Code

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.