Question: My assignment: Design and implement a recursive program to determine and print the Nth line of Pascals Triangle, as shown below. Each interior value is
My assignment: Design and implement a recursive program to determine and print the Nth line of Pascals Triangle, as shown below. Each interior value is the sum of the two values above it. Hint: Use an array to store the values on each line.
Ive got it kind of working but i dont know how to compute it an array.
Please help and provide the working program.
import java.util.Scanner;
public class PascalTriangle { public static void computeRow(int n) { int counter; for (int i = 0; i < n; i++) { if (i == n-1) { for (int p = 0; p <= i; p++) System.out.print(pascalValue(i, p) + " "); } System.out.println(); } }
public static int pascalValue(int i, int p) { if (p == 0) { return 1; } else if (p == i) { return 1; } else { return pascalValue(i - 1, p - 1) + pascalValue(i - 1, p); } }
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Line number: "); int row = scanner.nextInt(); System.out.print("Line " +row+" of Pascal's Triangle: "); computeRow(2); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
