C language uses recursion to obtain s neat Yang Hui triangles

#include<stdio.h>
int fun(int i,int j){
    if(j==0||j==i)
        return 1;
    else
        return fun(i-1,j-1)+fun(i-1,j);
}

int main(){
    int n,s;
    scanf("%d",&s);
    while(s>0){
    	scanf("%d",&n);
        for(int i=0;i<n;i++){
            for(int k=0;k<n-i-1;k++)
                printf(" ");
        for(int j=0;j<=i;j++){
            printf("%d ",fun(i,j));
        }
    printf("\n");
    }
    s=s-1;
}
    return 0;
} 

This question requires two inputs, one is the number of triangles, and the other is the number of rows of triangles. So we thought that the input of the number is the number of times we need to loop to make triangles, and as we all know, Yang Hui's triangle In the second row and beyond, one of the numbers is the sum of the two numbers in the first row. Therefore, we can use recursion to continuously add the numbers in the upper row.

Guess you like

Origin blog.csdn.net/kgb2333/article/details/134537717