Skip to content

Instantly share code, notes, and snippets.

@mike820324
Created March 12, 2014 14:24
Show Gist options
  • Save mike820324/9507964 to your computer and use it in GitHub Desktop.
Save mike820324/9507964 to your computer and use it in GitHub Desktop.
package ce1002.a2.ta;
import java.util.Scanner;
public class A2 {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
int bound = 0;
int[][] arr;
System.out.println( "Please input a number (1~10): " );
bound = input.nextInt();//讓使用者輸入一個數字
while( bound < 1 || bound > 10 )//輸入不在合理範圍內則重新輸入
{
System.out.println( "Out of range!" );
System.out.println( "Please input a number (1~10): " );
bound = input.nextInt();
}
arr = new int [bound+1][bound+1];
int j = 1;
for( int i = 1 ; i < bound + 1 ; i++ )//初始化
{
arr[i][1] = 1;//陣列的頭給1
arr[i][j] = 1;//陣列的尾給1
j++;
}
for( int i = 3 ; i < bound + 1 ; i++ )//每個位置的值是上面那排元素加旁邊的
{
for( int k = 2 ; k < bound + 1 ; k++ )
{
arr[i][k] = arr[i-1][k] + arr[i-1][k-1];
}
}
for( int i = 1 ; i < bound + 1 ; i++ )//最後輸出巴斯卡三角形
{
for( int k = 1; k < i+1 ; k++ )
{
System.out.print( arr[i][k] + " " );
}
System.out.println( "" );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment