Pages

Friday, 2 June 2017

Pascal's Triangle using Java

import java.util.Scanner;

public class PascalsTriangle {

public static void main(String[] args) {
int rows,coef=1,space,i,j;
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of rows : ");
rows = s.nextInt();
for(i=0;i<rows;i++)
{
for(space=1;space<=rows-i;space++)
{
System.out.print("  ");
}

for(j=0;j<=i;j++)
{
if(i==0 || j==0){
coef=1;
}else{
coef=coef*(i-j+1)/j;
}

System.out.printf("%4d",coef);
}
System.out.println();
}
        s.close();
}
}

Output:

Enter the number of rows : 
5
             1
           1   1
         1   2   1
       1   3   3   1
     1   4   6   4   1


No comments:

Post a Comment

Code Review

 SOLID Principles S – Single Responsibility Principle There should never be more than one reason for a class to change. O – Open-Closed Prin...