21xrx.com
2024-04-20 20:47:53 Saturday
登录
文章检索 我的文章 写文章
C中的弗洛伊德三角形
2021-07-06 22:25:23 深夜i     --     --
C

打印弗洛伊德三角形的 C 程序:用户输入要打印的三角形的行数。 弗洛伊德三角形的前四行是:12 34 5 67 8 9 10在弗洛伊德三角形中,第n行包含n个数字。 n 行三角形中的总数:n*(n+1)/2。

 

打印弗洛伊德三角形的 C 程序

#include <stdio.h>


int main()
{
  int n, i,  c, a = 1;

  printf("Enter the number of rows of Floyd's triangle to print\n");
  scanf("%d", &n);

  for (i = 1; i <= n; i++)
  {
    for (c = 1; c <= i; c++)
    {
      printf("%d ", a); // Please note space after %d
      a++;
    }
    printf("\n");
  }

  return 0;
}

该程序使用嵌套的 for 循环。 第一个是跟踪行数,第二个是打印单个行。 时间复杂度:O(n2)。

 

程序输出:

下载弗洛伊德三角程序。

使用递归打印弗洛伊德三角形的 C 程序

#include <stdio.h>
 
void print_floyd(int, int, int);
 
int main()
{
  int n;
 
  printf("Input number of rows of Floyd's triangle to print\n");
  scanf("%d", &n);
 
  print_floyd(1, n, 1);
 
  return 0;
}
 
void print_floyd(int currentRow, int numberOfRows, int numberToPrint) {
  int c;


  if (currentRow > numberOfRows) // Base case
    return;
 
  for (c = 1; c <= currentRow; c++)
    printf("%d ", numberToPrint++);
 
  printf("\n");
  print_floyd(++currentRow, numberOfRows, numberToPrint);
}

 

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章