Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
communitycreator
hollow rhombus
pattern

How to generate a hollow rhombus pattern using stars in C++.

Vinisha Maheshwari

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.

Hollow Rhombus Pattern

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 << "*" ;
      else 
        cout << " " ;
    }
    cout << endl ;
  }
  return 0;
}

Enter the input below

Generate a hollow rhombus pattern using stars in C++

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 for loop. Here we have given a condition to run the loop for number times.

  • In line 9, we have initialized an inner for loop. Here we have given conditions to run the loop for number - i times to print space.

  • From lines 11 to 17, we have initialized the for loop. 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 other characters.

RELATED TAGS

c++
communitycreator
hollow rhombus
pattern
RELATED COURSES

View all Courses

Keep Exploring