C 语言等边三角形打印



三条边都相等的三角形称为等边三角形。现在我们来看看怎样打印出以等边三角形形状排列的星号 *。

算法

算法应该像这样 −

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
Step 5 - Return

伪代码

我们可以为上述算法导出伪代码,如下 −

procedure equi_triangle

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

实现

C 语言中实现等边三角形的代码如下 −

#include <stdio.h>

int main() {
   int n,i,j;

   n = 5;   // number of rows.

   for(i = 1; i <= n; i++) {
      for(j = 1; j <= n-i; j++)
         printf(" ");

      for(j = 1; j <= i; j++)
         printf("* ");

      printf("\n");
   }
   return 1;
}

输出应该像这样 −

     *
    * *
   * * *
  * * * *
 * * * * *
patterns_examples_in_c.htm
广告