C++: Detailed explanation of the console output Yang Hui triangle

Yanghui triangle

First of all, the Yang Hui triangle is as follows:
Starting from the third row, all the numbers in the middle are equal to the sum of the two digits on its "shoulder" except for 1 at the beginning and the end.

Insert picture description here

Q: Then how to use the console to output Yang Hui triangle?
Idea one:

First list
Insert picture description here
the places where there is no value and fill it with 0.
Insert picture description here
Then you can dynamically create two one-dimensional arrays a and b, one for the output of the current column; one for recording the value of the previous column and assigning a value to the next column. In the 0th and 1st rows, the b array always copies the value of the a array. When the second line is reached, the usefulness of the b array begins, because if a plus the value of the previous number is paid to a, the original value is gone, and the following error will occur when recirculating:
Insert picture description here
So the existence of the b array is To avoid this from happening.
Using two arrays can reduce the storage space used to build a two-dimensional array as a table and improve efficiency.

Source code:
yang is a defined method, written in the file of the entry function main, and needs to be defined before calling.
The following code can run in the vs2019 community edition.

//*************code by senlinxing
#include <iostream>
using namespace std;
void yang(int n)
{
    
    
    int* a = new int[n];//这里是动态分配数组,因为直接int a[n]是不对的,中括号里的是常量不是变量
    int* b = new int[n];//记录上一行的数组
    for (int x = 0; x < n; x++)
    {
    
    
        a[x] = 0;//初始化
        b[x] = 0;//初始化
    }
    for (int i = 0; i < n; i++)//行
    {
    
        
        for (int j = 0; j < i + 1; j++)//列
        {
    
    
            if (i < 2)
            {
    
    
                a[j] = 1;
                b[j] = 1;
                cout << a[j] << " ";
            }
            else
            {
    
    
                if (j == 0)
                {
    
    
                    a[j] = a[j] + a[n - 1];//第2(行从0开始)行开始第一个数字的上方两位是它本身列号和最后一列的相加
                    b[j] = a[j];
                    cout << a[j] << " ";
                }
                else
                {
    
     
                    b[j] = a[j];
                    a[j] = b[j] + b[j - 1];
                    cout << a[j] << " ";                   
                }
            }
        }
        cout << endl;        
    }
}
int main()
{
    
    
    yang(6);//参数是输出的杨辉三角行数
    return 0;
}
//*************

Running effect:
output 6 lines of Yanghui triangle
Insert picture description here
output 20 lines
Insert picture description here
or more.
(Ps: I didn’t write the logic completely in the written test, so I should knock my head)

Guess you like

Origin blog.csdn.net/liangzixx/article/details/109102554