-1

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.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
podomunro
  • 495
  • 4
  • 16
  • 2
    Use binomial coefficient calculation – Mohit Jain Nov 27 '14 at 11:59
  • 7
    You just copied someone else's code from [here](http://www.cplusplus.com/forum/general/56615/). And without trying to understand it, you want people to modify it for you to fit your homework assignment. If you did try to understand it, you'd see that the change is trivial. – interjay Nov 27 '14 at 12:24
  • @interjay: that sounds bad, but I guess you're right. It's really soo trivial... shame on you, user! :) – davidhigh Nov 27 '14 at 12:45

4 Answers4

7

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;
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
1

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)
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
1

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;
}
Michael Laszlo
  • 12,009
  • 2
  • 29
  • 47
0

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

Himanshu
  • 4,327
  • 16
  • 31
  • 39