How to generate a solid diamond pattern with stars in C++
This shot discusses how to make a diamond pattern in C++ with stars or * (asterisks).
Method
We will use the
Let’s look at the below image to understand this better.
To generate the pattern, as shown above, we will use two nested for loops.
The first for loop will generate the upper half of the diamond, while the second for loop will generate the bottom half of the diamond.
Code
Let’s look at the below code snippet to understand this better. The program requires a number as an input to generate a diamond accordingly.
#include <iostream>using namespace std;int main() {int number, space = 1;cin >> number;space = number - 1;for (int i = 1; i <= number; i++) {for (int j = 1; j <= space; j++)cout << " " ;space--;for (int j = 1; j <= 2*i-1; j++)cout << "*" ;cout << endl;}space = 1;for (int i = 1; i <= number-1; i++) {for (int j = 1; j <= space; j++)cout << " ";space++;for (int j = 1; j <= 2*(number-i)-1; j++)cout << "*";cout << endl;}return 0;}
Enter the input below
Explanation
-
In line 6, we initialize the
numberandspacevariables. -
In line 7, we use
cin >>to take the input asnumber. -
From lines 11 to 19, we initialize nested
forloops that use*to build the upper half of the diamond, i.e., the solid full pyramid. -
From lines 22 to 30, we initialize a second nested
forloop that uses*to generate the lower half of the diamond, i.e., the inverted solid full pyramid.
In this way, we have learned to generate a diamond pattern with stars * in C++.
We can also use numbers, alphabets, or any other characters to generate this pattern.