Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: How can I add all the numbers in an array with out doing a foreach loop?

by rajib (Novice)
on Aug 20, 2002 at 17:41 UTC ( [id://191530]=note: print w/replies, xml ) Need Help??


in reply to How can I add all the numbers in an array with out doing a foreach loop?

Another recursive method:

@array = (1,2,3); print "SUM: ", sum($#array); sub sum { if ($_[0] == 0) { return $array[0]; } return $array[$_[0]] + sum($_[0]-1); } #note it's not efficient

This method's shortcoming is that the sub acts only on the global array "@array", and thus can't be easily applied to more than one array. A more elegant and useable recursive method was demonstrated earlier in this thread.

Originally posted as a Categorized Answer.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://191530]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (7)
As of 2024-06-18 11:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.