Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
solid rhombus
pattern
communitycreator

How to generate a solid rhombus pattern using stars in C++

Vinisha Maheshwari

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.

Solid Rhombus Pattern

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

Solid Rhombus Pattern using stars in C++

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

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

  • In lines 12 and 13, we initialize the for loop. 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 other characters.

RELATED TAGS

c++
solid rhombus
pattern
communitycreator
RELATED COURSES

View all Courses

Keep Exploring