PHP: Sum and average

Read a list of numbers and report its sum and its average.

What to build

A program that prints the sum and the average of some numbers.

Requirements

  • Read n, then one line with n integers.
  • Print Sum: S and Average: A with the average rounded to two decimals.

Input

Line 1: n. Line 2: n integers separated by spaces.

Output

Two lines.

Constraints

1 ≤ n ≤ 100; each number is between -10000 and 10000.

Example

Input:

3
1 2 3

Output:

Sum: 6
Average: 2.00

Why it works

array_sum adds the list, and dividing by the count gives the average, which printf rounds to two decimals.

Examples

Example 1 · Input
3
1 2 3
Expected output
Sum: 6
Average: 2.00
Example 2 · Input
4
10 20 30 41
Expected output
Sum: 101
Average: 25.25

Hints

Hint 1

Read the second line with explode(" ", trim(fgets(STDIN))) and turn it into ints with array_map.

Hint 2

printf("%.2f") prints the average with two decimals.

Solution

Show one correct solution (try it yourself first)
<?php
$n = (int) trim(fgets(STDIN));
$nums = array_map('intval', explode(" ", trim(fgets(STDIN))));
$sum = array_sum($nums);
echo "Sum: $sum\n";
printf("Average: %.2f\n", $sum / $n);

▶ Open this solution in the compiler

Lesson: Input from STDIN →