C中的上下三角打印(Up-side down triangle printing in C)

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

所有边相等的三角形称为等边三角形。 我们现在将看到如何以等边三角形形状打印星形*,但是颠倒了。

算法 (Algorithm)

算法看起来像这样 -

Step 1 - Take number of rows to be printed, n.
Step 2 - Make an iteration for n times
Step 3 - Print " " (space) for in decreasing order from 1 to n-1
Step 4 - Print "* " (start, space) in increasing order from 1 to I
Step 5 - Return

伪代码 (Pseudocode)

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

procedure upsidedown_triangle
   FOR I = 1 to N DO
      FOR J = 1 to N-I DO
         PRINT " "
      END FOR
      FOR J = 1 to I DO
         PRINT "* " 
      END FOR
   END FOR
end procedure

实现 (Implementation)

在C中实现等边三角形倒置如下 -

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

输出应该是这样的 -

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