'I want to print the upper half of the butterfly pattern. What is wrong with my code?

#include <iostream>
using namespace std;
int main() {
// your code goes here
for(int j=1;j<= 4;j++)
{
for(int i=1;i<=8;i++)
{if (i<=j)
cout<<"* ";
else if (i+j >= 9)
cout<<"* ";
else
cout<<" ";
}
cout<<endl;
}
return 0;
}
Solution 1:[1]
This does not directly answer the question,
but here is a 2-liner for the above example (Live):
for (auto k : { 1, 2, 3, 4 })
cout << string(k, '*') << string(8 - 2 * k, ' ') << string(k, '*') << endl;
Solution 2:[2]
ok so when I deleted the extra space (in line 7) to be printed after the asterisk then the code worked fine but still, it should work just fine with space too!
Solution 3:[3]
Hello If you want solve this problem in C++ I have the perfect reference code for you.
#include <iostream>
using namespace std;
int main()
{
int x;
cin>>x;
x = 2*x;
for(int i=0;i<=x/2-1;i++){
for(int j=0;j<=x-1;j++){
if (j <= i || j>=x-1-i )
cout<<"*";
else
cout<<" ";
}
cout<<"\n";
}
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Manav Kampani |
| Solution 3 | Vinayak Tripathi |
