Pascal's Triangle (First 5 Rows)
This program prints Pascal's Triangle using nested for loop.
Problem Statement
Write a Java program that prints first 5 rows of Pascal's Triangle using nested for loop.
Source Code
| 1 | public class PascalsTriangle { |
| 2 | public static void main(String[] args) { |
| 3 | int rows = 5; |
| 4 | for(int i=0; i<rows; i++) { |
| 5 | int num = 1; |
| 6 | for(int j=0; j<=i; j++) { |
| 7 | System.out.print(num + " "); |
| 8 | num = num * (i - j) / (j + 1); |
| 9 | } |
| 10 | System.out.println(); |
| 11 | } |
| 12 | } |
| 13 | } |
Program Output
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
Explanation
The outer loop controls the number of rows. The inner loop calculates binomial coefficients using the formula num = num * (i - j) / (j + 1). This demonstrates how nested loops can generate Pascal's Triangle, a classic mathematical sequence. Shows how nested for loops can generate Pascal's Triangle.