Question: In Java using Eclipse, implement a class to recursively calculate the n-th line of Pascal's Triangle which should produce this following output: 1: 1 2:
In Java using Eclipse, implement a class to recursively calculate the n-th line of Pascal's Triangle which should produce this following 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
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 from my homework that will call the method you write.
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) { return new int[]{0}; } } Output:
1: 0
Here is the code I got from Chegg:
class Main
{
// nested class pascal
static class Pascal
{
// calculate and rint the n th line
public static void triangle(int n)
{
int i, j;
// loop n times
for (i = 0; i < n; i++)
// if it is the required line
if (i == n - 1)
// calculate each value in the i th line
for (j = 0; j <= i; j++)
// get the j th value in i th line
System.out.print(currentValue(i, j) + " ");
}
// get the j th value in i th line
public static int currentValue(int i, int j)
{
// if it is the first term or the last term of i th line
if (j == 0 || j == i)
return 1;
// recursively get the other terms in the i th line
return currentValue(i - 1, j - 1) + currentValue(i - 1, j);
}
}
public static void main(String[] args)
{
int n = args.length == 1 ? Integer.parseInt(args[0]) : 1;
for (int i = 1; i <= n; ++i)
{
Pascal.triangle(i);
System.out.println();
}
}
}
And unlike the sample code from chegg, this is what I got from Eclipse
Output:
1
Can you help find out how to fix this code so that I can produce this output?
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
