diamond star pattern in cpp

Here is an example of how to create a diamond star pattern using C++:

#include <iostream>
using namespace std;

int main() {
    int n, i, j, space = 1;

    cout << "Enter number of rows: ";
    cin >> n;

    space = n - 1;

    for (j = 1; j<= n; j++) {
        for (i = 1; i<= space; i++) {
            cout << " ";
        }
        space--;
        for (i = 1; i <= 2 * j - 1; i++) {
            cout << "*";
        }
        cout << endl;
    }

    space = 1;

    for (j = 1; j<= n - 1; j++) {
        for (i = 1; i<= space; i++) {
            cout << " ";
        }
        space++;
        for (i = 1; i<= 2 * (n - j) - 1; i++) {
            cout << "*";
        }
        cout << endl;
    }

    return 0;
}

Explanation:

  1. First, we include the necessary header file iostream to use the input/output stream.
  2. We declare the main function where our program execution begins.
  3. We declare variables n, i, j, and space. n represents the number of rows, i and j are loop counters, and space represents the number of spaces in each row.
  4. We prompt the user to enter the number of rows using the cout object and then store the input in the variable n using the cin object.
  5. We set the value of space to n - 1 to determine the number of spaces in the first row.
  6. We start a loop for the upper half of the diamond pattern, which runs n times. In each iteration, we print the required number of spaces using the nested for loop and then decrement the value of space by 1.
  7. Inside the nested loop, we print a space using the cout object.
  8. After the nested loop, we start another nested loop to print the asterisks () in each row. The number of asterisks is given by the formula 2 j - 1.
  9. Finally, we print a newline character using cout << endl; to move to the next row.
  10. After the upper half is printed, we reset the value of space to 1 for the lower half of the diamond.
  11. We start another loop for the lower half, which runs n - 1 times. In each iteration, we print the required number of spaces using the nested for loop and then increment the value of space by 1.
  12. Inside the nested loop, we print a space using the cout object.
  13. After the nested loop, we start another nested loop to print the asterisks () in each row. The number of asterisks is given by the formula 2 (n - j) - 1.
  14. Finally, we print a newline character using cout << endl; to move to the next row.
  15. We return 0 from the main function to indicate successful program execution.