Related Tags

c++
communitycreator

# How to generate a butterfly pattern using stars in C++

Vinisha Maheshwari

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.

Butterfly Pattern

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 << "*";
else
cout << " ";
if (i >= (2*number-1)-j)
cout << "*";
else
cout << " ";
}
cout << endl;
}

for (int i = 0; i < number; i++) {
for (int j = 0; j < (2*number); j++) {
if(i + j <= number-1)
cout << "*";
else
cout << " ";
if((i+number) <= j)
cout << "*";
else
cout << " ";
}
cout << endl;
}
return 0;
}

Enter the input below

Butterfly pattern using stars in C++

## 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 number using cin >>.

• From lines 8 to 19: the nested for loops takes iterators i and j to iterate through the given number. The if-else statement prints * to generate the left half of the butterfly.

• From lines 22 to 35: similar to above nested for loops, this loop uses * to print the 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.

RELATED TAGS

c++
communitycreator

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time