C++ Program to Print Floyd Triangle
for loops and a counter variable, for example: int num = 1; for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { std::cout << num++ << " "; } std::cout << std::endl; }.Examples
How to Think About It
Algorithm
Code
#include <iostream> int main() { int n, num = 1; std::cout << "Enter number of rows: "; std::cin >> n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { std::cout << num++ << " "; } std::cout << std::endl; } return 0; }
Dry Run
Let's trace the program for input n=3 through the code.
Initialize variables
n = 3, num = 1
First row (i=1)
Print 1 number: print num=1, then num=2
Second row (i=2)
Print 2 numbers: print num=2, num=3, then num=4
Third row (i=3)
Print 3 numbers: print num=4, num=5, num=6, then num=7
| Row (i) | Numbers Printed | 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 for loop with variable i runs from 1 to n, controlling how many rows to print.
Step 2: Inner loop prints numbers per row
The inner for loop runs i times to print the correct count of numbers in each row.
Step 3: Counter increments after each print
The variable num starts at 1 and increases by 1 after printing each number to continue the sequence.
Alternative Approaches
#include <iostream> int main() { int n, num = 1, i = 1; std::cout << "Enter number of rows: "; std::cin >> n; while (i <= n) { int j = 1; while (j <= i) { std::cout << num++ << " "; j++; } std::cout << std::endl; i++; } return 0; }
#include <iostream> void printRow(int count, int &num) { if (count == 0) return; std::cout << num++ << " "; printRow(count - 1, num); } void printFloyd(int row, int n, int &num) { if (row > n) return; printRow(row, num); std::cout << std::endl; printFloyd(row + 1, n, num); } int main() { int n, num = 1; std::cout << "Enter number of rows: "; std::cin >> n; printFloyd(1, n, num); 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 the space complexity is O(1), constant space.
Which Approach is Fastest?
The loop-based approach is fastest and simplest. The recursive method adds overhead due to function calls.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(1) | Simple and efficient |
| Nested while loops | O(n^2) | O(1) | Beginners preferring while loops |
| Recursion | O(n^2) | O(n) | Learning recursion, less efficient |