C++ Code Example: diamond pattern

This code is an implementation of printing a diamond pattern made of asterisks. The diamond is formed by two pyramids, one facing up and one facing down.

The program uses two for loops to print each pyramid. The first for loop iterates through each row of the pyramid, and the second for loop prints the asterisks in each row. The first for loop in the upper pyramid starts with i=0, which means that the first row of the pyramid will have no asterisks. The second for loop in the upper pyramid prints 2i-1 asterisks for each row. The first for loop in the lower pyramid starts with i=rows-1, which means that the first row of the lower pyramid will have 2(rows-1)-1 asterisks. The second for loop in the lower pyramid prints 2*i-1 asterisks for each row.

The program also uses a nested for loop to print spaces before printing the asterisks. The number of spaces to print is determined by the current row of the pyramid and the total number of rows.

Overall, the program uses simple nested for loops to print a diamond pattern made of asterisks.

#include <iostream>
using namespace std;

int main() {
    int i, j, rows = 8;

    // upper pyramid
    for (i = 0; i <= rows; i++) {
        for (j = 1; j <= rows - i; j++) {
            cout << ' ';
        }
        for (j = 1; j <= 2 * i - 1; j++) {
            cout << '*';
        }
        cout << "\n";
    }

    // lower pyramid
    for (i = rows - 1; i >= 1; i--) {
        for (j = 1; j <= rows - i; j++) {
            cout << ' ';
        }
        for (j = 1; j <= 2 * i - 1; j++) {
            cout << '*';
        }
        cout << "\n";
    }

    return 0;
}
Output
       *
      ***
     *****
    *******
   *********
  ***********
 *************
***************
 *************
  ***********
   *********
    *******
     *****
      ***
       *