In: Computer Science
Write a program in PERL language that does the following:
a. Generates 100 random numbers between -17 and +31.
b. Calculates the average of the square of the generated numbers using a function that you implement.
c. Calculates the number of numbers greater than the average using a function that you implement.
d. Prints the results single line separated by spaces using a print function that makes call to the previously defined functions in parts b) and c).
In case of any query do comment. Please rate answer as well. Thanks
Code:
#declare a range
my @range = (-17 .. 31 );
my @arr; #declare an array
#fill an array with random values within the given range
for (my $i=0; $i<100; $i++)
{
$arr[$i]=$range[rand(@range)];
}
#call averageOfSquare and numbersGreaterThanAverage method
print averageOfSquare(@arr)," ", numbersGreaterThanAverage(@arr);
#function finds the sum of square and then divide by 100 to get an averageOfSquares
sub averageOfSquare
{
my $sumOfSquare =0.0;
for (my $i=0; $i<100; $i++)
{
$sumOfSquare += $arr[$i] * $arr[$i]
}
return $sumOfSquare/100;
}
#try to see if number generated is greater than averageOfSquare, then increase the count
sub numbersGreaterThanAverage
{
my $average = averageOfSquare(@arr);
my $count =0;
for (my $i=0; $i<100; $i++)
{
if($arr[$i] > $average)
{
$count = $count + 1;
}
}
return $count;
}
Screen shot of the code and Output: