Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

I am new to Java and stuck with this assignment, Although I have completed it somehow but I want to do it without the if-else statement.

 for(int i=0; i<numRows; i++) 

  {

     for(int j=0; j<numRows-i; j++) 

     {

         System.out.print(" ");

     }

    for(int k = 0; k <= i*2; k++) 

    {

    if(k%2 == 1)

        System.out.print("A");

    else

        System.out.print("*");

    }

        System.out.println();  

}

Output:

    *

   *A*

  *A*A*

 *A*A*A*

*A*A*A*A*

1 Answer

0 votes
by (13.1k points)

Since each row starts with an asterisk and then repeats A* n times. You can do that in your loop, i.e. print the first asterisk and then repeat A* as often as needed.

Example:

for( int i = 0; i < numRows; i++ )

{

  //print whitespace for correct indentation

  for( int j = 0; j < numRows - i; j++ )

  {

    System.out.print( " " );

  }

  //print the first asterisk

  System.out.print( "*" );

  //print as many A* as needed, i.e. row-1 times 

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

  {

    System.out.print( "A*" );        

  }

  System.out.println();

}

Want to learn Java? Check out the Java certification from Intellipaat.

Related questions

0 votes
1 answer
asked Feb 18, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 13, 2019 in Java by Anvi (10.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...