Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
communitycreator

How to make a right arrow pattern using stars in C++

Vinisha Maheshwari

This shot will discuss how to make a right arrow pattern in C++ using stars (*).

Approach

We will use nested loops to generate this pattern. A nested loop is an outer loop that contains an inner loop.

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

Right Arrow Pattern

To generate the above pattern, we have to use a nested for loop to first print the center horizontal line. Then, the upper right and bottom right diagonal lines complete the figure.

Code

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

#include <iostream>
using namespace std;

int main() {
  int number;
  cin >> number;
  
  // right arrow
  for (int i = 0; i <= number; i++) {
    for (int j = 0; j < number; j++) {
      if (i == number/2 || j - i == number/2 || i + j == number/2 *3)
        cout << "*";
      else 
        cout << " ";
    }
    cout << endl;
  }
  
  return 0;
}

Enter the input below

Right Arrow Pattern using stars in C++

Explanation

To run the code, enter any whole number in the input box.

  • In line 5, we initialize the variable number.

  • In line 6, we take the input as a number using cin >>.

  • In line 9, we initialize an outer for loop where we give conditions to run the loop number times.

  • From lines 10 to 14, we initialize an inner for loop, where we give conditions to run the loop number times to print the center horizontal line, upper right diagonal, and bottom-right diagonal to generate a right arrow pattern.

  • In line 16, we print a next line character to print the * or ( ) from the next line onwards.

In this way, we have learned to generate a right arrow pattern using stars in C++.

RELATED TAGS

c++
communitycreator
RELATED COURSES

View all Courses

Keep Exploring