changing a for loop into a do while loop

tronracer

Newcomer
Joined
Mar 11, 2003
Messages
4
I changed this:

Visual Basic:
intTotal = 0
For intOuterCounter = 2 To 5 Step 2
  For intInnerCounter = 2 To 4 
    intTotal += intInnerCounter
  Next intInnerCounter
Next intOuterCounter

into this:

Visual Basic:
intTotal = 0
intInnerCounter = 2
intOuterCounter = 2
Do While (intOuterCounter >= 2 And intOuterCounter <= 5)
    intOuterCounter += 2
    Do While (intInnerCounter >= 2 And intInnerCounter <= 4)
        intInnerCounter += 1
        intTotal += intInnerCounter
    Loop
Loop


In the first loop I get 18, then in the second I get 12. The goal is to get the same result. I need to keep it a nested loop. What's wrong?[edit]Added VB tags[/edit]
 
Last edited by a moderator:
you do realize the Next statment increments the value by the step THEN checks to see if it is still valid.. if it is out of the defined bounds then the loop terminates thought the value stays the same

what makes you think these 2 will be the same? what number are you trying to return?
 
You need to change the loop to add the counters at the bottom since a For loop changes the value at the bottom (when it hits the Next statement).

Also, you'll want to reset your intInnerCounter on every pass through the outer loop since the For statement does that as well.

Here's a revised version that works, hopefully - I can't test it from here but I hope I did it right :)

Visual Basic:
intTotal = 0
intOuterCounter = 2
Do While (intOuterCounter >= 2 And intOuterCounter <= 5)
    intInnerCounter = 2
    Do While (intInnerCounter >= 2 And intInnerCounter <= 4)
        intTotal += intInnerCounter
        intInnerCounter += 1
    Loop
    intOuterCounter += 2
Loop

-Nerseus
 
it is for my vb class

the question was to change the for loop into a series of do while loops. The first code was given...the second I wrote. So the first part of the code should execute twice since the statement would be true for the vaulue of 2 and 4. The nested part should execute 3 times, once for 2, 3, and 4. 2+3+4 = 9 so the result I should get is 18. Thank you I just tried the code and it works....I'll have to analyze what I did wrong later and what you said.....Thank you very much
 
Back
Top