I have to write a code that generates a pascal's triangle with 12 rows.
I've written everything on my own except one part, That's the formula we use to generate numbers. And the problem is I don't understand what's the connection between our counters and generated numbers (since we're using our counters.).
#include <iostream>
#include <string>
using namespace std;
int main() {
const int rows=12;
int padding, value, fxValue;
for(int rowCounter=0; rowCounter<rows; rowCounter++)
{
fxValue=1;
cout << string((rows-rowCounter)*6, ' ');
for(int fxCounter=0; fxCounter<=rowCounter; fxCounter++)
{
value=fxValue;
fxValue = fxValue*(rowCounter-fxCounter)/(fxCounter+1);
// cout << "fxCounter: "<< fxCounter << endl
// << "rowCounter: " << rowCounter << endl
// << "fxCounter: " << fxCounter << endl
// << "fxValue: " << fxValue << endl;
padding=fxValue/10;
if(padding==0) cout << value << string(11, ' ');
else if(10>padding) cout << value << string(10, ' ');
else if(padding>10) cout << value << string(9, ' ');
}
cout << endl;
}
return 0;
}
Here's the problem:
fxValue = fxValue*(rowCounter-fxCounter)/(fxCounter+1);
Can someone please explain how did the author came up with the idea of using these variables and how it works fine?
This works because Pascal's triangle can be represented with binomial coefficients :
This formula in your code is based on the fact that, on the same n-index (in the pascal's triangle case, same line), in order to get the next element (k -> k+1), we need to multiply the current value by (n-k)/(k+1):
It's fairly easy to prove if you want to convince yourself about that. So you can get the next value from the previous one with this operation.