在C中自上而下打三角形(Top down triangle printing in C)

优质
小牛编辑
124浏览
2023-12-01

一个角度为90°的三角形称为直角三角形。 我们现在将看到如何以直角三角形形状打印星形*,但是在y轴上颠倒。

算法 (Algorithm)

算法看起来像这样 -

Step 1 - Take number of rows to be printed, n.
Step 2 - Make outer iteration I for n times to print rows
Step 3 - Make inner iteration for J to I
Step 3 - Print "*" (star)
Step 4 - Print <i>NEWLINE</i> character after each inner iteration
Step 5 - Return

伪代码 (Pseudocode)

我们可以为上述算法推导出一个伪代码,如下所示 -

procedure topdown_triangle
   FOR I = 1 to N DO
      FOR J = 1 to I DO
         PRINT "*" 
      END FOR
      PRINT NEWLINE
   END FOR
end procedure

实现 (Implementation)

在C中实施直角三角形如下 -

#include <stdio.h>
int main() {
   int n,i,j;
   n = 5;
   for(i = 0; i < n; i++) {
      for(j = 0; j<i; j++)
         printf("  "); 
      for(j = i; j < n; j++)
         printf(" *");
      printf("\n");
   }
   return 0;
}

输出应该是这样的 -

 * * * * *
   * * * *
     * * *
       * *
         *