Home > front end >  Below pattern code is not working as expected
Below pattern code is not working as expected

Time:10-01

The below pattern code is not working as expected.

public class pattern_print {
    public static void main (String args[]){
        int i = 1, j = 5, n = 5;
        while (i <= n) {
            while (j >= i) {
                System.out.print("*");
                j--;
            }
            System.out.print("\n");
            i  ;
        }
    }
}

Who can help me?

CodePudding user response:

What are you expecting? The code that you wrote is displaying the following chars:

*****

If you want to display something like:

*****
****
***
**
*

Then the correct code is:

public class pattern_print {

public static void main (String args[]){

int i=1,j=5,n=5;

while (i<=n){

while (j>=i){

System.out.print("*");

j--;

}

System.out.print("\n");
j=5;
i  ; }

}
}

Now depends what you expect to be displayed.

CodePudding user response:

If the following triangle pattern is expected:

*****
****
***
**
*

the value of j needs to be reset to n as Andreea Frincu suggested.

However, for loops may be more preferable when printing patterns. Also, since Java 11 released back in Sep 2018 there is method String::repeat which allows to avoid redundant nested loops and the same triangle pattern may be printed as simply as:

for (int i = 5; i >= 0; i--) {
    System.out.println("*".repeat(i));
}
  • Related