Pascal's Triangle

In this blog, we will discuss Pascal's triangle. Pascal's triangle is a triangular arrangement of numbers that provides the coefficients within the expansion of any binomial expression. The triangle can be constructed by first placing 1 along the left and right edges and then triangle can be filled out from the top by adding two numbers just above to the left and right of each position in the triangle. Implementation Using Java: import java.util.Scanner;
public class PascalTriangle {
public static int nCr(int n, int r)
{
return fact(n)/(fact(r)*fact(n-r));
}
public static int fact(int n)
{
if(n==0||n==1)
{
return 1;
}
return n*fact(n-1);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter number of rows:");
int n=sc.nextInt();
for(int i=0;i<n;i++)
{
for(int j=n-i;j>0;j--)
{
System.out.print(" ");
}
for(int k=0;k<=i;k++)
{
System.out.print(nCr(i,k));
}
System.out.println();
}
}
} Output:
Enter number of rows: 7
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1 Happy Coding! Follow us on Instagram @programmersdoor Join us on Telegram @programmersdoor Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem. Follow Programmers Door for more. #blog #interview #placement #learn #computer #science

        Contact Us

programmersdoor@gmail.com

  • LinkedIn
  • Facebook
  • Instagram

©2023 by Programmers Door