Can you tell me what this statement is doing?

  • Thread starter Thread starter pairofstrings
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 2K views
pairofstrings
Messages
411
Reaction score
7
#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);

/* COUNTING FREQUENCY OF GROUPS */

++group[ (int) (value+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);

}

}

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

GROUP RANGE FREQUENCY
 
Physics news on Phys.org
Can you expalin me what is ++group[ (int) (value+0.5)/10]

It is equivalent to
Code:
// 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.
 
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+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);

}

}
 
Last edited:
pairofstrings said:
// why are we using int in the middle of this statement?

The calculation "(value+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.