Classic ASP BasicsFor beginner programmers starting with "classic" ASP 3, pre-".NET." NOT for ASP.NET 1.0, 1.1, or 2.0
Welcome to the p2p.wrox.com Forums.
You are currently viewing the Classic ASP Basics section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
I have a beginning value and an end value inputted by a user. I need to sum all of the numbers between the first and last value. What is a good do way to do this? Is a Do While loop or a For Each loop. I inderstand that I need to take the beginning variable and increment it by one until it equals that end value and then add them all together but I'm not sure how to put it together with the code.
You don't need a loop for this because there's a known mathematical formula for summing numbers from 1 to n, which is T(n) = n(n+1)/2, e.g. sum of all integers from 1 to 10 is T(10) = 10(10+1)/2 = 55.
So if you want to sum all numbers from say, 3 to 10, just do T(10) - T(2) = 55 - 3 = 52.
Also, if you don't want to include the 3 and 10 in the sum then just take them off the answer.
If you really insist on a loop-type thing, then recursion is much neater:
Code:
Function CalcSum(nStart, nEnd)
If nEnd = nStart Then
CalcSum = nStart
Else
CalcSum = nEnd + CalcSum(nStart, nEnd - 1)
End If
End Function
I think it is best to follow the mathematical formula example that PGTIPS pointed out. If you put no bounds on this calculation, suppose the user "wanted" to sum 1 to 1,000,000,000? Whether you use recursion or a loop, this is going to take a lot of processing time, not good for a web server.
If someone wanted to crash your site and you used recursion w/o boundary conditions, they could open multiple sessions and request huge sums as above. Each recursion is going to use more memory as variables and status registers get pushed onto the stack. Eventually your system could run out of memory and be unable to continue the recursion, yet unable to release memory by "unwinding" the recursive calls. Thus, locking up the server.
Of course, if you do not need to access any server info, you could just make this script local to the client. They might still be able to crash their own computer though (or at least their browser) just from simple ignorance.
For this reason, I would not use recursion w/o some boundary checking, even though it is the more elegant solution to some problems. Of course, it might take billions of recursions to actually use up all or a significant portion of the servers memory :)