Monday, February 17, 2020

Floyd's triangle

C program to print Floyd's triangle: a user inputs how many rows of the triangle to print. The first four rows of Floyd's triangle are:
1
2 3
4 5 6
7 8 9 10
In Floyd's triangle, the nth row contains n numbers.

#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 (= 1; i <= n; i++)
  {
    for (= 1; c <= i; c++)
    {
      printf("%d ",a);
      a++;
    }
    printf("\n");
  }
  return 0;
}
Output of program:

Floyd triangle C program output

C program to print Floyd's triangle using recursion

#include <stdio.h>

void print_floyd(int);

int main()
{
  int n;

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

  print_floyd(n);

  return 0;
}

void print_floyd(int n) {
  static int row = 1, c = 1;
  int d;
  if (<= 0)
    return;

  for (= 1; d <= row; ++d)
    printf("%d ", c++);
 
  printf("\n");
  row++;
  print_floyd(--n);
}

No comments:

Post a Comment