Print Butterfly Pattern Program in C++

Hello Learners,

In this article, we are going to learn how to Print a Solid Butterfly Pattern using C++. This pattern is possible and easy to understand in C++.
let us understand first what is a Butterfly Pattern?
We will print this pattern by using asterisks/stars (*). The size of the pattern will be dependent on the user in how many rows he/she wants in this particular pattern. It is an interesting pattern made out of stars that will look exactly like a Butterfly. This pattern checks how much your logic has been developed in pattern programming. It comes under hard difficulty level programming.
Now, let us see an example:

butterfly pattern in C++

The above Butterfly Pattern is containing 5 rows which will be entered by the user.

C++ program to print Butterfly Pattern

We can print this pattern by using “for loop and Nested for loop”. Firstly, we will print stars in increasing order and in the pyramid form to obtain the required shape. Then, spaces and then again stars in the pyramid form. We will write codes of spaces and stars only for half of the pattern as the lower part of the pattern is a mirror image of the upper part. So, if we reverse the first loop then we will get the same shape as of upper one. Let us understand this by source code:

#include<iostream>
using namespace std;

int main()
{
  int r,i,j;
  cout<<"Enter no. of rows: ";
  cin>>r;
  
  for(i=1;i<=r;i++)
  {
    for(j=1;j<=i;j++)
    cout<<"*";
    for(j=1;j<=2*(r-i);j++)
    cout<<" ";
    for(j=1;j<=i;j++)
    cout<<"*";
    cout<<"\n";
  }
    for(i=r;i>=1;i--)
  {
    for(j=1;j<=i;j++)
    cout<<"*";
    for(j=1;j<=2*(r-i);j++)
    cout<<" ";
    for(j=1;j<=i;j++)
    cout<<"*";
    cout<<"\n";
  }
  return 0;
}

In the above code i, j are the integer variables that will control the loops and r is the number of rows entered by the user.
i-loop will control rows of this pattern whereas j-loop will print spaces and stars as per requirement. We will need to apply some logic in the printing of those stars and spaces which are already given in codes. By tracing them, you can easily get your hands on them. It is written in a very minimal and easy way which makes it beginner-friendly and fun to learn.

Now, let us see and example in output screen after executing it:

Enter no. of rows: 10

print butterfly pattern in C++

In this way, you can print a Butterfly Pattern by using C++ language. I hope it was easy enough to understand. If you have any doubt, feel free to ask in the comment section. All the best!

You may also learn:

THANK YOU!
Regards,
Isha Rani Prasad
Codespeedy Pvt. Ltd.

Leave a Reply

Your email address will not be published. Required fields are marked *