C++ Code Example: Triangle Pattern

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.

Code Example

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
}

Output

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 

Code Explanation

1. Initialization

int rows = 8; // set the number of rows to 8
  • The variable rows determines the total height of the pyramid. In this case, it is set to 8 rows.

2. Top Half of the Pyramid

for (int i = 0; i <= rows; i++) {
    for (int j = 1; j <= i; j++) {
        cout << j << " ";
    }
    cout << endl;
}
  • Outer Loop (for (int i = 0; i <= rows; i++)):
    • Iterates through the rows of the top half, starting from 0 up to rows (inclusive).
    • i represents the current row number.
  • Inner Loop (for (int j = 1; j <= i; j++)):
    • Prints numbers from 1 to i for the current row.
    • Each number is followed by a space for proper alignment.
  • End of Row (cout << endl;):
    • Moves to the next line after printing all numbers for the current row.

Example Output for the Top Half (rows = 4):

1
1 2
1 2 3
1 2 3 4

3. Bottom Half of the Pyramid

for (int i = rows - 1; i >= 1; i--) {
    for (int j = 1; j <= i; j++) {
        cout << j << " ";
    }
    cout << endl;
}
  • Outer Loop (for (int i = rows - 1; i >= 1; i--)):
    • Iterates through the rows of the bottom half in reverse, starting from rows - 1 down to 1.
    • i represents the current row number.
  • Inner Loop (for (int j = 1; j <= i; j++)):
    • Prints numbers from 1 to i for the current row.
    • Like in the top half, each number is followed by a space.
  • End of Row (cout << endl;):
    • Moves to the next line after printing all numbers for the current row.

Example Output for the Bottom Half (rows = 4):

1 2 3
1 2
1

4. Combined Output

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