Description:

In this C++ example, we demonstrate how to print a diamond made out of asterisks in the console window. Our function for printing the diamond consists of two main loops: the first one expands number of asterisks printed in the diamond (top half), the second contracts the number back to one (bottom half). The inner loops print the spaces which precede the asterisk and the asterisks themselves, respectively. In our main function, we demonstrate the printing with a call to PrintDiamond() with an argument value of 5.

Example

#include <iostream>

void PrintDiamond(int iSide) {
    using namespace std;
    int iSpaces = iSide;
    int iAsterisks = 1;
    // Output the top half of the diamond
    for (int iI = 0; iI < iSide; ++iI) {
        for (int iJ = 0; iJ < iSpaces; ++iJ) {
            cout << " ";
        }
        for (int iJ = 0; iJ < iAsterisks; ++iJ) {
            cout << "*";
        }
        cout << endl;
        --iSpaces;
        iAsterisks += 2;
    }
    // Output the bottom half of the diamond
    for (int iI = 0; iI <= iSide; ++iI) {
        for (int iJ = 0; iJ < iSpaces; ++iJ) {
            cout << " ";
        }
        for (int iJ = 0; iJ < iAsterisks; ++iJ) {
            cout << "*";
        }
        cout << endl;
        ++iSpaces;
        iAsterisks -= 2;
    }
}

int main()
{
    // Print a diamond with side = 5
    PrintDiamond(5);

    return 0;
}

Output:

Print Diamond Output