Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize Yang Hui Triangle in C language

Shulou Source: shulou.com Published: 2022-06-02 04:36:57 10月05日 Update

This article introduces the relevant knowledge of "how to realize Yang Hui Triangle in C language". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Yang Hui Triangle-- C language implementation

Yang Hui Triangle:

Print Yang Hui triangle on the screen.

one

1 1

1 2 1

1 3 3 1

……

According to the above examples, we can see that:

1. The first and second numbers of each row are 1

two。 The rest is the sum of the numbers directly above and on the left.

Method 1: using two-dimensional array to realize

Ideas for solving the problem:

According to the law of Yang Hui triangle, we can define a two-dimensional array to realize the printing of Yang Hui triangle, in which the law of numbers is:

Data [I] [j] = data [I-1] [j] + data [I-1] [j-1], so we follow this method to fill the data into a two-dimensional array and print it.

The code is as follows:

# include int main () {int n; int data [30] [30] = {1}; / / fill in the first line directly to 1 printf ("Please enter the number of lines to print: >"); scanf ("% d", & n); for (int I = 1; I

< n; i++)//从第二行开始填 { data[i][0] = 1;//将每一行第一列先初始化为1,防止越界 for (int j = 1; j < i + 1; j++) { data[i][j] = data[i - 1][j] + data[i - 1][j - 1]; } } for (int i = 0; i < n; i++)//打印二维数组 { for (int j = 0; j < i + 1; j++) { printf("%d ", data[i][j]); } printf("\n"); } return 0;} 运行结果: 方法二(对方法一的改进): 由于我在填第n行的杨辉三角时,只跟第n-1行的杨辉三角产生联系,不会跟之前的有联系,所以没必要保存每一行的杨辉三角,利用一维数组,填一行打一行即可,这样能让空间复杂度从O(n^2)降低到O(n)。但是在填数据的时候不能对之前的数据覆盖,所以需要从后向前填。而填杨辉三角顺序对结果是没有影响的,所以可以实现。 代码如下: #include int main(){ int n; int data[30] = { 1 }; printf("请输入要打印的行数:>

"); scanf ("% d ", & n); printf (" 1\ n "); / / print the first line for (int I = 1; I) directly

< n; i++)//从第二行开始 { for (int j = i; j >

0; int -) / / fill in from back to front to prevent the data from the previous row from being overwritten {data [j] + = data [j-1];} for (int j = 0; j)

Tags: Yang Hui triangle Yang Hui triangle row array data method two-dimensional language result jangles code content numbers more knowledge rules contact input run Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Shulou Technology Huawei MariaDB Apple