PDA

View Full Version : Can you tell me what this statement is doing?


pairofstrings
Aug8-11, 07:31 AM
#define MAXVAL 50
#define COUNTER 11
main ()
{
float value[MAXVAL];
int i, low, high;
static group[COUNTER] = {0,0,0,0,0,0,0,0,0,0,0}

*/READING AND COUNTING*/

for(i=0; i<MAXVAL; i++)
{
/* READING OF VALUES*/

scanf("%f", &value[i]);

/* COUNTING FREQUENCY OF GROUPS */

++group[ (int) (value[i]+0.5)/10]
}

/* PRINTING OF FREQUENCY TABLE */

printf("\n");
printf(" GROUP RANGE FREQUENCY\N\N");

for(i=0; i< COUNTER; i++)
{
low = i*10;
if (i==10)
high =100;
else
high=low + 9;
printf( " %2d %3dto%3d %d)\n", i+1, low,high,group[i]);

}

}

Can you expalin me what is ++group[ (int) (value[i]+0.5)/10] and also what is %3d and %2d doing in the statements.


output:
input data

GROUP RANGE FREQUENCY

Timo
Aug8-11, 08:50 AM
Can you expalin me what is ++group[ (int) (value[i]+0.5)/10]

It is equivalent to

// calculate the number of the counter for this value.
index = (int) ( value[i]+0.5 ) / 10;
// increase the counter by one.
group[index] += 1;

(except that the integer variable index isn't defined in your piece of code, of course).


and also what is %3d and %2d doing in the statements.

That is the format in which the number should be displayed. Google for the printf command to find out more.

pairofstrings
Aug8-11, 10:58 AM
Can you help me trace the program? I am having little trouble in understanding this piece of code

/* COUNTING FREQUENCY OF GROUPS */

++group[ (int) (value[i]+0.5)/10

// why are we using int in the middle of this statement?

}

/* PRINTING OF FREQUENCY TABLE */

printf("\n");
printf(" GROUP RANGE FREQUENCY\N\N");

for(i=0; i< COUNTER; i++)
{
low = i*10;
if (i==10)
high =100;
else
high=low + 9;
printf( " %2d %3dto%3d %d)\n", i+1, low,high,group[i]);

}

}

jtbell
Aug8-11, 11:09 AM
// why are we using int in the middle of this statement?

The calculation "(value[i]+0.5)/10" is done using floats or doubles, which generally produces a result with a fractional part. The "(int)" casts (converts) the result to int, which discards the fraction.