In a recent interview I have been asked to write a program to generate the following output:
* * * * *
* * * *
* * *
* *
*
* *
* * *
* * * *
* * * * *
I had written the following code in java
public class Triangle
{
public static void main( String[] args )
{
show( 5 );
}
public static void show( int n )
{
for ( int i = 0; i < n - 1; i++ )
{
for ( int j = 0; j < i; j++ )
{
System.out.print( " " );
}
for ( int k = n - i; k > 0; k-- )
{
System.out.print( "* " );
}
System.out.println();
}
for ( int i = 0; i < n; i++ )
{
for ( int j = n - i; j > 1; j-- )
{
System.out.print( " " );
}
for ( int k = 0; k < i + 1; k++ )
{
System.out.print( "* " );
}
System.out.println();
}
}
}
But the interviewer was not happy. He asked me minimize the number variables I had used. I didn't found a way. Anyone could help? Also, could there be a possibility to optimize the iteration here?