# Robson » Little Red Book » Mean mark #2

## Chapter 3 - Question 3

Design a program to compute the mean mark from input data giving the number of students in a class followed by a list of their marks.

### Solution 1

`<?`
`    // * DATA CREATION`
`    `
`    // a random number of students`
`    \$students = mt_rand(5, 15);`
`    `
`    // for each student, generate a random mark`
`    for (\$n = 0; \$n < \$students; \$n++)`
`        \$marks .= ' ' . mt_rand(0, 10);`
`        `
`    // join everything together`
`    // so this is like [total] [mark1] [mark2] ...    `
`    \$data = \$students . \$marks;`
`    `
`    // * PROCESSING`
`    `
`    // first, split everything up`
`    \$data = explode(' ', \$data);`
`    `
`    // the total number of students is the first item of data`
`    // the rest of the array is the marks`
`    // divide the total by the students to get the average`
`    \$prc_average = array_sum(array_slice(\$data, 1, count(\$data)-1)) / \$data[0];`
`    `
`    // * OUTPUT`
`    `
`    echo 'Data: ' . implode(' ', \$data) . '<br/>' .`
`         'Students: ' . \$data[0] . '<br/>' .`
`         'Average mark: ' . round(\$prc_average, 4);    `
`?>`

Which produces:

Data: 13 0 5 4 4 10 9 6 10 8 7 4 5 1
Students: 13
Average mark: 5.6154

### Solution 2

There's no need for anyone to enter the number of students. That can easily be worked out from the number of marks given. Here's a simpler version that outputs the same thing but uses a lot less code.

`<?`
`    // * DATA CREATION`
`    `
`    // generate a random mark for a random number of students`
`    for (\$n = 0; \$n < mt_rand(5, 15); \$n++)`
`        \$scores[] = mt_rand(0, 10);`
`        `
`    // * OUTPUT & PROCESSING`
`    `
`    echo 'Data: ' . count(\$scores) . ' ' . implode(' ', \$scores) . '<br/>' .`
`         'Students: ' . count(\$scores) . '<br/>' .`
`         'Average mark: ' . round(array_sum(\$scores) / count(\$scores), 4);    `
`?>`

Which produces:

Data: 6 0 4 0 3 3 6
Students: 6
Average mark: 2.6667

## Log

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