28

C/C++ Program for Pascal’s Triangle.

program solution

#include <stdio.h>

  

int binomialCoeff(int n, int k);

  

// Function to print first n lines of Pascal's Triangle

void printPascal(int n)

{

    // Iterate through every line and print entries in it

    for (int line = 0; line < n; line++)

    {

        // Every line has number of integers equal to line number

        for (int i = 0; i <= line; i++)

            printf("%d ",

                    binomialCoeff(line, i));

        printf("\n");

    }

}

  

int binomialCoeff(int n, int k)

{

    int res = 1;

    if (k > n - k)

    k = n - k;

    for (int i = 0; i < k; ++i)

    {

        res *= (n - i);

        res /= (i + 1);

    }

      

    return res;

}

  

// Driver program 

int main()

{

    int n = 7;

    printPascal(n);

    return 0;

}

Output

      1

     1 1

    1 2 1

   1 3 3 1

  1 4 6 4 1

 1 5 10 10 5 1

1 6 15 20 15 6 1