Robson » Little Red Book » Exam marks

Chapter 5 - Question 1

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.

Solution 1

<?    // 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    array_pop($marks_list);        // loop through all the marks    foreach($marks_list as $mark)    {        // check how the student did        // and increment the appropriate counter        if ($mark < 40)            $failed++;        elseif ($mark <= 70)            $passed++;        else            $distinctions++;        }        // 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); ?>

Which produces:

17 students:
Failed: 6
Passed: 6
Distinctions: 5

Log

© 2004-20 robson | cc unless stated