nj92 nj92 - 6 months ago 20
Java Question

How to write the loop in java for the output shown below?

I need help to write java code that will display the output as the picture shown

enter image description here

Answer
for(int i = 0; i < 6; i++) {
    for(int j = 0; j < 13; j++) {
        if(j == i * 2 + 1) {     
            System.out.print(" - ");
        }
        else {
            System.out.print("*");
        }
    }
    System.out.println();
}

First for-loop is for each row. (This is why this loop ends with System.out.println() to skip to the next row.) The inner for-loop is for the output each row should print. Here you find the if(j == i * 2 + 1) statement. If j is equal to i * 2 + 1, it should print the " - ". (Check it yourself for each value of i and j.).