How to print a butterfly pattern for a given value
Here we are assuming n=10 .
First part :
for the first half of the pattern we are printing "*" which is equal to row number . then we print " " which is equal to 2*(n-row number). and after that we again print "*" which is equal to row number .
for first row i=1 and n=10 (given)
so at first we print one star and then print 2*(n-i) = 2*(10-1) =18 space. and then again print 1 star.
for the second row i=2 and n=10
so at first we print two(i) stars and then print 2*(n-i) = 2*(10-2) =16 space. and then again print two stars.
after completing each row we start from a new line .
we are following this pattern upto row number 10 .
for(int i=1;i<=n;i++)
{
for(int j=1 ;j<=i;j++)
{
System.out.print("*");
}
for(int j=1 ;j<=2*(n-i);j++)
{
System.out.print(" ");
}
for(int j=1 ;j<=i;j++)
{
System.out.print("*");
}
System.out.println();
}
Second part :
for second part we have to reverse the logic .
so for the first row of the second part we assuming i=n=10
so we are printing i=n=10 number of stars and then 2*(n-i)= 2*0=0 number of space and then again i=n=10 number of star
so for the second row of the second part we assuming i=n=9
so we are printing i=n=9 number of stars and then 2*(n-i)= 2*1=2 number of space and then again i=n=9 number of star .
and we are repeating this for n times
for(int i=n;i>0;i--)
{
for(int j=1 ;j<=i;j++)
{
System.out.print("*");
}
for(int j=1 ;j<=2*(n-i);j++)
{
System.out.print(" ");
}
for(int j=1 ;j<=i;j++)
{
System.out.print("*");
}
System.out.println();
}
Full Code :
import java.lang.*; import java.util.*; public class butterflyPattern { public static void main(String[] args) { System.out.println("Enter the number : "); Scanner sc= new Scanner(System.in); int n = sc.nextInt();
for(int i=1;i<=n;i++) { for(int j=1 ;j<=i;j++) { System.out.print("*"); } for(int j=1 ;j<=2*(n-i);j++) { System.out.print(" "); } for(int j=1 ;j<=i;j++) { System.out.print("*"); } System.out.println(); }
for(int i=n;i>0;i--) { for(int j=1 ;j<=i;j++) { System.out.print("*"); } for(int j=1 ;j<=2*(n-i);j++) { System.out.print(" "); } for(int j=1 ;j<=i;j++) { System.out.print("*"); } System.out.println(); }
} }
Post a Comment
0 Comments