Its unfortunate, KM, that you didn't really read the question, or my posts for that matter. You might have noticed that I was not putting you down or saying that your answer sucked. I was merely pointing out that you gave an answer that ignored the question, followed by one that didn't. As for why I hadn't posted my own answer? Thats because I liked your second answer. But you want one from me that doesn't use a loop? Ok. I'll use recursion then: sub addArray{ shift(@_) + addArray(@_) if(@_) }
$total = addArray( 1, 3, 8, 15, 7, 5, 3 )
Update:
Two other things KM, I notice that you voted -- on my original comment. I'm not sure why. Nothing I said in that post was incorrect or rude. I also have noticed that my recursive answer is similar to the one that Btrott posted. I'm not sure why I should care, but I didn't want you to think I had copied it, as I had not read it when I first posted this. Cheers. | [reply] [d/l] |
Recursion is a looping construct as well. As everybody
keeps pointing out there isn't really a way to do this
without some kind of loop going on somewhere.
Nuance
| [reply] |
Sorry Nuance, Recursion is NOT a loop.
Recursion works by building up the stack,
delaying evaluation until the end.
A loop evaluates as it goes. There is a big difference
between the two. Think about it this way: The recursive
method that I posted says to add the first number to the
sum of the other numbers. That can't be done until the sum
of the other numbers is known, so it puts the number on the
stack and trys to sum the other numbers by the same method.
It does this, pushing the list onto a stack, until there is
only one number left, then it sums the stack. This is not a
loop. Its not even close.
| [reply] |