【C】Print Yanghui triangle

1. Problem description

Print the Yanghui triangle as shown below

           1

         1     1

      1     2      1

    1    3     3     1

  1    4     6     4    1

1   5    10    10     5     1

2. Algorithm analysis

         Observe the above picture to find:

a. The outermost is all 1;

b. Each number is the sum of the left and right numbers on the previous line;

c. The nth row has n numbers;

d. The numbers in each row are symmetrical (except the first row).

   The key to solving the problem is that each number is the sum of the left and right numbers on its previous row. Here, a two-dimensional array arr is defined to store the numbers to be printed. Then the elements of the i-th row and j-column can be expressed as arr[i][j] = arr[i-1][j-1] + arr[i-1][j].

3. Source code

#define _CRT_SECURE_NO_WARNINGS 1

/*
* Copyright (c) 2018, code farmer from sust
* All rights reserved.
*
* File name: PascalTriangle.c
* Function: print Yanghui triangle
*
* Current version: V1.0
* Author: sustzc
* Completion date: April 4, 2018 22:16:10
*/

# include <stdio.h>
# include <assert.h>

# define ROW 20
# define COLUMN 20

/*
*
* Function name: PascalTriangle
*
* Function: Calculate Yanghui's triangle
*
* Entry parameters: p, len
*
* Exit parameter: void
*
* Return type: void
*/

void CalcPasTriangle(int (* p)[COLUMN], int len)
{
	int i = 0;
	int j = 0;

	assert(NULL != p);

	for (i=0; i<len; i++)
	{
		*(*(p+i)) = 1;
		*(*(p+i)+i) = 1;

		for (j=1; j<i; j++)
		{
			*(*(p+i)+j) = *(*(p+i-1)+j) + *(*(p+i-1)+j-1);
		}
	}

	return;
}

/*
*
* Function name: PrintTriangle
*
* Function: print Yanghui triangle
*
* Entry parameters: p, len
*
* Exit parameter: void
*
* Return type: void
*/

void PrintTriangle(int (* p)[COLUMN], int len)
{
	int i = 0;
	int j = 0;
	
	assert(NULL != p);

	if (len > 0)
	{
		for (i=0; i<len; i++)
		{
			// print spaces
			for (j=0; j<len-i-1; j++)
			{
				printf("    ");
			}
			// print numbers
			for (j=0; j<=i; j++)
			{
				printf("%-8d", *(*(p+i)+j));
			}

			printf("\n");
		}
	}
	else
	{
		printf("input error!\n");
	}
}

int main(void)
{
	int row = 0;
	int triangle[ROW][COLUMN] = {0};

	printf("input row:");
	scanf("%d", &row);

	CalcPasTriangle(triangle, row);
	PrintTriangle(triangle, row);
	
	return 0;
}

4. Output results


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325386269&siteId=291194637