Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Pascal\'s Triangle Implement a program to recursively print out Pascal\'s Triang

ID: 3661640 • Letter: P

Question

Pascal's Triangle

Implement a program to recursively print out Pascal's Triangle:

Important questions to ask yourself:

What is the base case?

What is the recursive case?

What should the method return?

Your class should be called Pascal and have one static
method called triangle that takes an argument 'n' and
returns the n-th line of Pascal's Triangle.

Here is the code for the main method that
will call the method you write.

Result should look like Pascal's Triangle above and use recursive method for code. Please copy and paste your result.

This is what i have if anyone could help me fix it and finish it. Thank you.

public class Main {

public static void main(String[] args) {

int n = args.length == 1 ? Integer.parseInt(args[0]) : 1;

for (int i = 1; i <= n; ++i) {

int[] arr = Pascal.triangle(i);

System.out.print((i < 10 ? " " : "") + i + ": ");

for (int j : arr) {

System.out.print(j + " ");

}

System.out.println();

}

}

}

class Pascal

{

   public static int[] triangle(int n)

   {

   int[] cur = new int[n+1];

   if(n == 0)

   {

   cur[0] = 1;

      return cur;

   }

   int[] prev = triangle(n-1);

   cur[0] = cur[n] = 1;

   for(int i=1; i<prev.length; i++)

   {

       cur[i] = prev[i-1] + prev[i];

   }

   return cur;

   }

}

Explanation / Answer

Answer:

I have changes a little bit in code in Main Method

public class Main {

public static void main(String[] args) {

int n = args.length == 1 ? Integer.parseInt(args[0]) : 10;

for (int i = 0; i < n; i++) {
int[] arr = Pascal.triangle(i);
System.out.print((i < 10 ? " " : "") + (i+1) + ": ");
for (int j : arr) {
System.out.print(j + " ");
}
System.out.println();
}
}
}

class Pascal
{
public static int[] triangle(int n)
{
int[] cur = new int[n+1];

if(n == 0)
{
cur[0] = 1;
return cur;
}

int[] prev = triangle(n-1);
cur[0] = cur[n] = 1;
for(int i=1; i<prev.length; i++)
{
cur[i] = prev[i-1] + prev[i];
}
return cur;

}
}

Output:

1: 1
2: 1 1
3: 1 2 1
4: 1 3 3 1
5: 1 4 6 4 1
6: 1 5 10 10 5 1
7: 1 6 15 20 15 6 1
8: 1 7 21 35 35 21 7 1
9: 1 8 28 56 70 56 28 8 1
10: 1 9 36 84 126 126 84 36 9 1