Home > Common Problem > How to write Christmas tree code in C language

How to write Christmas tree code in C language

小老鼠
Release: 2024-01-23 16:05:55
Original
1500 people have browsed it

Writing: Use three loops to print each line of the Christmas tree. The first loop controls the height of the tree, the second loop prints spaces, and the third loop prints asterisks. In the second loop, n - i is used to control the number of spaces printed in front of each line. As the height increases, the number of spaces will gradually decrease. In the third loop, use 2 * i 1 to control the number of asterisks printed in each line. As the height increases, the number of asterisks will gradually increase. After the second loop, an additional loop is used to print the trunk, making the tree look more complete.

How to write Christmas tree code in C language

The following is a simple C language Christmas tree code example:

c

#include <stdio.h>  
  
int main() {  
    int i, j, k;  
    int n = 6;  // 树的高度  
  
    for (i = 0; i < n; i++) {  
        for (j = 0; j < n - i; j++) {  
            printf(" ");  
        }  
        for (k = 0; k < 2 * i + 1; k++) {  
            printf("*");  
        }  
        printf("\n");  
    }  
    for (i = 0; i < n - 1; i++) {  
        for (j = 0; j < n - 1 - i; j++) {  
            printf(" ");  
        }  
        for (k = 0; k < n + 1 + i; k++) {  
            printf("*");  
        }  
        printf("\n");  
    }  
    return 0;  
}
Copy after login

In this example, we use three loop to print each row of the Christmas tree. The first loop controls the height of the tree, the second loop prints spaces, and the third loop prints asterisks. In the second loop, we use n - i to control the number of spaces printed in front of each line, since the number of spaces gradually decreases as the height increases. In the third loop, we use 2 * i 1 to control the number of asterisks printed in each line, because as the height increases, the number of asterisks will gradually increase. After the second loop, we also used an additional loop to print the trunk to make the tree look more complete.

The above is the detailed content of How to write Christmas tree code in C language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template