Number Triangle Pattern Program in Java



Number Triangle Pattern Program in Java

Method 1

Sample Code

import java.util.*;
public class numbertriangle {
  public static void main(String[] args) {
    int i, j, n;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the no of lines");
    n = sc.nextInt();
    for (i = 1; i <= n; i++) {
      for (j = 1; j  <= n - i; j++)
        System.out.printf(" ");
      for (j = 1; j  <= i; j++)
        System.out.print(j);
      for (j = i - 1; j  >= 1; j--)
        System.out.print(j);

      System.out.println();
    }
  }
}

Output

Enter the no of lines 5
        1
      121
    12321
  1234321
123454321

Method 2

Sample Code

import java.util.*;
public class pascaltriaangle {
  public static void pascal(int n) {
    for (int line = 1; line <= n; line++) {
      for (int j = 0; j <= n - line; j++) {

        System.out.print(" ");
      }

      int C = 1;
      for (int i = 1; i <= line; i++) {

        System.out.print(C + " ");
        C = C * (line - i) / i;
      }
      System.out.println();
    }
  }

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the number of rows ");
    int n = sc.nextInt();
    pascal(n);
  }
}

Output

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

Related Searches to Number Triangle Pattern Program in Java