Printing Pascal Triangle seems like a easy problem, however, it isn't that easy to print a good-looking Pascal triangle.
To print the Pascal triangle, for each line, the "spaces" to "left of" numbers, and then print digit numbers.
To calculate Pascal numbers, two assays can is used:one array to store numbers of above, and the other array to store NU Mbers of this line. The has 1 number (1), the second lien has 2 numbers (1 1), the third line has three numbers (1 2 1) and.
To make the Pascal triangle more readable, print spaces between two neighbor numbers at the same line.
Pascal triangle #include <iostream> #include <iomanip> #include <cstring> using namespace std;
const int width=7; int main () {int* oldarr=new int[width];//store numbers of above row int* newarr=new int[width];//store numbers of C urrent row for (int i=0;i<width;++i)//Cntrol row counting {to (int j=0;j<width-i-1;++j)//left space cout
<<SETW (2) << "";
Set default boundary numbers newarr[0]=1;
if (i>=1) newarr[i]=1;
if (i>=2) {for (int k=1;k<i;++k) newarr[k]=oldarr[k-1]+oldarr[k];
} memcpy (oldarr,newarr,sizeof (int) *width);
Print the middle part int idx=0;
int flag= (width-i-1)%2;
for (int j=width-i-1;j<width+i;++j) {if (J%2==flag) {COUT<<SETW (2) <<newarr[idx++];
else {COUT<<SETW (2) << "";
}//for (int j=width+i;j<width;++j)//Print right spaces, if like//COUT<<SETW (4) << "";
cout<<endl; } Delete [] Oldarr;
delete [] newarr;
return 0;
}
The output looks like:
1
1 1
1 2 1 1 3 3 1 1 4 6 4 1 1-5 Ten 5 1
1 6 6 1