hw2 solution

This post shows the solution for the homework coded hw2.

The solution for hw2 is reported in codepad.

@numeri = (3,66,2,34,12,57);
$lunghezza = 0;
 
# Inizializzo due variabili con il primo numero dell'array
# serviranno a tenere minimo e massimo
$min = $numeri[0];
$max = $numeri[0];
 
foreach $i (@numeri) {
    $lunghezza++;
    $somma = $somma + $i;
    if ($min > $i) {
       $min = $i;
    }
    if ($max < $i) {
        $max = $i;
    }
 
    print "Il numero corrente e': $i (per ora min: $min e max: $max)\n";
 
}
 
$lunghezza_alternativa = $#numeri + 1;
if ($lunghezza > 0) {
    $media = $somma / $lunghezza;
}
 
print "\nLunghezza dell'array: $lunghezza (o $lunghezza_alternativa)
Il numero minimo:     $min
Il numero massimo:    $max
La media:             $media";

As you see this solution is comprehensive and contains a lot of things. A couple of them requires some attention:

  • We initialize the variable min and max. Initializing means creating them assigning a value before using them. We use them inside the loop, we initialize them before. This is not strictly necessary, but consider an array with all negative numbers… What would happen to the minimum if not properly initialized?
  • We simply calculate the average as a division. As you can see we put the division inside an if statement. Why?
Tagged ,

Leave a Reply

Your email address will not be published.