This code generates a number pyramid pattern, consisting of two parts: an ascending sequence in the top half and a descending sequence in the bottom half. The pattern uses nested loops and outputs increasing numbers within each row.
int rows = 8; // set the number of rows to 8
// Print the top half of the pyramid with increasing numbers
for (int i = 0; i <= rows; i++) { // loop through each row
for (int j = 1; j <= i; j++) { // loop through each column in the row
cout << j << " "; // print the current column number followed by a space
}
cout << endl; // move to the next line after printing all the columns in the current row
}
// Print the bottom half of the pyramid with decreasing numbers
for (int i = rows - 1; i >= 1; i--) { // loop through each row in reverse order
for (int j = 1; j <= i; j++) { // loop through each column in the row
cout << j << " "; // print the current column number followed by a space
}
cout << endl; // move to the next line after printing all the columns in the current row
}
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
int rows = 8; // set the number of rows to 8
rows
determines the total height of the pyramid. In this case, it is set to 8 rows.for (int i = 0; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
cout << j << " ";
}
cout << endl;
}
for (int i = 0; i <= rows; i++)
):rows
(inclusive).i
represents the current row number.for (int j = 1; j <= i; j++)
):i
for the current row.cout << endl;
):Example Output for the Top Half (rows = 4
):
1
1 2
1 2 3
1 2 3 4
for (int i = rows - 1; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
cout << j << " ";
}
cout << endl;
}
for (int i = rows - 1; i >= 1; i--)
):rows - 1
down to 1.i
represents the current row number.for (int j = 1; j <= i; j++)
):i
for the current row.cout << endl;
):Example Output for the Bottom Half (rows = 4
):
1 2 3
1 2
1
For rows = 4
, the complete pattern looks like this:
1
1 2
1 2 3
1 2 3 4
1 2 3
1 2
1