Kelton2
Kelton2

Reputation: 1

Spacing on a pascal's triangle program c++

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?

Upvotes: 0

Views: 1291

Answers (1)

Barry
Barry

Reputation: 303186

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);

Upvotes: 1

Related Questions