This week's book giveaway is in the Big Data forum. We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line! See this thread for details.

OK this is question #5(my third code segment question) for the AP Comp Sci A sample questions:

Consider the following output.

1 1 1 1 1 2 2 2 2 3 3 3 4 4 5

Which of the following code segments will produce this output?

(A) for (int j = 1; j <= 5; j++) { for (int k = 1; k <= 5; k++) { System.out.print(j + " "); } System.out.println(); }

(B) for (int j = 1; j <= 5; j++) { for (int k = 1; k <= j; k++) { System.out.print(j + " "); } System.out.println(); }

(C) for (int j = 1; j <= 5; j ++) { for (int k = 5; k >= 1; k--) { System.out.print(j + " "); } System.out.println(); }

(D) for (int j = 1; j <= 5; j++) { for (int k = 5; k >= j; k--) { System.out.print(j + " "); } System.out.println(); }

(E) for (int j = 1; j <= 5; j++) { for (int k = j; k <= 5; k++) { System.out.print(k + " "); } System.out.println(); }

My analysis:

So we're dealing with two for loops, one embedded within another. All of them output j except for E. I guess I'll have to try out each answer choice and see what each one yields:

A. for j is 1, 2, 3, 4, 5, k is 1, 2, 3, 4, 5 output j So for j = 1, it will output 1 and a space then a blank line then: Well, after thinking about it, I think k needs to be related to j here, otherwise it will just print out 1 2 3 4 5 I'll go on to B.

B. for j is 1, 2, 3, 4, 5, k is 1, 2, 3, 4, 5 ??? output j Here k is related to j. So for j = 1, it will print out 1 and a space, and since k is less than or equal to j, which means k = 1, it will print out: 1 + a blank space. Since k is not incremented when it's more than or equal to j (it says it's increm. when <=), I know this will print out something like this: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5

But that doesn't seem right, because that is outputting k not j. Maybe E is the answer then? C. for j is 1, 2, 3, 4, 5, k is 5, 4, 3, 2, 1 output j Here again k is not in relation to j, so I see the output as being: 1 2 3 4 5 D. for j is 1, 2, 3, 4, 5, k is 5, 4, 3, 2, 1 ??? output j Well I left D for last. If this doesn't make sense, I'm gonna feel like a total idiot. So I'll work it out: 1 1 1 1 1 2 2 2 2 3 3 3 4 4 5 What's unique about this one is not is k decrementing, but it's also in relation to j. This has got to be the answer... *checks back at answer key* it's D. I'm correct!

E. for j is 1, 2, 3, 4, 5, k is 1, 2, 3, 4, 5 output k Just looking at k I think it's the answer, but I have bad reasoning and judgement, so I'll work it out: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 DOH! I'm getting the same answer as in B. Let's go back to C.