弗洛伊德三角C语言程序



弗洛伊德三角因罗伯特·弗洛伊德得名,它是一个直角三角形,由自然数组成。它从1开始,并连续选取序列中的下一个较大数字。

Floyds Triangle

我们将在本文中学习如何使用C语言编程打印弗洛伊德三角形。

算法

算法应该是这样的 -

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 NEWLINE character after each inner iteration
Step 6 - Return

伪代码

我们可以按如下方式推导出上述算法的伪代码 -

procedure floyds_triangle

   FOR I = 1 to N DO
      FOR J = 1 to I DO
         PRINT K
         INCREMENT K
      END FOR
      PRINT NEWLINE
   END FOR

end procedure

实现

在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
patterns_examples_in_c.htm
广告
© . All rights reserved.