Experiment 7-2-6 The simple and easy-to-understand method of printing Yanghui triangle (recommended)

This question requires printing the first N lines of Yang Hui triangle in the prescribed format.

Input format:

Enter N in one line (1≤N≤10).

Output format:

Output the first N rows of Yanghui triangles in the format of regular triangles. Each number occupies a fixed 4 digits.

Input sample:

6

Sample output:
Insert picture description here

Ideas:

Define a two-dimensional array of 11×11 size, assign all values ​​to 0, and leave the 0th column empty.
Yang Hui's triangle principle can be understood as dividing each number in the first row to the sum of the number directly above and the upper left, then obviously this question The answer is obvious

AC code:

#include <stdio.h>  
int main()  
{
    
     
    	int n,i,j;   
    	static int a[11][11];
    	scanf("%d",&n);
    	a[1][1]=1;
 	for(j=0;j<n-1;j++)              
  		printf(" ");          
 	printf("%4d\n",a[1][1]); 
 	for(i=2;i<=n;i++)    
 	{
    
                
  		for(j=0;j<n-i;j++)       
        		printf(" ");        
  		for(j=1;j<=i;j++)     
  		{
    
                    
   			a[i][j]=a[i-1][j]+a[i-1][j-1];  
   			if(j==i)                
    				printf("%4d\n",a[i][j]);            
   			else            
    				printf("%4d",a[i][j]);    
  		}    
 	}      
 	return 0; 
} 

Guess you like

Origin blog.csdn.net/weixin_45989486/article/details/106023733