Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class PascalTriangle
- {
- public static int[] pascalRow(int n){
- Scanner scan = new Scanner(System.in);
- if (n<0){
- System.out.print("Please eneter a number greater then or equal to 0. ");
- n = scan.nextInt();
- }
- int[] row = new int[n+1];
- // Base Case: Builds the n = 0 row.
- if (n ==0)
- {
- row[0] = 1;
- }
- // Recursive Case: Builds the nth row by recursively calling the previous row.
- else {
- int[] previousRow = pascalRow(n-1);
- // Sets the first element in the row to 1
- row[0] = 1;
- for (int i = 1; i<(n);i++){
- row[i] = previousRow[i-1]+previousRow[i];
- }
- // Sets the last element in the row to 1
- row[n] = 1;
- }
- return row;
- }
- public static void main(String[] args){
- int[] a;
- a = pascalRow(-1);
- for (int elem: a){
- System.out.println(elem);
- }
- int i = 0;
- while (i<10)
- {
- for(int elem: pascalRow(i))
- {
- System.out.print(elem+" ");
- }
- System.out.println();
- i++;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement