Robson » Little Red Book » Mean mark #3

Chapter 3 - Question 4

Design a program to compute the mean mark from input data giving the number of marks for a class of students ending with a negative value.

Solution 1

<?
   // * DATA CREATION
 
   // generate a random mark for a random number of students
   for ($n = 0; $n < mt_rand(5, 15); $n++)
       $data .= mt_rand(0, 10) . ' ';
       
   // add the terminator negative value
   $data .= -1;
   
   // now we have data that looks like
   // [mark] [mark] ... [mark] [terminator]
   // example: 1 7 8 3 4 -1
   
   // * PROCESSING
   
   // split everything up
   $scores = explode(' ', $data);
   
   // remove the terminator value
   array_pop($scores);
   
   // * OUTPUT
   
   echo 'Data: ' . $data . '<br/>' .
        'The average mark for the ' . count($scores) . ' students is ' .
        round(array_sum($scores) / count($scores), 4);
?>

Which produces:

Data: 2 8 9 6 7 3 1 5 7 9 -1
The average mark for the 10 students is 5.7

Log

© 2004-17 robson | cc unless stated