Search code examples
c++algorithmmathbinomial-coefficients

C++: How do I produce the 'nth' line of Pascal's Triangle?


Here is my code:

#include <iostream>
using namespace std;

int main()
{
    int n,k,i,x;
    cout << "Enter a row number for Pascal's Triangle: ";
    cin >> n; 
    for(i=0;i<=n;i++)
    {
        x=1;
        for(k=0;k<=i;k++)
        {
            cout << x << '\t';
            x = x * (i - k) / (k + 1);
        }
    cout << endl;
    }
    return 0;
}

How do I change this so that it only displays the nth line instead of the whole triangle? TIA.


Solution

  • Just remove the outer loop:

    int main()
    {
        cout << "Enter a row number for Pascal's Triangle: ";
        cin >> n; 
        int x = 1;
        for (int k = 0; k <= n; k++)
        {
            cout << x << '\t';
            x = x * (n - k) / (k + 1);
        }
        cout << endl;
        return 0;
    }