在本文中,我们将展示如何使用 for 循环、while 循环和函数来编写一个 C 程序来打印字母 W 模式或星形形状。
#include <stdio.h>
int main() {
int rows;
printf("Enter Rows = ");
scanf("%d", &rows);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < rows; j++)
{
if(j == 0 || j == rows - 1)
{
printf("*");
}
else if ((i + j == rows - 1 || i == j) && (i >= rows / 2))
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n");
}
return 0;
}
Enter Rows = 15
* *
* *
* *
* *
* *
* *
* *
* * *
* * * *
* * * *
* * * *
* * * *
* * * *
** **
* *
这个星形字母 W 模式程序使用 while 循环 来迭代行和列,而不是 for 循环。有关更多星形程序,请点击此处。
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter Rows = ");
scanf("%d", &rows);
i = 0;
while ( i < rows)
{
j = 0;
while ( j < rows)
{
if(j == 0 || j == rows - 1)
{
printf("*");
}
else if ((i + j == rows - 1 || i == j) && (i >= rows / 2))
{
printf("*");
}
else
{
printf(" ");
}
j++;
}
printf("\n");
i++;
}
return 0;
}
Enter Rows = 17
* *
* *
* *
* *
* *
* *
* *
* *
* * *
* * * *
* * * *
* * * *
* * * *
* * * *
* * * *
** **
* *
在这个 C 程序中,我们创建了一个 alphabetWPat 函数,它接受这些值并打印给定字符的字母 W 形状或模式。
#include <stdio.h>
void alphabetWPat(int rows, char a)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < rows; j++)
{
if(j == 0 || j == rows - 1)
{
printf("%c", a);
}
else if ((i + j == rows - 1 || i == j) && (i >= rows / 2))
{
printf("%c", a);
}
else
{
printf(" ");
}
}
printf("\n");
}
}
int main()
{
int rows;
char a;
printf("Enter Alphabet = ");
scanf("%c", &a);
printf("Enter Rows = ");
scanf("%d", &rows);
alphabetWPat(rows, a);
return 0;
}
