C language printout asterisk triangle case explanation

Let's first look at an example of an asterisk triangle:

The characteristics of the asterisk triangle are as follows

Take the pattern that the printout is exactly the same as the illustration as an example to write the code.

 Idea analysis

1) First print the asterisk triangle with no space before the star.

 code show as below:

#include <stdio.h>
# define N 4
void main(){
	int i,j,k;
	for(i=1;i<=N;i++){//控制打印输出4行星星
		for(j=1;j<=2*i-1;j++){//控制打印输出每行的星星个数
			printf("*");
		}
		printf("\n");//打印完一行后都需要换行
	}
}

The result of running the code is as follows:

 2) On the premise of the original code, add a for loop statement that controls the number of spaces before the first star in each line of printout.

The whole code of the case is as follows

#include <stdio.h>
# define N 4
void main(){
	int i,j,k;
	for(i=1;i<=N;i++){//控制打印输出4行星星
		for(k=1;k<=N-i;k++){
			printf(" ");//控制打印输出每一行第一个星星前的空格个数
		}
		for(j=1;j<=2*i-1;j++){//控制打印输出每行的星星个数
			printf("*");
		}
		printf("\n");//打印完一行后都需要换行
	}
}

The result of running the code is as follows

Explanation: The code has been written, and the printout of the pattern is completely correct. But there is one thing, what if you are nervous and can't find the rules in the examination room? Here’s a clever solution: we can print out whatever pattern he wants, use violence to do the problem, and print out the stars line by line according to the pattern! If the number of lines is within 10 lines, this method is completely ok. If my clever method of controlling the printout of 100 lines fails, I should honestly find a rule and print out in a loop.

My clever method, the teacher saw it and called it an expert, double-click 666!

code show as below:

#include <stdio.h>
void main(){
	printf("   *\n");
	printf("  ***\n");
	printf(" *****\n");
	printf("*******\n");

}

The result of running the code is as follows:

 

 Is it so simple? I have to admire myself.

Some notes:

The teacher read my answer of using printf to output the star pattern, which is my clever way, and gave me 2 points, which is probably still hard work. This clever method of mine is just for fun, use it with caution.

Guess you like

Origin blog.csdn.net/weixin_63279307/article/details/129874112