Friday, 29 August 2014

Print Pascal Triangle using java programming


Pascal Triangle is a number triangle where each number in a row is the sum of two number in above row. If any number is missing then it is taken as 0. Triangle is start with 1 in the top. Let’s see a Pascal Triangle
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1
In above triangle we draw a 5 rows. As we can see that two side of triangle is 1. Now pic up any number in any row, for example we take 6 in last row. Now look above of that row. Number above 6 is 3 at right and 3 at left. Now 6 is equal to 3+3. Now same thing is applied for any number.
Now let’s write java code

public class pascal {
public static void main(String args[])
{
int y=6;
int x=y+1;
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][0]=1;
                }
for(int i=1;i<x;i++)
{
for(int j=1;j<i;j++)
{
if(i==j)
{ triangle[i][j]=1;
}
else
{ triangle[i][j]=triangle[i-1][j-1]+triangle[i-1][j];
}
}
}
for(int i=0;i<x;i++)
{
for(int j=0;j<i;j++)
{
System.out.print(triangle[i][j]+" ");
}
System.out.println(" ");
}
}
}
Output of above program is

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
In above program we use “triangle[][]” which is a 2d array.

0 comments:

Post a Comment