如何使用C语言打印菱形图案的星星?
在这里,为了按菱形图案打印星星,我们使用嵌套for循环。
我们用来按菱形图案打印星星的逻辑如下所示 −
//For upper half of the diamond the logic is:
for (j = 1; j <= rows; j++){
for (i = 1; i <= rows-j; i++)
printf(" ");
for (i = 1; i<= 2*j-1; i++)
printf("*");
printf("
");
}假设我们考虑行数=5,则打印输出如下 −
* *** ***** ******* *********
//For lower half of the diamond the logic is:
for (j = 1; j <= rows - 1; j++){
for (i = 1; i <= j; i++)
printf(" ");
for (i = 1 ; i <= 2*(rows-j)-1; i++)
printf("*");
printf("
");
}假设行数=5,将会打印如下输出 −
******* ***** *** *
示例
#include <stdio.h>
int main(){
int rows, i, j;
printf("Enter no of rows
");
scanf("%d", &rows);
for (j = 1; j <= rows; j++){
for (i = 1; i <= rows-j; i++)
printf(" ");
for (i = 1; i<= 2*j-1; i++)
printf("*");
printf("
");
}
for (j = 1; j <= rows - 1; j++){
for (i = 1; i <= j; i++)
printf(" ");
for (i = 1 ; i <= 2*(rows-j)-1; i++)
printf("*");
printf("
");
}
return 0;
}输出
Enter no of rows 5 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP