C + + Code to Print Pascal triangle

Source: Internet
Author: User

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

		&LT;&LT;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&LT;&LT;SETW (2) <<newarr[idx++];
			else {COUT&LT;&LT;SETW (2) << "";

		}//for (int j=width+i;j<width;++j)//Print right spaces, if like//COUT&LT;&LT;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


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.