Generate a left arrow pattern using stars in C++
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.
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 arrowfor (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 <<"* ";elsecout <<" ";}cout << endl;}return 0;}
Enter the input below
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
forloop, where we have given conditions to run the loopnumbertimes. -
From lines 10 to 16, we initialize an inner
forloop where we have given conditions to run the loopnumbertimes 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++.