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

5.6k views Asked by At

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.

4

There are 4 answers

0
Jarod42 On BEST ANSWER

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;
}
0
Michael Laszlo On

The following is an efficient way to generate the nth row of Pascal's triangle.

Start the row with 1, because there is 1 way to choose 0 elements.

For the next term, multiply by n and divide by 1. That's because there are n ways to choose 1 item.

For the next term, multiply by n-1 and divide by 2. There are n*(n-1) ways to choose 2 items, and 2 ways to order them.

For the next term, multiply by n-2 and divide by 3. There are n*(n-1)*(n-2) ways to choose 3 items, and 2*3 ways to order them.

And so on.

We stop once we have multiplied by 1 and divided by n.

#include <iostream>
using namespace std;

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

Change cout << x << '\t'; to

if(i == n) cout << x << '\t';  // Print only last line (i = n)

And cout << endl; to

if(i == n) cout << endl;  // Print after only last line (i = n)
1
Himanshu On

You need to enter value of nth line

int i =nth Line;
for(k=0;k<=i;k++)
{
    count<<fact(i)/(fact(k)*fact(i-k))<<"\t";
}


int fact(int a)
{
    int j=1;
    for(int i=a;i>1;i--)
    {
        j*=a;
        a--;
    }
    return j;
}

Value of i start from 0
For i=6

Output will be 1 6 15 20 15 6 1