Advertisement
Guest User

Untitled

a guest
Apr 19th, 2015
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.00 KB | None | 0 0
  1. import java.util.Scanner;
  2. public class PascalTriangle
  3. {
  4.     public static int[] pascalRow(int n){
  5.         Scanner scan = new Scanner(System.in);
  6.         if (n<0){
  7.             System.out.print("Please eneter a number greater then or equal to 0. ");
  8.             n = scan.nextInt();
  9.         }
  10.         int[] row = new int[n+1];
  11.         // Base Case: Builds the n = 0 row.
  12.         if (n ==0)
  13.         {
  14.             row[0] = 1;
  15.         }
  16.         // Recursive Case: Builds the nth row by recursively calling the previous row.
  17.         else {
  18.             int[] previousRow = pascalRow(n-1);
  19.             // Sets the first element in the row to 1
  20.             row[0] = 1;
  21.             for (int i = 1; i<(n);i++){
  22.                 row[i] = previousRow[i-1]+previousRow[i];
  23.             }
  24.             // Sets the last element in the row to 1
  25.             row[n] = 1;
  26.         }
  27.         return row;
  28.     }
  29.     public static void main(String[] args){
  30.         int[] a;
  31.         a = pascalRow(-1);
  32.         for (int elem: a){
  33.             System.out.println(elem);
  34.         }
  35.         int i = 0;
  36.         while (i<10)
  37.         {
  38.             for(int elem: pascalRow(i))
  39.             {
  40.                 System.out.print(elem+" ");
  41.             }
  42.             System.out.println();
  43.             i++;
  44.         }
  45.         }
  46.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement