C++ Code Example: christmas tree pattern

This program prints a diamond shape made of stars (*) and vertical bars (|). It uses nested loops to iterate over the rows and columns of the diamond.

Here’s a breakdown of how the program works:

  1. Define a variable n to set the size of the diamond.
  2. Use a for loop to iterate over the rows of the diamond, from 0 to n-1.
  3. Use another for loop to print spaces before the first star on each row. The number of spaces printed depends on the current row number (i).
  4. Print a star to start the row.
  5. Use a for loop to print vertical bars before the center of the diamond. The number of vertical bars printed depends on the current row number (i).
  6. Use another for loop to print vertical bars after the center of the diamond. The number of vertical bars printed depends on the current row number (i).
  7. Print a star after the center of the diamond, but only if the row is not the top row.
  8. Move to the next line to start a new row.

The result is a diamond shape made of stars and vertical bars, with the number of vertical bars increasing and then decreasing as the rows move away from the center.

#include <iostream>
using namespace std;

int main() {
    int n = 10, i, j, k;

    for (i = 0; i < n; i++) {
        for (j = 1; j <= n - i; j++) {
            cout << " ";
        }
        cout << "*";
        for (k = 0; k <= i - 1; k++) {
            cout << "|";
        }
        for (j = 1; j < i; j++) {
            cout << "|";
        }

        if (i > 0) {
            cout << "*";
        }
        cout << endl;
    }
}
Output
          *
         *|*
        *|||*
       *|||||*
      *|||||||*
     *|||||||||*
    *|||||||||||*
   *|||||||||||||*
  *|||||||||||||||*
 *|||||||||||||||||*