This program generates a symmetrical triangle pattern of asterisks (*
) based on the number of rows entered by the user. The pattern consists of two parts: an ascending section followed by a descending section. It demonstrates the use of nested for
loops to control the number of asterisks printed per row and provides a simple example of working with loops and user input in C++.
#include <iostream>
using namespace std;
int main() {
// Get the number of rows from the user
int num_rows;
cout << "Enter the number of rows: ";
cin >> num_rows;
// Display the left arrow pattern
for (int i = 1; i <= num_rows; i++) {
for (int j = 1; j <= i; j++) {
cout << "*";
}
cout << endl;
}
for (int i = num_rows - 1; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
cout << "*";
}
cout << endl;
}
return 0;
}
*
**
***
****
*****
****
***
**
*
In this code, the user is prompted to enter the number of rows for the left arrow pattern. The first for
loop is responsible for printing the top half of the pattern, and the second for
loop prints the bottom half. The inner for
loops within each outer loop are used to print the desired number of asterisks (*) for each row. The cout << "*";
statement prints an asterisk. The endl
statement is used to move to the next line after each row.