C 语言打印字母 Y 形图案程序

在本文中,我们将展示如何使用 for 循环、while 循环和函数编写一个 C 语言程序来打印字母 Y 图案或星形图案。

#include <stdio.h>

int main() {
int rows;

printf("Enter Rows = ");
scanf("%d", &rows);

if (rows % 2 == 0)
rows += 1;

for (int i = 0; i < rows; i++)
{
for (int j = 0; j < rows; j++)
{
if (((i + j == rows - 1 || i == j) && (i < rows / 2)) || (j == rows / 2 && i > rows / 2 - 1))
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n");
}
}
Enter Rows = 15
*             *
 *           * 
  *         *  
   *       *   
    *     *    
     *   *     
      * *      
       *       
       *       
       *       
       *       
       *       
       *       
       *       
       *       

此字母 Y 形星图案程序不使用 for 循环,而是使用 while 循环来迭代行和列。有关更多星形图案程序,请单击此处

#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 ((i + j == rows - 1) || (i == j && i < rows / 2))
{
printf("*");
}
else
{
printf(" ");
}
j++;
}
printf("\n");
i++;
}
}
Enter Rows = 17
*               *
 *             * 
  *           *  
   *         *   
    *       *    
     *     *     
      *   *      
       * *       
        *        
       *         
      *          
     *           
    *            
   *             
  *              
 *               
*                

在此 C 语言程序中,我们创建了一个 alphabetYPat 函数,该函数接受这些值并打印给定字符的字母 Y 形或图案。

#include <stdio.h>

void alphabetYPat(int rows, char a)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < rows; j++)
{
if (((i + j == rows - 1 || i == j) && (i < rows / 2)) || (j == rows / 2 && i > rows / 2 - 1))
{
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);

if (rows % 2 == 0)
rows += 1;

alphabetYPat(rows, a);
return 0;
}
C Program to Print Alphabet Y Pattern