How to print Floyd’s triangle (of integers) using C program?

CServer Side ProgrammingProgramming

Floyd's triangle is a right-angle triangle of consecutive numbers, starting with a 1 in the top left corner −

For example,

1
2 3
4 5 6
7 8 9 10

Example 1

 Live Demo

#include <stdio.h>
int main(){
   int rows, i,j, start = 1;
   printf("Enter no of rows of Floyd's triangle :");
   scanf("%d", &rows);
   for (i = 1; i <= rows; i++){
      for (j = 1; j <= i; j++){
         printf("%d ", start);
         start++;
      }
      printf("\n");
   }
   return 0;
}

Output

Enter no of rows of Floyd's triangle :6
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21

Example 2

The following program shows how to reverse a Floyd’s triangle −

 Live Demo

#include<stdio.h>
int main() {
   int num, i, j;
   printf("Enter number of rows: ");
   scanf("%d",&num);
   int k = num*(num+1)/2;
   for(i=num; i>=0; i--) {
      for(j=1; j<=i; j++)
      printf("%4d",k--);
      printf("\n");
   }
   return 0;
}

Output

Enter number of rows: 7
28 27 26 25 24 23 22
21 20 19 18 17 16
15 14 13 12 11
10 9 8 7
6 5 4
3 2
1
raja
Published on 05-Mar-2021 10:28:32
Advertisements