Pascal Triangle In Java

Hello everyone..!! this post will explain pascal triangle in java.

First let us understand what is pascal’s triangle? and how it is used in java example??

what is PASCAL’S triangle?

Pascal triangle is a triangle of numbers arranged in the form of a triangle. It is named after french mathematician Blaise Pascal. Pascal triangle looks like this,

        1        
      1   1      
    1   2   1    
  1   3   3   1  
1   4   6   4   1

As you can see in the above triangle, the triangle has five rows and the first row starts with digit 1. Then each digit in a row is the sum of left digit and right digit on above row. Suppose, if a digit is missing in the above row, it is assumed as 0.

NOTE:

  • diagonals adjacent to the border diagonals contain natural numbers in an order.
  • sum of numbers in each row is twice the sum of numbers in above row.

example: Pascal Triangle In Java

Pascal Triangle In Java

Also Read – Matrix Transpose In Java

public class Pascal_Triangle_In_Java {

public static void main(String[] args) {
 
int triangle[][] = new int[5][];
pascal(triangle);
show(triangle);
}
 
public static void pascal(int triangle[][]){

for(int a = 0;a < triangle.length;a++)
{
triangle[a] = new int[a + 1];
triangle[a][0] = 1;
triangle[a][a] = 1;
 
for(int b = 1;b < a;b++)
{
triangle[a][b] = triangle[a - 1][b - 1] + triangle[a - 1][b];
}
}
}
 
public static void show(int triangle[][]){

for(int a = 0;a < triangle.length;a++)
{
for(int b = 0;b < triangle[a].length;b++)
{
System.out.print(triangle[a][b] + " ");
}
System.out.println();
}
}
}

Output:

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

About the author

admin

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *