Thread: VBA Excel
View Single Post
Old 10-16-2010, 02:24 PM   #18
Bob
Franchise Player
 
Join Date: Jan 2007
Exp:
Default

The description says to sum all *even* numbers from 121 to your number (a negative, even integer), so you've got it backwards.

Quote:
The subroutine needs to sum all the even integers between one hundred and twenty-one (121) and the inputted number and display the result in a message box.
Code:
For i = 120 To mynum Step -2
I don't see the point of starting at 121 if we're using even numbers all the way. It's also fine to start at mynum and go up to 121, but assignments like this are known for their pedantry. It's probably safer (from an academic perspective) to check the starting number and adjust it down if it's odd so it doesn't break your loop. Something like:

Code:
Start = 121
If Start Mod 2 <> 0 Then
Start = Start - 1
End If

For i = Start To mynum Step -2
...
The argument being "your code doesn't work if I give you a different starting number, or ask the user for a starting number", etc. I always encountered silly technicalities like that.

There's no need to add 1 to mynum to start the loop if you've already verified that a) it's negative, and b) it's even. You've already got negative numbers, so you should be able to modify your data entry check to account for non even numbers. I don't know if this is syntactically correct, but you need the modulus operator.

Code:
If mynum >= 0 Or mynum Mod 2 <> 0 Then
Essentially, reject the input if it's a) non-negative or b) the remainder when dividing by two is non-zero (i.e. it's an odd number).

Last edited by Bob; 10-16-2010 at 02:29 PM.
Bob is offline   Reply With Quote
The Following User Says Thank You to Bob For This Useful Post: