Printing a sideways triangle in java
Posted
by Will
on Stack Overflow
See other posts from Stack Overflow
or by Will
Published on 2010-03-23T06:42:25Z
Indexed on
2010/03/23
6:53 UTC
Read the original article
Hit count: 350
I'm trying to print a sideways triangle in java. If the user enters 5, the output should be:
*
***
*****
***
*
If the user enters 6, the output should be:
*
***
*****
*****
***
*
I've gotten it to work for the case when the user enters 5, 3, or 1 but my code seems to work for those three cases only. I was wondering if anyone could help me get my code working for more cases. Here it is:
public void printArrow( int n )
{ int asterisks = 1;
for ( int i = 0; i <= n/2; i++ )
{
for ( int j = i; j < asterisks; j++ )
{
System.out.print( "*" );
}
asterisks += 3;
System.out.println();
}
asterisks = asterisks / 2 - 2;
for ( int i = 0; i < n/2; i++ )
{
for ( int k = i; k < asterisks; k++ )
{
System.out.print( "*" );
}
if ( i == 1 )
{
System.out.print( "*" );
}
asterisks -= 2;
System.out.println();
}
}
© Stack Overflow or respective owner