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 nested looploops within a loop method to generate this pattern.

Let’s look at the below image to understand this better.

Solid Diamond Pattern

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 number and space variables.

  • In line 7, we use cin >> to take the input as number.

  • From lines 11 to 19, we initialize nested for loops 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 for loop 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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources