Skip to main content

ProwessApps

Learn · Practice · Excel

Write a program to print the following pattern:
1
1 1
1 2 1
1 3 3 1

Java Code Example — Pattern Programs

ADVERTISEMENT

Write a program to print the following pattern:
1
1 1
1 2 1
1 3 3 1

Objective

Write a Java program to print Pascal's Triangle using the factorial formula.

Algorithm / Approach

  1. Create a helper method fact(x) to calculate the factorial of a number.
  2. In the show() method, use an outer loop (i) from 0 to 5 for rows.
  3. Print leading spaces to format it as a pyramid.
  4. Use an inner loop (c) from 0 to i for columns.
  5. Calculate the value at that position using the combination formula: i! / (c! * (i - c)!).
  6. Print the value and a newline.
Test.java
class Test {
 int fact(int x) {
  int res = 1;
  for(int i = 1; i < x; i++) {
   res = res*i;
  }
  return res;
 }
 void show() {
  int y;
  for(int i=0; i<=5; i++) {
   for(int c = 0; c<=(5-i-2); c++) {
    System.out.print(" ");
   }
   for(int c =0; c<= i; c++) {
    y =fact(i)/(fact(c)*fact(i-c));
    System.out.print(y+" ");
   }
   System.out.println();
  }
 }
 public static void main(String[] a)
 {
  Test t = new Test();
  t.show(); 
 }
}

Explanation of the Program

  • Pascal's Triangle is a mathematical triangular array of binomial coefficients.
  • The value at any position (row i, column c) can be calculated mathematically using combinations (nCr).
  • The formula for nCr is n! / (r! * (n - r)!). The program delegates the factorial calculation to a separate helper method to keep the main logic clean.

Complexity

Time Complexity O(n3) - Due to calculating the factorial repeatedly for every cell.
Space Complexity O(1)
ADVERTISEMENT