Sunday, March 1, 2015

Project Two for Java: Pascal's Triangle

Program:

package fourthlecture;

import java.util.Scanner;

public class Pascaltriangle {
static Scanner sc=new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter -1 to exit ");
System.out.println("Please give a number which you convert pascal triangle: ");
int yourchoice=sc.nextInt();
while(yourchoice !=-1){
if(yourchoice <-1 || yourchoice>20){
System.out.println("Please input a value between 1~20 ");
yourchoice=sc.nextInt();
continue;
}
pascaltrianglee(yourchoice);
System.out.println("\n\n");
System.out.println("Please input a value between 1~20 ");
yourchoice=sc.nextInt();

}

System.out.println("You have exited the program.");

}

static void pascaltrianglee(int length){
int[][] pascal = new int[length][length];
for(int i=0;i<length;i++){
pascal[0][i]=1;
pascal[i][0]=1;
}


for(int row=1;row<length;row++){
for(int column=1;column<length-row;column++){
pascal[row][column]=pascal[row][column-1]+pascal[row-1][column];
}
}


for(int row=0;row<length;row++){
for(int column=0;column<length-row;column++){
System.out.print(pascal[row][column]+"\t");
}

System.out.println("\n");
}
}
}

Output:

Enter -1 to exit
Please give a number which you convert pascal triangle:
5
1 1 1 1 1

1 2 3 4

1 3 6

1 4

1




Please input a value between 1~20
6
1 1 1 1 1 1

1 2 3 4 5

1 3 6 10

1 4 10

1 5

1




Please input a value between 1~20
-1
You have exited the program.


Screenshots

program 1


Program:2


Output



No comments: