How to generate a solid rhombus pattern using stars in C++
In this shot, we will discuss how to make a solid rhombus pattern using stars in C++.
Approach
A nested loop refers to a loop that calls another loop.
We will use a nested loop to make the solid rhombus pattern in C++.
Let’s look at an image of the pattern that we want to generate.
We use the for loop to generate this solid rhombus pattern. In the loop, we give conditions to print * on the edges and inside the rhombus.
Code
Let’s look at the code below to understand this 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++)cout << "*" ;cout << endl ;}return 0;}
Enter the input below
Please enter a number above to generate an output.
Explanation
-
In line 5, we initialize the variable
number. -
In line 6, we take the input as
number. -
In line 7, we initialize an outer
forloop. Here, we have given a condition to run the loop fornumbertimes. -
In line 9, we initialize an inner
forloop. Here, we have given conditions to run the loop fornumber-itimes to print space. -
In lines 12 and 13, we initialize the
forloop. Here we have given conditions to print*at the edges as well as inside the rhombus. -
In line 15, we print a next line character. We do this so that the
*is printed from the next line onwards.
In this way, we can use loops to make a solid rhombus pattern in C++.
This pattern can also be made with
numbers,alphabets, or any othercharacters.