编写一个 C 程序,使用 for 循环、while 循环、do while 循环和函数来打印沙漏星形图案,并附带示例。
#include <stdio.h>
int main(void)
{
int i, j, k, rows;
printf("Enter Sandglass Star Pattern Rows = ");
scanf("%d",&rows);
for (i = 1; i <= rows; i++)
{
for (j = 1; j < i; j++)
{
printf(" ");
}
for (k = i; k <= rows; k++)
{
printf("* ");
}
printf("\n");
}
for (i = rows - 1; i >= 1; i--)
{
for (j = 1; j < i; j++)
{
printf(" ");
}
for (k = i; k <= rows; k++)
{
printf("* ");
}
printf("\n");
}
}

这个 C 示例 使用 while 循环来显示沙漏图案或结构的星形。在这里,我们用 while 循环 替换了 for 循环。
#include <stdio.h>
void loopLogic(int rows, int i)
{
int j = 1;
while (j < i )
{
printf(" ");
j++;
}
int k = i;
while (k <= rows )
{
printf("* ");
k++;
}
printf("\n");
}
int main(void) {
int i, j, k, rows;
printf("Enter Sandglass Star Pattern Rows = ");
scanf("%d",&rows);
i = 1;
while (i <= rows)
{
loopLogic(rows, i);
i++;
}
i = rows - 1;
while (i >= 1)
{
loopLogic(rows, i);
i--;
}
}
Enter Sandglass Star Pattern Rows = 7
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
C 语言使用 do while 循环打印沙漏星形图案的程序
请参考 Do while 循环 文章。
#include <stdio.h>
void loopLogic(int rows, int i)
{
int j = 1;
do
{
printf(" ");
j++;
} while (j < i );
int k = i;
do
{
printf("* ");
k++;
} while (k <= rows );
printf("\n");
}
int main(void) {
int i, j, k, rows;
printf("Enter Sandglass Star Pattern Rows = ");
scanf("%d",&rows);
i = 1;
do
{
loopLogic(rows, i);
i++;
} while (i <= rows);
i = rows - 1;
do
{
loopLogic(rows, i);
i--;
} while (i >= 1);
}
Enter Sandglass Star Pattern Rows = 11
* * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
此示例使用函数,并接受用户输入的符号,打印给定符号的沙漏图案。
#include <stdio.h>
void loopLogic(int rows, int i, char ch)
{
for (int j = 1; j < i; j++ )
{
printf(" ");
}
for (int k = i; k <= rows; k++ )
{
printf("%c ", ch);
}
printf("\n");
}
int main(void) {
int i, rows;
char ch;
printf("Enter Character = ");
scanf("%c", &ch);
printf("Enter Sandglass Star Pattern Rows = ");
scanf("%d",&rows);
for (i = 1; i <= rows; i++)
{
loopLogic(rows, i, ch);
}
for (i = rows - 1; i >= 1; i--)
{
loopLogic(rows, i, ch);
}
}
Enter Character = $
Enter Sandglass Star Pattern Rows = 9
$ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $
$ $ $ $ $ $ $
$ $ $ $ $ $
$ $ $ $ $
$ $ $ $
$ $ $
$ $
$
$ $
$ $ $
$ $ $ $
$ $ $ $ $
$ $ $ $ $ $
$ $ $ $ $ $ $
$ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $