An input sequence of whole numbers in the range 0 - 100 (inclusive) represents the marks for a class of students. A negative number terminates the sequence.
A program is required to compute the mean mark for the class together with the number of students who failed with less than 40 marks, the number who passed with up to 70 marks and the number who obtained distinctions with 70 and over.
// generate a random list of marks for a random number of students
for ($n = 0; $n < mt_rand(10, 40); $n++)
$marks .= mt_rand(0, 100) . ' ';
// add the terminator
$marks .= -1;
// explode all the marks and terminator into an array
$marks_list = explode(' ', $marks);
// get rid of the terminator
// loop through all the marks
foreach($marks_list as $mark)
// check how the student did
// and increment the appropriate counter
if ($mark < 40)
elseif ($mark <= 70)
// show the counters
// intval is used to turn nothing into zero
echo count($marks_list) . ' students:<br/>' .
'Failed: ' . intval($failed) . '<br/>' .
'Passed: ' . intval($passed) . '<br/>' .
'Distinctions: ' . intval($distinctions);