How to generate a hollow rhombus pattern using stars in C++.
In this shot, we will discuss how to make a hollow rhombus pattern using stars * in C++.
Methodology
A nested loop means loop calling another loop. We will use a nested loop to make the hollow rhombus pattern in C++.
Let’s look at an image of the pattern that we will generate.
We will use for loop to generate this hollow rhombus pattern. In this loop, we will give conditions to print * on the edges of the rhombus and space ( ) inside the rhombus.
Code
Let’s see the code below to understand it better.
#include <iostream>using namespace std;int main() {int number;cin>> number;for (int i=0; i < number; i++){for (int j=0; j < number - i; j++)cout << " ";for (int j=0; j < number; j++){if (i == 0 || i == number-1 || j == 0 || j == number-1)cout << "*" ;elsecout << " " ;}cout << endl ;}return 0;}
Enter the input below
Explanation
Please enter a number above to generate an output.
-
In line 5, we have initialized the variable
number. -
In line 6, we take the input as
number. -
In line 7, we have initialized an outer
forloop. Here we have given a condition to run the loop fornumbertimes. -
In line 9, we have initialized an inner
forloop. Here we have given conditions to run the loop fornumber - itimes to print space. -
From lines 11 to 17, we have initialized the
forloop. Here we have given conditions to print*at the edges of the rhombus i.e., upper horizontal, bottom horizontal, left diagonal, and right diagonal. We will print a space() for the rest of the positions. -
In line 18, we print a next line character. This is done so that the
*or( )gets printed from the next line onwards.
In this way, we can use loops to make a hollow rhombus pattern in C++.
This pattern can also be made with
numbers,alphabets, or any othercharacters.