0

Which of the following program fragments will produce this output? (Ignore Spacing)

2-----
-4----
--6---
---8--
----10-
-----12

Imagine if the rows and columns were perfectly aligned.

for (int i = 1; i <= 6; i++) {

        for (int k = 1; k <= 6; k++) 
            if (k == i) 
                System.out.print(2 * k);
            else 
                System.out.print("-");


        System.out.println("");

    }

How is the code fragment above going to print that?

2-
-
-
-
-
-
4-

The above is... what I believe the code fragment should print because I'm not sure where the pointer indicating where I insert the next symbol goes after looping the inner loop once by increasing k from 1 to 6. How am I wrong?

1 Answers1

1

A for loop without braces only applies to the next statement (which is an if and else). If you add braces then your example looks like

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

So, the inner loop prints 6 things one of which is 2 * k (when k equals i) or a -. Then the next statement adds a newline. It's important to note that Java doesn't have pointers.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • if java doesn't have pointers, then when does java have a nullpointer exception error? –  Jan 01 '15 at 23:22
  • @CrazyRaisans Because Java is implemented in C++, and C++ does have pointers. That **really** should have been a `NullReferenceException` (Java does have references because the value of an `Object` instance is its' reference). – Elliott Frisch Jan 01 '15 at 23:24
  • @CrazyRaisans A null pointer exception just means that you're trying to reference a null object. For example, if you have a string set equal to null, and then try to reference it later, then you would get a null pointer exception. It's really null reference exception because you're referencing an object that is null (not pointing to it). –  Jan 01 '15 at 23:27