Related Tags

c++
loop
nested
communitycreator

# How to generate a solid half diamond pattern with stars in C++

Vinisha Maheshwari

This shot will discuss how to make a solid half diamond pattern in C++ with stars, or * (asterisks).

## Method

We will use nested loopsloop within a loop to generate this pattern.

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

Solid Half Diamond Pattern

To make a solid half diamond, we will use two 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 code snippet below to understand better. The program requires a number as an input to generate a diamond accordingly.

#include <iostream>
using namespace std;

int main() {

int number;
cin >> number;

for (int i = 1; i <= number; i++) {
for (int j = 1; j <= number-i; j++) {
cout << " ";
}

for (int j = 1; j <= i; j++) {
cout << "*";
}
cout << endl;
}

for (int i = number-1; i > 0; i--) {
for (int j = 1; j <= number-i; j++) {
cout << " " ;
}

for (int j = 1; j <= i; j++) {
cout << "*" ;
}
cout << endl;
}

return 0;
}

Enter the input below

## Explanation

• In line 7, we initialize the number variable.

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

• From lines 9 to 18, we initialize nested for loops that use * to build the upper half of the pyramid.

• From lines 20 to 29, we initialize a second nested for loop that uses * to generate the lower half of the pyramid.

In this way, we learned to generate a solid half diamond pattern with * in C++.

We can also use numbers, alphabets, or any other characters to generate this pattern.

RELATED TAGS

c++
loop
nested
communitycreator

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time