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?
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:-
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:-
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.
Amit Rawat
Latest posts by Amit Rawat (see all)
- Python Program to Print the Fibonacci Sequence (2 ways) - April 7, 2020
- Python Program to Display or Print Prime Numbers Between a Range or an Interval - June 18, 2019
- Python Program To Print Pascal’s Triangle (2 Ways) - June 17, 2019