Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Pascal Triangle

Sharing is caring!

Problem Statement
The figure below illustrates the first five rows of a graphic that is known as Pascal’s triangle. Each entry in each row before the last one is adjacent to one or two numbers in the lower row. It is a fact that each entry holds the sum of the numbers in the adjacent entries above it.
Write a program which takes as input a nonnegative integer n and returns the first n rows of Pascal’s triangle.

Solution
public class PascalTriangle2 {

    private static void solve(int rows) {
        int[] previousRow = new int[rows];
        previousRow[0] = 1;

        for (int r=1; r<=rows; r++) {
            System.out.format("%"+(rows-(r-1))*2+"s","");

            System.out.print("1 ");
            int[] temp = new int[rows];
            temp[0] = 1;
            for (int c=1; c<r; c++) {
                int out = previousRow[c-1] + previousRow[c];

                System.out.format("%4d",out);

                temp[c] = out;
            }

            previousRow = temp;
            System.out.println();
        }
    }

    public static void main(String[] args) {
        solve(5);
    }
}