How to generate a butterfly pattern using stars in C++
This shot will discuss how to make a butterfly pattern in C++ using stars, i.e., *.
Before moving on, it is advised to go through these articles so that it becomes easy to understand the logic to generate a butterfly pattern.
Methodology
To create this image, we will use nested loops. A nested loop is a loop that contains an inner loop inside an outer loop.
Let’s look at the below image to understand this better.
We will use nested for loops to generate the above illustration.
The first for loop will generate the left half of the butterfly pattern, while the second for loop will generate the right half of the butterfly pattern.
The butterfly is made with two rotated solid half pyramids, one on the left and one on the right.
Code
Let’s look at the below code implementation to understand this better.
#include <iostream>using namespace std;int main() {int number;cin >> number;for (int i = 0; i < number; i++) {for (int j = 0; j < (2*number); j++) {if (i >= j)cout << "*";elsecout << " ";if (i >= (2*number-1)-j)cout << "*";elsecout << " ";}cout << endl;}for (int i = 0; i < number; i++) {for (int j = 0; j < (2*number); j++) {if(i + j <= number-1)cout << "*";elsecout << " ";if((i+number) <= j)cout << "*";elsecout << " ";}cout << endl;}return 0;}
Enter the input below
Explanation
To execute the above code, enter any number as input.
-
In line 5: we initialize the variable
number. -
In line 6: we take the input as a
numberusingcin >>. -
From lines 8 to 19: the nested
forloops takes iteratorsiandjto iterate through the givennumber. Theif-elsestatement prints*to generate the left half of the butterfly. -
From lines 22 to 35: similar to above nested
forloops, this loop uses*toprintthe right half of the butterfly.
In this way, we can generate a butterfly pattern using stars in C++.
Note: We can also use numbers, alphabets, or any other characters to generate this pattern.