Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to print Floyd's triangle (of integers) using C program?
Floyd's triangle is a right-angle triangle of consecutive numbers, starting with 1 in the top left corner. Each row contains one more number than the previous row, forming a triangular pattern −
1 2 3 4 5 6 7 8 9 10
Syntax
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; j++) {
printf("%d ", number);
number++;
}
printf("<br>");
}
Example 1: Basic Floyd's Triangle
This program generates Floyd's triangle by printing consecutive numbers row by row −
#include <stdio.h>
int main() {
int rows, i, j, start = 1;
printf("Enter number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; j++) {
printf("%d ", start);
start++;
}
printf("<br>");
}
return 0;
}
Enter number of rows: 5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Example 2: Reverse Floyd's Triangle
This program creates a reverse Floyd's triangle by starting with the largest number and decrementing −
#include <stdio.h>
int main() {
int rows, i, j;
printf("Enter number of rows: ");
scanf("%d", &rows);
int k = rows * (rows + 1) / 2;
for (i = rows; i >= 1; i--) {
for (j = 1; j <= i; j++) {
printf("%4d", k--);
}
printf("<br>");
}
return 0;
}
Enter number of rows: 5 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
How It Works
- Outer loop: Controls the number of rows (from 1 to rows)
- Inner loop: Prints numbers in each row (j numbers in the j-th row)
- Counter variable: Keeps track of the current number to print
- Formula: Total numbers in n rows = n*(n+1)/2
Conclusion
Floyd's triangle demonstrates nested loops and sequential number generation. The pattern is useful for understanding triangular number sequences and can be modified to create variations like reverse triangles.
Advertisements
