Adeel Ahmad
Adeel Ahmad

Reputation: 1053

Printing binomial coefficients using pascals triangle

The question is this:

Binomial coefficients are the numeric factors of the products in a power of a binomial such as (x + y) * n. For example, (x + y) * 2 = 2 x + 2 x y + 2 y has the coefficients 1 2 1. Binomial coefficients can be calculated using Pascal's triangle:

Each new level of the triangle has 1's at the ends; the interior numbers are the sums of the two numbers above them. I have to write a program that includes a recursive function to produce a list of binomial coefficients for the power n using the Pascal's triangle technique.

Here is the code. I need to get the output 1 2 1 if input x is 2, but the output is not correct.

#include <iostream>
using namespace std;
int pascal(int n, int x){
    if ((n==0) || (n==1) || (n==x))
        return 1;
    else
        return pascal(n, x-1) + pascal(n, x-1);
}
int main()
{
    int x;
    cout << "Input the number of which you want to print the binomial coefficients : ";
    cin >> x;
    int n = 0;
    for (int i=0; i<x; ++i)
        cout << pascal(n, x) << " ";
}

Upvotes: 0

Views: 1261

Answers (1)

jensa
jensa

Reputation: 2890

A good rule of thumb is that whenever you pass a variable to a function and its value is to remain constant, pass it as a constant. Then mishappens like

n=1

instead of

n==1

can't happen, because the compiler won't allow it.

int pascal(const int n, const int x)
{
    if(n == 0 || n == 1 || x == 0 || x == n)
        return 1;
    return pascal(n-1, x-1) + pascal(n-1, x);
}

Note the

const int n, const int x

rather than

int n, int x

in the function head.

Output

int main()
{   
    for(int n=0;n<12;++n){
        std::cout << "n = " << n << ": ";
        for(int x=0;x<=n;++x){
            std::cout << pascal(n, x) << ' ';
        }
        std::cout << std::endl;
    }
    return 0;
}

Upvotes: 1

Related Questions