C++ program to print Floyd’s Triangle (2 Ways)

In this program, we will learn how to print Floyd’s Triangle using the C++ programming language.

What is Floyd’s Triangle?

It is a right-angled triangular array of natural numbers which is named after Robert Floyd.

We discuss two ways to write code for it.

  • Using Loop
  • Using Recursion

C++ programming code to print Floyd’s Triangle

Using Loop

In this program, we will use nested for loop.

Code:-

#include <iostream>

using namespace std;
 
int main(){
    int rows, num = 1;

    cout << "Enter the number of rows of Floyd's triangle to print: ";
    cin >> rows ;


    for (int i = 1; i <= rows; i++){
        for (int j = 1; j <= i; j++){
            cout << num << " ";
            num++;
        }
    cout << endl;
    }

    return 0;
}

Output:-

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Using Recursion

In this program, we will use the recursive function printFloydTriangle(), which will print the Floyd Triangle in the output.

Code:-

#include <iostream>

using namespace std;

void printFloydTriangle(int rows){
   static int col = 1, num = 1;
   
   if (rows <= 0)
        return;
 
   for(int i = 1; i <= col; ++i)
        cout << num++ << " ";
     
   cout << endl;
   col++;
   
   printFloydTriangle(--rows);  
}

int main(){
    int rows, num = 1;

    cout << "Enter the number of rows of Floyd's triangle to print: ";
    cin >> rows ;

    printFloydTriangle(rows);

    return 0;
}

Output:-

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

You can learn about many other C++ Programs Here.

Best Books for learning C++ programming language with Data Structure and Algorithms.

The following two tabs change content below.
Amit Rawat

Amit Rawat

Founder and Developer at SpiderLabWeb
I love to work on new projects and also work on my ideas. My main field of interest is Web Development.

You may also like...