You are here

C program to print Floyd's triangle

C program to print Floyd's triangle: A user will input how many numbers of rows of Floyd's triangle to print. First four rows of Floyd's triangle are:
1
2 3
4 5 6
7 8 9 10
It's clear that in Floyd's triangle, nth row contains n numbers.

C programming code

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.   int n, i,  c, a = 1;
  6.  
  7.   printf("Enter the number of rows of Floyd's triangle to print\n");
  8.   scanf("%d", &n);
  9.  
  10.   for (i = 1; i <= n; i++)
  11.   {
  12.     for (c = 1; c <= i; c++)
  13.     {
  14.       printf("%d ",a);
  15.       a++;
  16.     }
  17.     printf("\n");
  18.   }
  19.  
  20.   return 0;
  21. }

Output of program:
Floyd triangle C program output

Download Floyd triangle program.

C program to print Floyd's triangle using recursion

  1. #include <stdio.h>
  2.  
  3. void print_floyd(int);
  4.  
  5. int main()
  6. {
  7.   int n, i,  c, a = 1;
  8.  
  9.   printf("Input number of rows of Floyd's triangle to print\n");
  10.   scanf("%d", &n);
  11.  
  12.   print_floyd(n);
  13.  
  14.   return 0;
  15. }
  16.  
  17. void print_floyd(int n) {
  18.    static int row = 1, c = 1;
  19.    int d;
  20.    
  21.    if (n <= 0)
  22.       return;
  23.  
  24.    for (d = 1; d <= row; ++d)
  25.       printf("%d ", c++);
  26.      
  27.    printf("\n");
  28.    row++;
  29.    
  30.    print_floyd(--n);  
  31. }