This shot will discuss how to make a right arrow pattern in C++
using stars (*
).
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.
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
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++.