[C language] Use for loop to print star-like diamonds (two methods are super detailed)

The following is the detailed code about the realization of the star-like diamonds written in the for loop of the C language. The comment analysis is more detailed and is for reference only. If there are errors or optimization points, readers are welcome to correct them.

Draw the image and treat the left space as 1 for easy viewing and analysis.

Consider the first n rows first, and then process the remaining n-1 rows.

        1111*
        111***
        11*****
        1*******
        *********
        1*******
        11*****
        111***
        1111*
//VS系列编译器中不用此定义会出现非法错误
/*错误  error C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. */

#define  _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int main()
{
    
    
 //由菱形几何性质可知中间行的行数即为菱形的半径
 int n = 0;                  //初始化n
 
 printf("请输入星星菱形边长:");
 
 scanf("%d", &n);            //输入n
 
 for (int i = 1; i <= n; i++)//定义从第1行到第n行外循环
  {
    
        
  
  //随着外循环i的增大(行数的增加)n-i依次变小(图中1依次变小) 
  //与行数变化相反,所以采取递减
  //处理左方空白 
    //当n=5时 上半部分图像如下图,空白用1表示 
    /*      1111*
            111***
            11*****
            1*******
            *********
    */        
   //根据等差数列
   /*
       行数:1   2   3   4   5
   星的个数:1   3   5   7   9
   易得行数i与对应行星星个数k满足的通项公式 k=2*i-1  注意此处2*i不可省略为2i
   */
   
   
         
  for (int j = n - i; j>=1; j--)    
   {
    
                                     
   
      printf(" ");                         
                                   
   }
  for (int k = 1; k <= 2 * i-1 ;k++) //等差数列公式
   {
    
    
      printf("*");
   }
      printf("\n");//对每行操作后换行
  }

   // 下面是从第n+1行开始倒序操作
 
  for (int i = n-1; i >=1; i--)//之前处理了n行,所以接下来处理剩下的n-1行
 {
    
    
  for (int j = 1; j <= n-i; j++)                 //           1*******
  {
    
                                                  //           11*****
   printf(" ");                                  //           111***
  }                                              //           1111*
  for (int k = 1; k <= 2 * i-1; k++)
  {
    
    
   printf("*");
  }
  printf("\n");
 }
 //以下是另一种解法正序操作,即把剩下的n-1行当做新的序列从1开始
 for (int i = 1; i <= n - 1; i++)
 {
    
    
  for (int j = 1; j <= i; j++)
  {
    
    
   printf(" ");
  }
  //此时要求得行数与对应行星星个数的函数关系
  //首(行)项为2n-3,公差为-2(依次递减),规律变化行数为i,则通过等差数列通项公式:通项=首项+公差*(i-1)
  //则2*n-3-2*(i-1)=2*n-2*i-1即为i行星星数的通项
  for (int k = 1; k <= 2 * n - 2 * i - 1; k++)
  {
    
    
   printf("*");
  }
  printf("\n");
 }
 system("pause");
 return 0;
}
                               

Guess you like

Origin blog.csdn.net/weixin_50067564/article/details/108193073