Floyd's Triangle
Objective
Write a C++ program to print Floyd's Triangle.
Algorithm / Approach
- Initialize a global counter
k = 1. - Use nested loops to create a right half pyramid shape.
- Inside the inner loop, print
kand increment it.
main.cpp
#include<iostream>
using namespace std;
int main() {
int k = 1;
for(int i = 1; i<=4; i++) {
for(int j = 1; j<=i; j++) {
cout<< k<<" ";
k++;
}
cout<< endl;
}
return 0;
}
Expected Output
1 2 3 4 5 6 7 8 9 10
Explanation of the Program
- Floyd's Triangle is a famous pattern consisting of consecutive natural numbers spread across a right-angled triangle.
- Just like the even-numbers pattern, we use an independent counter variable that keeps growing regardless of when the loops reset for the next row.
Complexity
Time Complexity
O(n^2)
Space Complexity
O(1)