C Program to Print Floyd Triangle with Output and Explanation
for loops where the outer loop controls rows and the inner loop prints consecutive numbers, incrementing a counter each time, like for(i=1; i<=rows; i++){ for(j=1; j<=i; j++){ printf("%d ", num++); }}.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int rows, num = 1; printf("Enter number of rows: "); scanf("%d", &rows); for (int i = 1; i <= rows; i++) { for (int j = 1; j <= i; j++) { printf("%d ", num++); } printf("\n"); } return 0; }
Dry Run
Let's trace the program with input 3 to see how Floyd's triangle is printed.
Initialize variables
rows = 3, num = 1
First row (i=1)
Print 1 number: print 1, num becomes 2
Second row (i=2)
Print 2 numbers: print 2, 3, num becomes 4
Third row (i=3)
Print 3 numbers: print 4, 5, 6, num becomes 7
| Row (i) | Numbers Printed | Value of num after row |
|---|---|---|
| 1 | 1 | 2 |
| 2 | 2 3 | 4 |
| 3 | 4 5 6 | 7 |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to the number of rows, deciding how many rows to print.
Step 2: Inner loop prints numbers per row
The inner for loop runs as many times as the current row number, printing numbers and increasing the counter.
Step 3: Counter increments after each print
The variable num starts at 1 and increases by 1 after printing each number, ensuring consecutive numbers.
Alternative Approaches
#include <stdio.h> int main() { int rows, i = 1, j, num = 1; printf("Enter number of rows: "); scanf("%d", &rows); while (i <= rows) { j = 1; while (j <= i) { printf("%d ", num++); j++; } printf("\n"); i++; } return 0; }
#include <stdio.h> int main() { int rows, num = 1, count = 0, i = 1; printf("Enter number of rows: "); scanf("%d", &rows); for (int k = 1; k <= rows*(rows+1)/2; k++) { printf("%d ", num++); count++; if (count == i) { printf("\n"); i++; count = 0; } } return 0; }
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested loops where the outer loop runs n times and the inner loop runs up to n times cumulatively, resulting in O(n^2) time.
Space Complexity
Only a few integer variables are used, so space complexity is O(1), constant space.
Which Approach is Fastest?
All approaches have similar O(n^2) time; using for loops is clearer and preferred for readability.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(1) | Clarity and simplicity |
| Nested while loops | O(n^2) | O(1) | Alternative syntax preference |
| Single loop with manual breaks | O(n^2) | O(1) | Reducing nested loops but less readable |