Kylian Murphy Kylian Murphy - 1 month ago 13
Java Question

Printing triangles using nested loop in Java

I'm trying to print a certain triangle in Java by using Nested Loops and I am having difficulty. Could somebody give me a hand or just show me how it's done?

The triangle is:

123456654321
1234554321
12344321
123321
1221
11


I can print a triangle like

123456
12345
1234
123
12
1


Though I'm not sure how to reverse and make my loops count down afterwards.

PEF PEF
Answer

This works:

public class Main {
    public static void main(String args[]) {
        int n = 6;
        while (n > 0) {
            for (int i = 1; i <= n; i++) {
                System.out.print(i);
            }
            for (int i = n; i > 0; i--) {
                System.out.print(i);
            }
            System.out.println("");
            n--;
        }
    }
}

The second for loop assigns n to the iterator int i, executes the statements within the curly brackets, then decrements i using i-- until the condition i > 0 is no longer true.

Comments