// HW08_2e.java // Tim Hilby // Created on April 12, 2006 import java.util.Scanner; public class HW08_2e { // calculates the nth row of Pascal's Triangle // returns null if n is not positive public static int[] row(int n) { int[] prevRow; int[] curRow; if (n <= 0) { // invalid row number curRow = null; } else if (n == 1) { // trivial base case curRow = new int[1]; curRow[0] = 1; } else { // first get the previous row prevRow = row(n - 1); // now build the current row curRow = new int[n]; // the ends are both 1 curRow[0] = 1; curRow[n - 1] = 1; // now build the middle for (int i = 1; i < (n - 1); i++) { curRow[i] = prevRow[i - 1] + prevRow[i]; } } return curRow; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("This program prints the Nth"); System.out.println("line of Pascal's Triangle."); System.out.println("What is N? (type 0 to quit)"); int n = scan.nextInt(); while (n != 0) { if (n < 0) { System.out.println("N must be a positive number!"); } else { System.out.print("Answer:"); int[] nthrow = row(n); for (int i = 0; i < n; i++) { System.out.print(" " + nthrow[i]); } System.out.println(); } System.out.println("What is N? (type 0 to quit)"); n = scan.nextInt(); } } }