Java Pascal Triangle
I have given here Java code to build a pascal triangle. It uses simple nested for loops and Console.WriteLine functions. The input would be the number of rows in the pascal triangle.
Source Code
import java.lang.*;
import java.util.*;
import java.io.*;
class PascalTriangle
{
public static int ReadInteger()
{
try
{
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
return Integer.parseInt(reader.readLine());
}
catch (Exception e)
{
e.printStackTrace();
return 0;
}
}
public static void main(String[] args)
{
System.out.println("Pascal Triangle Program");
System.out.print("Enter the number of rows: ");
int n = ReadInteger();
for (int y = 0; y < n; y++)
{
int c = 1;
for (int q = 0; q < n - y; q++)
{
System.out.print(" ");
}
for (int x = 0; x <= y; x++)
{
System.out.format(" %3d ", c);
c = c * (y - x) / (x + 1);
}
System.out.println();
System.out.println();
}
System.out.println();
}
}
Output
|