Java Online Compiler
Example: Pascal's Triangle using nCr in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Pascal's Triangle using nCr import java.util.Scanner; // Main class containing the entry point of the program public class Main { // Helper function to calculate nCr public static long nCr(int n, int r) { if (r < 0 || r > n) { return 0; // Invalid combination } if (r == 0 || r == n) { return 1; // Base case } if (r > n / 2) { r = n - r; // Optimization: C(n,r) = C(n, n-r) } long res = 1; for (int i = 0; i < r; i++) { res = res * (n - i) / (i + 1); } return res; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of rows for Pascal's Triangle: "); int numRows = scanner.nextInt(); // Step 1: Iterate through each row for (int i = 0; i < numRows; i++) { // Step 2: Print leading spaces for triangular alignment for (int k = 0; k < numRows - i - 1; k++) { System.out.print(" "); } // Step 3: Iterate through each element in the current row for (int j = 0; j <= i; j++) { // Step 4: Calculate and print the binomial coefficient nCr System.out.print(nCr(i, j) + " "); } System.out.println(); // Move to the next line after each row } scanner.close(); } }
Output
Clear
ADVERTISEMENTS