0

I need some help with a program that prints Pascal's Triangle in c++. I need the spacing to look like this:

How many rows: 4
             1
          1     1
       1     2     1
    1     3     3     1
 1     4     6     4     1

but instead it looks like this:

Enter a number of rows: 4
        1
        1           1
        1           2            1
        1           3            3            1
        1           4            6            4            1

My code is:

#include <iostream>
#include <iomanip>
using namespace std;

int combinations (int n, int k) {
    if (k == 0 || k == n) {
        return 1;
    }
    else {
        return combinations(n-1,k-1) + combinations(n-1,k);
    }
}

int main ( ) {
    int rows;
    cout << "Enter a number of rows: ";
    cin >> rows;
    for(int r = 0; r < rows+1; r++) {
        cout << "            " << "1";
        for(int c = 1; c < r+1; c++) {

            cout << "           " << combinations(r, c) << ' ';

        }
        cout << endl;
    }
}

Can someone help me get the spacing right?

user1118321
  • 25,567
  • 4
  • 55
  • 86
Kelton2
  • 1
  • 3
  • 1
    The way you put the question makes it look like you did not try anything to solve that particular issue. – E_net4 Jan 21 '15 at 00:33
  • I did try quite a few things, but I couldn't figure out how to get it working. I tried various combinations of << setw, for example. – Kelton2 Jan 21 '15 at 00:34
  • I've written a solution for this in the past for another post. You can check it out at http://stackoverflow.com/questions/19898756/pascals-triangle-using-mainly-functions-in-c/ – Mars Feb 13 '15 at 03:55

1 Answers1

1

Looks like the main difference is the spacing at the front, which you have constant but shouldn't be:

cout << "            " << "1";

Instead, if you count the number of spaces at the front in your desired output, you'll notice that it decreases by 3 every row. So:

for (int s = 0; s < 3 * (rows - r) + 1; ++s) {
    cout << ' ';
}
cout << '1';

Or just:

cout << std::string(3 * (rows - r) + 1, ' ');

Also printing each element is incorrect. Instead of:

cout << "           " << combinations(r, c) << ' ';

You want this: (five spaces in beginning, no spaces at end):

cout << "     " << combinations(r, c);

Or, for clarity:

cout << std::string(5, ' ') << combinations(r, c);

None of that, however, would handle multiple-digit values, so really the right thing to do is use setw:

cout << setw(3 * (rows - r) + 1) << '1';
// ..
cout << setw(6) << combinations(r, c);
Barry
  • 286,269
  • 29
  • 621
  • 977
  • That's almost right (and I see where I made my mistake) but it is still too many spaces to the left. Is it as simple as adding a setw? – Kelton2 Jan 21 '15 at 00:38
  • @Kelton2 Actually `setw` would be better - since that handles multiple-digits. Updated. – Barry Jan 21 '15 at 00:42