C language heart-shaped pattern simple code writing: 1. The code prints the upper and lower parts of the heart through two loops; 2. In each loop, use nested loops to print Add the specified number of spaces and asterisks to form a heart shape; 3. You can change the size of the heart shape by adjusting the value of the variable n.
The operating environment of this article: Windows 10 system, Code Blocks version 20.03, Dell G3 computer.
The simple code for a heart-shaped pattern in C language can be in the following form:
#include <stdio.h> int main() { int i, j; int n = 6; // 心形的大小,可以根据需要调整 // 上半部分心形图案 for (i = n / 2; i <= n; i += 2) { // 打印空格 for (j = 1; j < n - i; j += 2) { printf(" "); } // 打印左边的心形 for (j = 1; j <= i; j++) { printf("*"); } // 打印空格 for (j = 1; j <= n - i; j++) { printf(" "); } // 打印右边的心形 for (j = 1; j <= i; j++) { printf("*"); } printf("\n"); } // 下半部分心形图案 for (i = n; i >= 1; i -= 2) { // 打印空格 for (j = 1; j <= n - i; j += 2) { printf(" "); } // 打印左边的心形 for (j = 1; j <= i; j++) { printf("*"); } // 打印空格 for (j = 1; j <= n - i; j++) { printf(" "); } // 打印右边的心形 for (j = 1; j <= i; j++) { printf("*"); } printf("\n"); } return 0; }
The above code implements a simple C language program for printing out a heart-shaped pattern. The code prints the upper and lower halves of the heart through two loops. In each loop, use nested loops to print out the specified number of spaces and asterisks to form a heart shape. The size of the heart can be changed by adjusting the value of the variable n.
The above is the detailed content of How to write a simple code for a heart-shaped pattern in C language. For more information, please follow other related articles on the PHP Chinese website!