Print Floyd's Triangle

Beginner

Introduction

In this lab, we will learn how to write a C++ program to print Floyd's Triangle.

Include the necessary header files

To write any C++ program, we need to include certain header files in our code. In this step, we will include the necessary header files that we will be using in our program.

#include <iostream>
using namespace std;

Write the main() function

The main() function is the entry point of the program. It is here that we will be writing the code to print Floyd's Triangle.

int main()
{
    // code to print Floyd's Triangle
    return 0;
}

Declare the necessary variables

In this step, we will be declaring the necessary variables that we will be using in our program. We will be using i and j to iterate through the rows and columns of the triangle, rows to store the number of rows in the triangle, n to store the current number, first to store the first number in the current row and last to store the last number in the current row.

int i, j, rows, n=1, first, last;

Get the input from the user

In this step, we will be getting the number of rows in the triangle from the user.

cout << "Enter the number of rows in the pyramid: ";
cin >> rows;

Print Floyd's Triangle

In this step, we will be using nested loops to print Floyd's Triangle. The outer loop is used to move to a particular row and the inner loop is used to print the numbers in that row. We will be printing a space after each number to separate them.

for (i = 1; i <= rows; i++)
{
    first = n;
    last  = first + i -1;

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

    cout << endl;
}

Complete the program

Finally, we will complete the program by printing a message to indicate that the program has run successfully.

cout << "\n\nFloyd's Triangle has been printed successfully.\n\n";
return 0;

Summary

In this lab, we learned how to write a C++ program to print Floyd's Triangle. We used nested loops to iterate through the rows and columns of the triangle and printed a space after each number to separate them. By following the above steps, you can create your own C++ program to print Floyd's Triangle.

Other Tutorials you may like