floyd’s triangle using C++

In this tutorial, we will learn how to print Floyd’s triangle in C++.

Floyd’s triangle is a triangular array of natural numbers arranged as a right triangle. In the beginning of education of a computer programming language, A programmer is often given or assigned a task for printing this Floyd triangle as output because it tests the understanding level of programmer logic about loops.

If you’re such a person and you are getting difficulties in writing program, here you’ll get to learn about and how of Floyd’s triangle using C++


Generate floyd’s triangle in C++

The most important part of this program is the correct application of iteration either by ‘for’, ‘while’, or ‘do-while’ loop. Let’s do it by ‘for’ loop. We will use two loops, first for the number of rows and the second loop for elements in the row. Since two iterations are done consecutively the time complexity of the program will be O(nˆ2).

Also read: Write a program to print Floyd’s triangle in C++

Let understand it by creating a pseudo-code :

Pseudo Code: Floyd’s triangle

Step 1 – Take the number of rows to be printed and store it in variable n.

Step 2 – Make the first iteration for n times to print rows

Step 3 – Make the second iteration for j to i ->  Print K

Step 4 – Increment K

Step 5 – Print \n character after each inner iteration

Step 6 – end of program: return

C++ program to print Floyd’s triangle

#include <iostream>
using namespace std;

int main() {
   int n,i,j,k = 1;
   cout<<"No. of rows: <<endl;
   cin>>n;
   

   for(i = 1; i <= n; i++) {
      for(j = 1;j <= i; j++)
         cout<<k++;

      cout<<"\n";
   }

   return 0;
}


Output:

No. of rows: 5                                                                                                                                         
1                                                                                                                                                      
23                                                                                                                                                     
456                                                                                                                                                    
78910                                                                                                                                                  
1112131415

Also read:

Transpose of a matrix using C++

Traveling Salesperson Problem using Dynamic Approach in C++

Find all pairs of number whose sum is equal to a given number in C++

Leave a Reply

Your email address will not be published. Required fields are marked *