優點:只需要與楊輝三角形行數相同的存儲空間。
缺點:因為數組長度不能在運行時確定,所以楊輝三角形的長度不能通過用戶自行輸入確定。
#include<iostream>
using namespace std;
const int N = 10;
int main()
{
int a[N]={0};
a[0]=1;
for(int i=1; i!=N;++i)
{
int m = N - i;
//輸出空格
while(m != 0 )
{
cout << " ";
--m;
}
//輸出
for(int j=0;j != i;++j)
cout << a[j] << " ";
cout << endl;
//賦值
a[i]=1; //最后一個元素賦值1
for(int j=i-1;j!=0;--j)
a[j]=a[j]+a[j-1];
}
return 0;
}

文章來源:http://liyuxia-life.spaces.live.com/Blog/cns!DA1B364675ACF35!270.entry