maltuin
maltuin

Reputation: 11

Trouble understanding parts of this code using for-loops?

public class PA4 {
    public static void main(String[] args) {
        for (int line = 1; line <= 6; line++) {
            for (int j = 1; j <= (line - 1); j++) {
                System.out.print(".");
        }
        System.out.print(line);
        for (int j = (line + 1); j <= 6; j++) {
            System.out.print(".");
        }

        System.out.println();
    }
}
}

This code produces this output:

1.....

.2....

..3...

...4..

....5.

.....6

I understand the first loop and how it prints the dots by subtracting one from each line but I can't understand how the second loop works and how it prints the dots, or how assigning "j" the value of "line + 1" does whatever it's doing.

Upvotes: 0

Views: 59

Answers (2)

Zag
Zag

Reputation: 638

Maybe this is clearer; it does the same thing.

public class PA4 {
    public static void main(String[] args) {
        for (int line = 1; line <= 6; line++) {
            for (int j = 1; j <= 6; j++) {
                if (j == line)
                    System.out.print(line);
                else
                    System.out.print(".");
            }
        System.out.println();
        }
    }
}

Your inner portion (two loops plus), together, always count up to 6, printing dots and one number. But they do it by counting up to line-1, then printing the number, then printing more dots, counting from just after the number up to 6. I've done it above in a single loop, but it's the same thing.

Upvotes: 1

Scary Wombat
Scary Wombat

Reputation: 44834

Corrected indentation

for (int line = 1; line <= 6; line++) {
    for (int j = 1; j <= (line - 1); j++) {
        System.out.print(".");
    }
    System.out.print(line);
    for (int j = (line + 1); j <= 6; j++) {
        System.out.print(".");
    }

    System.out.println();
}

replacing with a hard-coded value

// for three it would be
for (int j = 1; j <= (2); j++) {  // personally I would do j < 3
    System.out.print(".");
}
System.out.print(3);
for (int j = (4); j <= 6; j++) {
    System.out.print(".");
}
System.out.println();   

output

..3...

Upvotes: 0

Related Questions