Data Structuresand Algorithms Good OldJava AdvancedInterview Topics Cloud andDatabases Web Designand Development Must-knowTools Good ToKnow

## Pascals Triangle

Below is shown a Pascal's Triangle of height 11.
Basic idea in the pascal's triangle is that the value in any node is the sum of it's two parent.
So it's very close to a Fibonacci series where current value is defined in terms of two previous values. Code: We print the Pascal's Triangle line-by-line.
Current line is obtained from the previous line by the following simple rules:
1. Take the previous list of numbers and add 1 to it in the first place.
2. Loop in the previous list from index 1 to length-1 and replace each arr[i] with arr[i]+arr[i+1]
3. The modified list has more element by virtue of #1 and can be printed as the new list.

```
import java.util.ArrayList;
import java.util.List;

public class PascalsTriangle {

public static void main (String args[])
{
// some variable to print the pascal's triangle like a real triangle
int numRows = 20;
int maxNumLen = 8;
int maxNumLenFactor = maxNumLen/2;

// actual list
List <Integer> nums = new ArrayList<Integer> ();

// list manipulation and pretty-printing of the list
for (int i=1; i<=numRows; i++)
{
System.out.println("\n");
for (int j=2;j<maxNumLenFactor*(numRows-i); j++)
System.out.print(" ");

for (int j=1; j<nums.size()-1; j++)
{
int curr = nums.get(j);
int next = nums.get(j+1);
nums.set(j, curr+next);
System.out.print(String.format ("%8d", curr) + " ");
}
System.out.print(String.format ("%8d",nums.get(nums.size()-1)) + " ");
}
}
}

```

Like us on Facebook to remain in touch
with the latest in technology and tutorials!

Got a thought to share or found a
bug in the code?
We'd love to hear from you:

 Name: Email: (Your email is not shared with anybody) Comment: