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.
<? // * 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: 1 8 3 3 2 -1
The average mark for the 5 students is 3.4