Get up to 80 % extra points for free! More info:

Discussion: Need help in solving pascal triangle problem

In the previous quiz, C++ online test, we tested our experience gained from the course.

Activities
Avatar
Patrica Millie:7/30/2018 9:29

Hi all,

I need help in solving the pascal triangle problem -

Given numRows, generate the first numRows of Pascal’s triangle.

Pascal’s triangle : To generate A[C] in row R, sum up A’[C] and A’[C-1] from previous row R - 1.

Return

[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

 
Reply
7/30/2018 9:29
Avatar
Samuel Kodytek
Creator
Avatar
Samuel Kodytek:7/30/2018 11:21

Hi!

I tried googling a bit ( https://www.geeksforgeeks.org/…al-triangle/ ) and got this result, with a decent explanation:

#include <stdio.h>

// See https://www.geeksforgeeks.org/archives/25621
// for details of this function
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");
    }
}

// See https://www.geeksforgeeks.org/archives/25621
// for details of this function
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;
}

Hope I helped!

 
Up Reply
7/30/2018 11:21
To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

2 messages from 2 displayed.