C++ Code Example: triangle pattern

This code prints a triangle pattern with numbers. It starts with a triangle of increasing numbers from 1 to 8 and then prints a triangle of decreasing numbers from 1 to 7. Here’s how the code works:

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