# 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 3 2 9 9 2 8 7 10 -1
The average mark for the 9 students is 5.7778

## Log

• May 2, 2005 - Added solution 1.
© 2004-19 robson | cc unless stated