33.6k views
5 votes
I don't understand how to write code for this in Java using nested for loops only. The official question is: write a program that produces the following hourglass figure using nested for loops?

I don't understand how to write code for this in Java using nested for loops only-example-1

1 Answer

2 votes

Answer:

public class Triangle

{

public static void main( String[] args )

{

show( 5 );

}

public static void show( int n )

{

int i,j,k;

for (i = 0; i < n - 1; i++ )

{

for (j = 0; j < i; j++ )

{

System.out.print( " " );

}

for (k = n - i; k > 0; k-- )

{

System.out.print( "* " );

}

System.out.println();

}

for (i = 0; i < n; i++ )

{

for (j = n - i; j > 1; j-- )

{

System.out.print( " " );

}

for (k = 0; k < i + 1; k++ )

{

System.out.print( "* " );

}

System.out.println();

}

User Revell
by
6.2k points