You are here

Floyd's triangle in C

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. Total numbers in the triangle of n rows: n*(n+1)/2.

C program to print Floyd's triangle

#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;
}

The program uses nested for loops. The first is to keep track of the number of rows, and the second is to print individual rows. Time complexity: O(n2).

Output of program:
Floyd triangle C program output

Download Floyd triangle program.

C program to print Floyd's triangle using recursion

#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);
}