C++ Program To Print Floyd’s Triangle
Floyd’s triangle is a triangular array of natural numbers and it is named after Robert Floyd, a renowned computer scientist popularly known for the design of the Floyd–Warshall algorithm. Here, we will see how to print Floyd’s pattern triangle pyramid using the C++ program. Below are the examples:
Input: row = 5
Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Input: row = 4
Output:
1
2 3
4 5 6
7 8 9 10
Algorithm:
- At first, take the number of rows as input.
- The next step is to implement the nested loop to print this pattern.
- A variable name count maintains the value of natural numbers to be printed.
There are 3 ways to print Floyd’s pattern triangle pyramid:
- Using for loop.
- Using While loop.
- Using Recursion.
Let’s start discussing each of these methods in detail.
1. Using for loop
Below is the C++ program to print Floyd’s pattern triangle using for loop:
C++
#include <bits/stdc++.h>
using namespace std;
void print_patt( int row)
{
int count = 1;
for ( int i = 1; i <= row; i++)
{
for ( int j = 1; j <= i; j++)
{
cout << count << " " ;
count += 1;
}
cout << "\n" ;
}
}
int main()
{
int row = 5;
print_patt(row);
return 0;
}
|
Output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
- Time Complexity: O(n2) as the nested loop is used.
- Auxiliary Space: O(1) no extra space is required, so space is constant.
2. Using while loop
Below is the C++ program to print Floyd’s triangle using the While loop.
C++
#include <bits/stdc++.h>
using namespace std;
void print_patt( int row)
{
int count = 1;
int i = 1, j;
while (i <= row)
{
j = 1;
while (j <= i)
{
cout << count << " " ;
count += 1;
j += 1;
}
i += 1;
cout << "\n" ;
}
}
int main()
{
int row = 5;
print_patt(row);
return 0;
}
|
Output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
- Time Complexity: O(n2) as the nested loop is used.
- Auxiliary Space: O(1) no extra space is required, so space is constant.
3. Using Recursion
Below is the C++ program to print Floyd’s triangle using Recursion:
C++
#include <bits/stdc++.h>
using namespace std;
void print_patt( int row, int curr_row,
int count)
{
if (row <= 0)
return ;
for ( int i = 1; i <= curr_row; i++)
{
cout << count << " " ;
count += 1;
}
cout << "\n" ;
curr_row += 1;
print_patt(row - 1,
curr_row, count);
}
int main()
{
int curr_row = 1;
int count = 1;
int row = 5;
print_patt(row, curr_row, count);
return 0;
}
|
Output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
- Time Complexity: O(n2).
- Auxiliary Space: O(n) as a recursive approach is used.
Last Updated :
22 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...