弗洛伊德在C中的三角形印刷(Floyd's triangle printing in C)

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

Floyd的三角形以Rober Floyd命名,是一个直角三角形,使用自然数字制作。 它从1开始,并按顺序连续选择下一个更大的数字。

弗洛伊德三角

我们将在这里学习如何使用C编程语言打印floyd的三角形。

算法 (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 K
Step 4 - Increment K
Step 5 - Print <i>NEWLINE</i> character after each inner iteration
Step 6 - Return

伪代码 (Pseudocode)

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

procedure floyds_triangle
   FOR I = 1 to N DO
      FOR J = 1 to I DO
         PRINT K
         INCREMENT K
      END FOR
      PRINT <i>NEWLINE</i>
   END FOR
end procedure

实现 (Implementation)

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

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

输出应该是这样的 -

  1
  2  3
  4  5  6
  7  8  9 10
 11 12 13 14 15