Pascal Triangle in Java
Display five rows of Pascal's triangle in Java using an nCr helper with product and division steps. Rows are left-aligned; larger rows can overflow int.
1public class Main {2 private static int nCr(int n, int r) {3 int res = 1;4 for (int i = 0; i < r; i++) {5 res = res * (n - i) / (i + 1);6 }7 return res;8 }910 public static void main(String[] args) {11 int rows = 5;12 for (int i = 0; i < rows; i++) {13 for (int j = 0; j <= i; j++) {14 System.out.print(nCr(i, j) + " ");15 }16 System.out.println();17 }18 }19}
Sample Output
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
The row indices 0 to 4 produce 1,2,3,4,5 values. The last row has the symmetric values 1 4 6 4 1.
In this one
- Connect pattern values to combinations
- Use zero-based row numbers
- Preserve multiplication and division order
How it works
- 1
Set rows to 5.
- 2
Visit row i from 0 through 4.
- 3
For each j from 0 through i, calculate nCr(i, j).
- 4
Print the values and finish with a newline.
Edge cases
First row
Use i = 0 and j = 0
The helper loop is skipped and returns 1.
Many rows
Increase rows greatly
int calculations can exceed their range. This small teaching helper is not a large-combination calculator.
What's going on
Print the first five rows of Pascal's triangle. Each row starts and ends with 1, and an inner value equals the two values above it added together. These numbers also count combinations, which means ways to choose items without caring about order.
The helper nCr computes the number of ways to choose r items from n. It starts res at 1 and updates a product and division together for each step. main treats the first row as row 0 and calls nCr(i, j) for positions j from 0 through i.
This version prints left-aligned rows, not a centred picture. Row 4 is 1, 4, 6, 4, 1. The helper avoids writing a factorial calculation, but its int arithmetic still has a size limit. Keep the sample small. Dividing too early in the update could discard a fraction and change the result, so retain the multiplication-before-division order shown.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is the middle value of row 4?
Pick an answer to check it.
Question 2
How many values are in zero-based row i?
Pick an answer to check it.
Questions people ask
Why does the first row use zero?
nCr(0,0) is 1, which naturally represents the first row.
Why are rows not centred?
The code adds spaces only between values; it does not print leading alignment spaces.
What is nCr counting?
It counts selections of r items from n when order does not matter.