Tristan
Tristan

Reputation: 1

Nested for loop in descending order - Java

I managed to get the output to almost get what I want but I am not sure what needs to be modified to make the value in the middle to be x.

98765
87654
76543
65432
54321

The above is the output I got but I want it to display

98765
87654
76x43
65432
54321

Here is the code

for(int row=9;row>=5; row--) {
    for(int col = row; col >=(row + 1 - 5); col--) {
        System.out.printf("%d",col);
    }
    System.out.println();
}

I would appreciate it if anyone could fix my code or at least tell me what to edit to get that output.

Upvotes: 0

Views: 223

Answers (1)

Wais Kamal
Wais Kamal

Reputation: 6180

Use an if statement inside your loop:

for (int row = 9; row >= 5; row--) {
    for (int col = row; col >= (row - 4); col--) {
        if(row == 7 && col == 5) {
            System.out.print("x");
        } else {
            System.out.printf("%d", col);
        }
    }
    System.out.println();
}

Upvotes: 1

Related Questions