C++ Modified Floyd's Triangle

Beginner

Introduction

In this lab, we will learn how to print the modified Floyd's triangle pattern using the C++ programming language. The modified Floyd's triangle pattern is a right-angled triangular array of natural numbers where each row starts with the row number and contains a number of columns equal to the row number.

Write the initial code

  • Type the following code snippet in the main.cpp file. This code will print the modified Floyd's triangle pattern for a given number of rows.

    #include <iostream>
    using namespace std;
    
    int main()
    {
        cout << "Modified Floyd's Triangle Pattern\n\n";
    
        //i to iterate the outer loop and j for the inner loop
        int i, j, rows;
    
        //to denote the range of numbers in each row
        int n = 0, first, last;
    
        cout << "Enter the number of rows in the pyramid: ";
        cin >> rows;
    
        cout << "\nThe modified Floyd's Triangle pattern containing " << rows << " rows is:\n\n";
    
        //outer loop is used to move to a particular row
        for (i = 1; i <= rows; i++)
        {
            first = i;
            last = first + i - 1;
    
            //inner loop is used to decide the number of columns in a particular row
            for (j = 1; j <= i; ++j)
                cout << n + j << " ";
    
            n++;
            cout << endl;
        }
    
        cout << "\n";
    
        return 0;
    }

Compile and run the code

  • Open the terminal and navigate to the directory containing the main.cpp file using the cd command.

  • Type the following command to compile the program:

    g++ main.cpp -o main
  • This should create an executable file named main.

  • Run the executable file using the following command:

    ./main
  • The program will prompt you to enter the number of rows for the modified Floyd's triangle pattern.

  • After you enter the input, the program will print the modified Floyd's triangle pattern in the console.

Modify the code (optional)

  • You can modify the code to print the range of numbers in each row.

  • Uncomment the following line in the code:

    //cout << "Row ## " << i << " contains the numbers from " << first << " to " << last << " :    ";
  • Recompile and run the code to see the range of numbers printed for each row.

Summary

In this lab, we learned how to print the modified Floyd's triangle pattern using the C++ programming language. We wrote the code to iterate over the rows and columns of the pattern and used a simple algorithm to calculate the starting and ending numbers for each row. We also learned how to compile and run C++ programs in the terminal.

Other Tutorials you may like