Pascal Triangle in Java code:
import java.util.Scanner;
class Pascal
{
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in); //making object of Scanner for input
int n;
System.out.println("Enter the no of rows to print : ");
n=sc.nextInt(); // taking integer input
int p[][]; // declaring 2-d Array
p= new int[n][]; // specifying size
for(int i=0;i<n;i++)
p[i] = new int[i+1]; // allocating memory
for(int i=0;i<n;i++)
{
p[i][0]=p[i][i]=1; // The edges are set by 1
for(int j=1;j<i;j++)
p[i][j]= p[i-1][j-1]+ p[i-1][j]; // logic of pascal triangle
}
System.out.println("\n\n");
for(int row[] : p) // for each row
{
for(int trm : row) // & inside for each column
System.out.printf("%5d",trm); // print result
System.out.println ();
}
}
}
No comments:
Post a Comment