Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

script

Status
Not open for further replies.

help911

Technical User
Aug 31, 2003
7
US
I am new to perl and need help. How do you write a script to add the sum and find out the average and print out the five largest number in the array.

here is my array and here my script can some tell me what am i doing wrong thanks:

#to get the total

@a = ( 10 .. 16 );

$total = 0;

for ( $i = 0; $i < @a; ++$i ) {
total += $a[ $i ];
}
print &quot;$total\n&quot;;
 
Well looks like your missing $ before the total

total += $a[ $i ];
 
I put the $ in front of the total and it still doesn't work is there any I can get the total some.
 
Shouldn't this:

for ( $i = 0; $i < @a; ++$i ) {

be this?

for ( $i = 0; $i < $#a; ++$i ) {
 
Or, alternatively, this:
Code:
foreach $i ( 0..$#a ) {
Once you have the total, the average is:
Code:
$average = $total / scalar(@a);
To find the 5 largest numbers in @a, you could sort @a in descending order and take the first 5 elements:
Code:
@sorted = sort {$b <=> $a} @a;
@top5 = @sorted[0..4];
You could probably combine the sort and the statement following it, but it wouldn't contribute much to the readability of the code. Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top