-
Need help with spacing
I have a program that prints out pascal's triangle. One problem: it isn't a triangle. The output doesn't work. This is what it should print:
Code:
How many rows: 4
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
and this is what it does print:
Code:
Enter a number of rows: 4
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Can someone help me get the spacing right? My code is:
Code:
#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;
}
}
-
-
Code:
cout << " " << "1";
This is your code for outputting the initial spaces. So it should be clear why the code is doing what it's doing now. It just outputs 12 spaces every time.
The question is, how can you figure out how many spaces to put for each row? You should first ask yourself how you'd do it if you were drawing the pyramid yourself. How many spaces should be in the beginning of the first row if the user inputs 4? What if the user inputs 2? What if they input 1? Can you find a pattern? If you can find a pattern, you can then try to put that pattern into code.
-
I almost have it now, it just prints too many spaces to the left.
Code:
#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 << setw(3 * (rows - r) + 1) << '1';
for(int c = 1; c < r+1; c++) {
cout << setw(6) << combinations(r, c);
}
cout << endl;
}
}