Pascal Triangle in java
The pattern similar to Floyed triangle, there is another triangle
is called Pascal triangle named after famous
French mathematician Blaise Pascal. But it has a little bit different. Here
each row is the summation of the left value and a right value of the previous
row. if the above row value is missing then it is taken as 0.
The formula is co = co * (i - j + 1) / j Where i
is the row number and j is the element position in that row.
Java program for Pascal triangle
import java.util.*;
public class PascalTriangle
{
public
static void main(String args[])
{
int
rows, co, i, j;
co
= 1;
Scanner sc = new Scanner (System.in);
System.out.println("Enter the number of rows");
rows = sc.nextInt();
for(i = 0; i < rows; i++)
{
// print the space
for(j = 1; j < rows - i; j++)
{
System.out.print(" ");
}
// print value
for(j = 0; j <= i; j++)
{
if (j == 0 || i == 0)
{
co = 1;
}
else
{
co = co * (i - j + 1) / j;
}
// row print
System.out.print(co + " ");
}
System.out.println();
}
} //
end of the main() method
} // end of the class
Output
Enter the number of rows
6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Java program for Pascal triangle with recursive method
import java.util.*;
public class PascalTriangleRecursiveMethod
{
//instance variable;
int i,
j, k;
public
void printRow(int n)
{
for
(i = 0; i < n; i++)
{
for (k = 0; k < n - i; k++)
{
// print the space
System.out.print(" ");
}
for (j = 0; j <= i; j++)
{
System.out.print(pascalTriangle(i, j) + " ");
}
System.out.println();
}
}
public
int pascalTriangle(int i, int j)
{
if
(j == 0 || j == i)
{
return 1;
}
else
return pascalTriangle(i - 1, j - 1) + pascalTriangle(i - 1, j);
}
public
static void main(String[] args)
{
int
rows;
PascalTriangleRecursiveMethod ob = new PascalTriangleRecursiveMethod();
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows : ");
rows = sc.nextInt();
System.out.println("Pascal Triangle printed as:");
System.out.println("======================”);
ob.printRow(rows);
}
}
Output
Enter the number of rows: 5
Pascal Triangle printed as:
======================
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1