Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
communitycreator

Generate a left arrow pattern using stars in C++

Vinisha Maheshwari

In this shot, we will discuss how to make a left arrow pattern in C++ using stars.

Approach

We will use a nested loop to generate this pattern. A nested loop means there is an outer loop inside of which there is another loop called the inner loop.

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

Left Arrow Pattern

We will generate the left arrow pattern, as shown in the image. We use the for loop to print the center horizontal, upper left, and bottom left diagonal line to generate the left arrow pattern in C++.

Code

Let’s look at the below code snippet to clarify.

#include <iostream>
using namespace std;

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

Enter the input below

Generate a left arrow pattern using stars in C++

Please enter a number above to generate the size of the output.

Explanation

  • In line 5, we initialize the variable number.

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

  • In line 8, we initialize an outer for loop, where we have given conditions to run the loop number times.

  • From lines 10 to 16, we initialize an inner for loop where we have given conditions to run the loop number times to print the center horizontal line, upper left diagonal, and bottom left diagonal to generate a left arrow pattern.

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

We have now learned to generate a left arrow pattern using stars in C++.

RELATED TAGS

c++
communitycreator
RELATED COURSES

View all Courses

Keep Exploring