Hello guys I need some help about the Pascal's Triangle. It's not about showing an output of the triangle itself but it's a little different.

The user will be asked to choose a row number in the triangle. After that, it will output the sum of all the values above the given row and another output which has the sum of all the numbers on the next row given. Please help me.

Here is the Pascal's Triangle that I know so far.

``````public class PascalTriangle {
public static void main(String args[]) {
int x = 10;
int triangle[][] = new int[x][x];
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
triangle[i][j] = 0;
}
}
for(int i = 0; i < x; i++) {
triangle[i] = 1 ;
}
for (int i = 1; i < x; i++) {
for (int j = 1; j < x; j++) {
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];
}
}

}
}``````

## Recommended Answers

What does the current code do? What is wrong with the results?
Show the output and explain/show what it should be.

## All 4 Replies

What does the current code do? What is wrong with the results?
Show the output and explain/show what it should be.

Hello sir! Sorry for the late reply.
This code will make a Pascal's triangle as a value.

The problem that I have is like this:

Row 1: 1
Row 2: 1 1
Row 3: 1 2 1
Row 4: 1 3 3 1
Row 5: 1 4 6 4 1

I am asked to input a row number, let's assume that I entered 4.

It will output the sum of all the numbers above Row 4 which is 7(1+1+1+1+2+1) and then the row below the given row. The sum of all the numbers in the next row which is Row 5 will
be given as an output which is 16 (1+4+6+5+1). Please help me sir.

Where is your code?

What you need to do is to think about how you really build a pascal triangle manually before you can implement in a code. Your current code has flaws.

1) You do not need to create 2D array to accommodate a triangle. If you look at it, about half of the memory space you acquire for your variable is used, and the other half is empty. A dynamic array would be OK.
2) You could either build and save all value of the triangle, or keep value only the previous and current rows you are working on. The easiest way is to keep all in a dynamic array, such as ArrayList.
3) In each row, you need to compute the added value from the previous row up to half of the row. The other half, you just copy it in reverse order.
4) Do not attempt to find out the problem's result value until you can complete building your triangle.
5) Do not forget that you need to build 1 more row from whatever a user specifies in order to compute the total value of the "after" row.

Hope this help you to think a bit further. Please get back with some code you implement with more of your thought.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.