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