0

Can anyone explain the output of this code? I have been hitting my head really hard to understand, but I just don't get it.

public static void main(String ars[]) {
    int responses[] = {1,2,4,4};
    int freq[] = new int[5];

    for(int answer = 1; answer < responses.length; answer++) {
        ++freq[responses[answer]];
    }

    for (int rating = 1; rating < freq.length; rating++)
         System.out.printf("%6d%10d\n", rating, freq[rating]);
}

Output

 1         0
 2         1
 3         0
 4         2
John Bollinger
  • 160,171
  • 8
  • 81
  • 157
bgreatfit
  • 55
  • 1
  • 10
  • you may want to print out all values of freq inside your first loop to see what happens – Thorbjørn Ravn Andersen Aug 19 '15 at 19:17
  • Your question title perhaps betrays the nature of your confusion: the pre-increment operator does not apply to arrays, and the code you present does not exhibit pre-incrementing an array. Instead, the pre-increment operator applies to an array *element*, namely `freq[responses[answer]]`. – John Bollinger Aug 19 '15 at 19:22
  • Note also that Java arrays are indexed from 0, but your `for` loops ignore element 0 of each array. – John Bollinger Aug 19 '15 at 19:25

2 Answers2

1

In first loop ++freq[responses[answer]]; means :

  • responses[answer] get the value from response array index.
  • Freq[value] check & get the value from Filter array index.
  • ++Freq[value] add value 1 to Freq[value].
Suraj Gupta
  • 879
  • 7
  • 6
0

I've tried to simply things a bit so you can see what is going on:

    int responses[] = new int[4];
    responses[0] = 1;
    responses[1] = 2;
    responses[2] = 4;
    responses[3] = 4;

    int freq[] = new int[5];

    for(int answer = 1; answer < 4; answer++)
    {
        int x = responses[answer];
        freq[x] = freq[x] + 1;
    }

    for (int rating = 1; rating < 5; rating++)
    {  
         //Print 6 spaces and then the rating variable
         //Print 10 spaces then the integer at freq[rating]

         System.out.printf("%6d%10d\n", rating, freq[rating]);
    } 

I would look up the ++ prefix & postfix.

Community
  • 1
  • 1
Kevvvvyp
  • 1,704
  • 2
  • 18
  • 38
  • Is the value y= 1 correct for freq[1] - first loop – bgreatfit Aug 19 '15 at 19:49
  • Does that make more sense? I thought it might be easier to simply the code than write a big paragraph. – Kevvvvyp Aug 19 '15 at 19:54
  • Is the value y= 1 correct for freq[1] - first loop – bgreatfit Aug 19 '15 at 19:57
  • Yeah in the first pass of that loop answer is equal to 1. 'x' is then set equal to responses[1] which is 2. 'Y' is set equal to freq[2] which is 0. So freq[x] = 0 + 1. So when you get to the second for loop, freq[1] would be 0 but freq[2] is 1 ! – Kevvvvyp Aug 19 '15 at 20:07
  • I am crying, I don't know why I am not getting the same results as the output. The first loop is used to assign values to freq array the second loop to print out the values? – bgreatfit Aug 19 '15 at 20:29