1

Why is the output of this program 1 1 2 2 3 3 instead of 1 1 2 2 3 1

class Scratch {
    public static void main(String[] args) {
        int[] a = { 1, 2, 3, 4, 5, 3 };
        for (int i = 0; i < 6; i++)
            System.out.print(a[i / 2] + " ");
    }
}

When you divide 3/2 it equals 1.5, which I thought Java only took the first value of an integer number. What's going on?

Makoto
  • 104,088
  • 27
  • 192
  • 230

5 Answers5

4

You are dividing the index not the value. To get the result you're looking for, you should take the division outside the square brackets:

System.out.print(a[i] / 2 + " ");
// Here --------------^
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • I wholly believe that the point is to divide the index accesses here, or they'd get 0 for the first value. – Makoto Apr 18 '18 at 17:20
  • who downvoted this and why? This is right on. – EJK Apr 18 '18 at 17:20
  • 1
    @EJK: You'd get `0 1 1 2 2 1` instead, which does *not* agree with anything the OP is even saying. – Makoto Apr 18 '18 at 17:21
  • 1
    @Makoto - I guess the post is a bit unclear. The OP did say "because when you divide 3/2.." which implies the intent is to process the value, not the index. But your point is correct as well. – EJK Apr 18 '18 at 17:23
  • @EJK: I would strongly disagree that the post isn't clear. You can read it a bit fast and *assume* things, but that's really not the question's fault... – Makoto Apr 18 '18 at 17:24
2

The last iteration of the loop will be when i = 5. 5/2 = 2. a[2] = 3.

chevybow
  • 9,959
  • 6
  • 24
  • 39
2

Because the last number of your loop is 5. Then 5/2 = 2.5 which java turns into 2. If you see your array, it came up that in the position 2, the number printed is 3.

Glim
  • 361
  • 1
  • 10
2

I think the mistake you're making is that you're thinking of the values stored in the array being divided by 2, not the index. Or really moreso, you're letting the fact that the value 3 is not what you would expect the last value in the array would be, affect your perception of what the array look-up should yield. It's important to keep those separate.

Your code is looking up (0, 1, 2, 3, 4, 5) all divided by two which is (0, 0, 1, 1, 2, 2) with integer division. That is, a[5 / 2] = a[2] = 3.

thesquaregroot
  • 1,414
  • 1
  • 21
  • 35
1

i / 2 is an integer division which will effectively take the floor of the produced value by discarding the fractional part.

This results in a[0/2=0], a[1/2=0], a[2/2=1], a[3/2=1], a[4/2=2], a[5/2=2] array element access in your code.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111