How to make a right arrow pattern using stars in C++
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.
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 arrowfor (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 << "*";elsecout << " ";}cout << endl;}return 0;}
Enter the input below
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
numberusingcin >>. -
In line 9, we initialize an outer
forloop where we give conditions to run the loopnumbertimes. -
From lines 10 to 14, we initialize an inner
forloop, where we give conditions to run the loopnumbertimes 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++.