-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathPascalsTriangle.java
More file actions
38 lines (31 loc) · 980 Bytes
/
PascalsTriangle.java
File metadata and controls
38 lines (31 loc) · 980 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package Practice;
//To generate the Pascal's triangle for a given number of rows
import java.util.Scanner;
class C{
int fact(int n){ //To calculate the factorial of a number
int f=1;
for(int i=1;i<=n;i++)
f*=i;
return f;
}
int ncr(int n,int r) { //To find the combination i.e. the nCr for a given pair of numbers
int c = fact(n)/(fact(n-r)*fact(r));
return c;
}
}
public class PascalTriangle {
public static void main(String[] args) {
C c=new C();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of rows: "); //Taking the no. of rows input from the user
int n=sc.nextInt();
int i,j;
for(i=0 ; i<=n ; i++) { //Loop to print the spaces at the start of each row
for(j=0 ; j<=(n-i) ; j++)
System.out.print(" ");
for(j=0 ; j<=i ; j++) //Loop to print the binomial coefficients i.e. the numbers of the Pascal's triangle
System.out.print(" " + c.ncr(i,j));
System.out.println();
}
}
}