Create a Pascal Triangle using Java

On my last job interview, i was asked to create a very simple Pascal Triangle using java. What is a Pascal Triangle (indonesian people called it “Segitiga Pascal”) ?? According to Wikipedia, it is a triangular array of the binomial coefficients in a triangle. Okay this is how i do it.

package com.edw.test;

/**
 *  com.edw.test.PascalTriangle
 *
 *  @author edw
 */
public class PascalTriangle {

    public static void main(String[] args) {
        // initiate
        int numberOfRows = 8;
        int[][] pascal = new int[numberOfRows][numberOfRows];
         
        // fill my triangle
        for (int i = 0; i < numberOfRows; i++) {
            pascal[i][0] = 1;                        
            for (int j = 1; j <= i; j++) {
                pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
            }
        }

        // print it
        for (int i = 0; i < numberOfRows; i++) {
            for (int j = 0; j <= i; j++) {
                System.out.print(pascal[i][j] + " ");
            }
            System.out.println();
        }
    }
}

this is the result on my Netbeans’ console

hope it can help others
cheers :-[

Google+

2 Comments

Exile829

about 4 years ago

Thank you so much! (Y)

Reply

edwin

about 4 years ago

You're welcome

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked


:-[ (B) (^) (P) (@) (O) (D) :-S ;-( (C) (&) :-$ (E) (~) (K) (I) (L) (8) :-O (T) (G) (F) :-( (H) :-) (*) :-D (N) (Y) :-P (U) (W) ;-)