C++ Code to Print Pascal Triangle

Printing Pascal Triangle seems like an easy problem, however, it is not that easy to print a good-looking Pascal Triangle. 

To print the Pascal Triangle, for each line, first print spaces to the left of numbers, and then print digit numbers.

To calculate Pascal numbers, two assays can be used: one array to store numbers of above line, the other array to store numbers of this line. The first line has 1 number(1), the second lien has 2 numbers(1 1), the third line has three numbers(1 2 1) and so on.

To make the Pascal Triangle more readable, print spaces between two neighbor  numbers in 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 current row

	for(int i=0;i<WIDTH;++i) // cntrol row counting
	{
		for(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 space, if you 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  10  10   5   1
 1   6  15  20  15   6   1


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值