C++ Code to Print Pascal Triangle
来源:互联网 发布:零基础数据库培训 编辑:程序博客网 时间:2024/05/21 17:45
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 rowint* newarr=new int[WIDTH]; // store numbers of current rowfor(int i=0;i<WIDTH;++i) // cntrol row counting{for(int j=0;j<WIDTH-i-1;++j) // left spacecout<<setw(2)<<" ";// set default boundary numbersnewarr[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 partint 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
0 0
- C++ Code to Print Pascal Triangle
- CODE 15: Pascal's Triangle
- [leet code] Pascal's Triangle
- CODE 14: Pascal's Triangle II
- [leet code] Pascal's Triangle II
- leetcode 日经贴,Cpp code -Pascal's Triangle
- [C++]LeetCode: 7 Pascal's Triangle
- [C++]LeetCode: 8 Pascal's Triangle II
- [leetcode-118]Pascal's Triangle(c++)
- [leetcode-119]Pascal's Triangle II (c++)
- 【leetcode c++】118 Pascal's Triangle
- [C语言][LeetCode][118]Pascal's Triangle
- 【LeetCode-119】 Pascal's Triangle II(C++)
- [C语言] leetcode 118. Pascal's Triangle
- Pascal Triangle
- Pascal Triangle
- leetcode 日经贴,Cpp code -Pascal's Triangle II
- Leet Code OJ 118. Pascal's Triangle [Difficulty: Easy]
- Scrapy:Spider参数及其应用场景
- shell 函数参数传递
- JS为什么有时候要做两次encodeURI
- 【转载】Cgroup用法解析
- Java 与flex 数据类型对照表
- C++ Code to Print Pascal Triangle
- 代码比较工具
- javaweb项目命名规范
- 地球坐标系 (WGS-84) 到火星坐标系 (GCJ-02)百度坐标系 (BD-09) 的转换算法
- 工作10个月,做地图插件的感悟——理论篇
- 我在这里
- jdk安装及开发环境部署
- Shell编程:在当前目录下遍历所有文件和子目录及子目录下的文件
- Java NIO框架Netty教程(十一)-并发访问测试(上)