-1

How do I print this pattern modifying my original code below:

I am a beginner in java and not able to create the pattern listed below.

Pattern:

1
1 ,1
1 ,2 ,1
1 ,3 ,3 ,1
1 , 4 , 6 , 4 , 1
1 , 5 , 1 0 , 1 0 , 5 , 1

My Code:

public class Q2 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int count = 5;
        for (int i = 1; i <= count; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(i);
            }
            System.out.println();
        }
    }
}

My Output:

1
22
333
4444
55555
Aniruddh Parihar
  • 3,072
  • 3
  • 21
  • 39
applehacker321
  • 35
  • 1
  • 1
  • 4
  • 2
    It's called Pascal's Triangle. Read up on how it works: https://en.wikipedia.org/wiki/Pascal%27s_triangle – markspace Jul 13 '18 at 02:48
  • If you Google it,you will find answer more quickly,you can see this https://stackoverflow.com/questions/19918994/pascals-triangle-format – flyingfox Jul 13 '18 at 03:04
  • http://www.javawithus.com/programs/pascal-triangle – Kartik Jul 13 '18 at 03:23
  • Does this answer your question? [Pascal's triangle 2d array - formatting printed output](https://stackoverflow.com/questions/8935254/pascals-triangle-2d-array-formatting-printed-output) –  Jun 24 '21 at 09:41

2 Answers2

1

I wish I could comment but I don't have enough reputation.

You need to add something to Yimin's answer to calculate the factorial, for example.

static int factorial(int n){    
    if (n == 0)    
        return 1;    
    else    
        return(n * factorial(n-1));
}
0

What you want is i choose j for each term. This is by formula:

i!/(j!*(i-j)!)
public static void main(String[] args) {
    int count = 5;
    for (int i = 0; i <= count; i++) {
        for (int j = 0; j <= i; j++) {
            System.out.print(factorial(i) / (factorial(j) * factorial(i - j)));
            System.out.print(' ');
        }
        System.out.println();
    }
}
Pawel Veselov
  • 3,996
  • 7
  • 44
  • 62
Yimin Rong
  • 1,890
  • 4
  • 31
  • 48