0

it is a simple one but there is a problem with the nested array

/*2 Student poll program */
#include <stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>

#define RESPONSE_SIZE 40
#define FREQUENCY_SIZE 11

int main()
{
    int answer;
    int rating;

    /* place survey responses in array responses */
    int frequency[ FREQUENCY_SIZE ] = { 0 };

    int responses[ RESPONSE_SIZE ] = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10,
        1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6,
        5, 6, 7, 5, 6, 4, 8, 6, 8, 10 };

    /*for each answer, select value of an element of array responses
and use that value as subscript in array frequency to
determine element to increment */

        for ( answer = 0; answer < RESPONSE_SIZE; answer++ ) {
            ++frequency[ responses [ answer ] ]; // this part is complex for me, can you please explain it further?
        }
        printf( "%s%17s\n", "Rating", "Frequency" );

    /* output frequencies in tabular format */
        for ( rating = 1; rating < FREQUENCY_SIZE; rating++ ) {
            printf( "%6d%17d\n", rating, frequency[ rating ] );
        }
        _sleep(1000*100);

        return 0;
}  

++frequency[ responses [ answer ] ]; how does this work, I could not grasp the logic of it. it increment the every value in it or what?

mch
  • 9,424
  • 2
  • 28
  • 42
chatay
  • 151
  • 3
  • 12

3 Answers3

2
++frequency[ responses [ answer ] ];

is shorthand for

frequency[ responses [ answer ] ] = frequency[ responses [ answer ] ]  +  1;

You can find more details about increment operators here.

Community
  • 1
  • 1
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
2

It's a somewhat unclear way of writing this identical code:

int index = responses[answer];
++frequency[index];

where you should know that ++frequency[index] is the same as

frequency[index] = frequency[index]+1

The code only increases one value by 1. Prefix or postfix ++ doesn't matter here.

Lundin
  • 195,001
  • 40
  • 254
  • 396
1

++frequency[ responses [ answer ] ]; this actually increments it. Here index is answer of responses array, and adds to frequency. Thus it is like, instead of using ++a, you can use :

a = a+1;
Munahil
  • 2,381
  • 1
  • 14
  • 24