Jump to content
Xtreme .Net Talk

Recommended Posts

Posted (edited)

I changed this:

 

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

 

into this:

 

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]

Edited by John
Posted

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?

i'm not lazy i'm just resting before i get tired.
  • *Experts*
Posted

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 :)

 

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

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
Posted

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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...