# Code segment question #3(5)

Daniel Lucas
Ranch Hand
Posts: 48
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.

NOTE: I FOUND THE RIGHT ANSWER IN D.

Shaan Shar
Ranch Hand
Posts: 1249
Daniel Lucas,

I didn't get you properly.. But yes that is sure that right answer

is 'D'....... If you have any concern about D or any other answer then

revert us back with proper indentations..... I mean to say that with proper

arguments.....