C Online Compiler
Example: Pascal's Triangle using nCr in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Pascal's Triangle using nCr #include <stdio.h> // Function to calculate factorial long long factorial(int n) { long long res = 1; for (int i = 2; i <= n; i++) { res *= i; } return res; } // Function to calculate nCr long long nCr(int n, int r) { if (r < 0 || r > n) { return 0; // Invalid combination } return factorial(n) / (factorial(r) * factorial(n - r)); } int main() { int rows = 5; // Number of rows to generate printf("Pascal's Triangle (nCr approach):\n"); // Step 1: Iterate through each row for (int i = 0; i < rows; i++) { // Step 2: Print leading spaces for triangular shape for (int space = 0; space < rows - i - 1; space++) { printf(" "); } // Step 3: Iterate through each element in the current row for (int j = 0; j <= i; j++) { printf("%lld ", nCr(i, j)); // Calculate and print nCr } printf("\n"); // Move to the next line for the next row } return 0; }
Output
Clear
ADVERTISEMENTS