C++ Program to Print Reverse Floyd Pattern Triangle Pyramid
Last updated on 05/05/2024To create a C++ program that prints a reverse Floyd’s Triangle, we need to reverse the pattern seen in the traditional Floyd’s Triangle. In this pattern, numbers will decrease with each row rather than increasing. The highest number starts at the top and decreases as we proceed downwards, maintaining the staggered layout of Floyd’s Triangle.
C++ Code for Reverse Floyd’s Triangle:
#include <iostream>
using namespace std;
int main() {
int rows;
// Ask the user for the number of rows
cout << “Enter the number of rows for the Reverse Floyd’s Triangle: “;
cin >> rows;
// Determine the starting number
int start_number = rows * (rows + 1) / 2; // Sum of first ‘rows’ natural numbers
cout << “Reverse Floyd’s Triangle:” << endl;
// Outer loop for handling the number of rows
for (int i = rows; i > 0; i–) {
// Inner loop for handling the number of columns in each row
for (int j = 0; j < i; j++) {
cout << start_number << ” “;
start_number–; // Decrement number for next place
}
cout << endl; // Move to the next line after each row
}
return 0;
}
Explanation:
-
Variable Declaration and Input:
- rows: The user specifies how many rows the triangle should have.
- start_number: Calculated as the sum of the first rows natural numbers using the formula 𝑛(𝑛+1)22n(n+1). This gives the starting point for the highest number in the triangle.
-
Printing the Triangle:
- Outer Loop: Runs backward from rows to 1. Each iteration corresponds to a row in the triangle.
- Inner Loop: Handles the number of entries in each row, which matches the current row number (i). It prints out the current start_number and decrements it after each print.
- Output:
Each row decreases in length sequentially, and numbers decrease from the top down.
Example Output:
If the user inputs 4 for the number of rows, the output will be:
Reverse Floyd’s Triangle:
10
9 8
7 6 5
4 3 2 1