C Program to print Floyd's Triangle
Objective
Write a C program to print Floyd's Triangle.
Algorithm / Approach
- Declare a counter variable
a = 1. - Run an outer loop
ifrom 1 tonrows. - Run an inner loop
jfrom 1 toi. - Inside the inner loop, print
aand immediately increment it (a++). - Print a newline.
main.c
#include<stdio.h>
int main( ) {
int a = 1, i, j, n;
printf("Enter the number of rows ");
scanf("%d",&n);
for(i = 1; i<=n; i++) {
for(j = 1; j<=i; j++) {
printf("%d",a);
a++;
}
printf("\n");
}
return 0;
}
Expected Output
1 2 3 4 5 6 7 8 9 10
Explanation of the Program
- Floyd's Triangle is a right-angled triangular array of natural numbers.
- Unlike previous patterns where we printed the loop variables (
iorj), here we print a completely independent counter (a) that never resets. It simply keeps counting upwards forever as the loops run.
Complexity
Time Complexity
O(n^2)
Space Complexity
O(1)