Suppose you want to draw Following pattern in java...But the que. is how..?
let's view logic behind this pattern...
*
* * *
* * * * *
* * * * * * *
* * *
* * * * *
* * * * * * *
consider j = *, i=row
so when ,
i=1, j=1
i=2, j=3
i=3, j=5... and so on...
so from above we get j= (2*i) - 1
now let do same thing for white space which are used before the *...
let take j=white space and i=row
so when...
i=1, j=3
i=2, j=2
i=3, j=1...nd so on...
so we got... j = n - i
so now lets write program using above equation...
class pattern
{
public static void main(String [] args)
{
int i,j,n=5;
System.out.println("hi");
for(i=1;i<=5;i++)
{
for(j=i-1;j>0;j--)
{
System.out.print(" ");
}
for(j=(n-i)*2+1;j>0;j--)
{
System.out.print("*");
}
System.out.println();
}
}
}
output :-
*
* * *
* * * * *
* * * * * * *
* * *
* * * * *
* * * * * * *
0 comments :
Post a Comment