Converting an if ..end if to a For Next loop
Converting an if ..end if to a For Next loop
Converting an if ..end if to a For Next loop
Converting an if ..end if to a For Next loop
Converting an if ..end if to a For Next loop
Converting an if ..end if to a For Next loop Converting an if ..end if to a For Next loop Converting an if ..end if to a For Next loop Converting an if ..end if to a For Next loop Converting an if ..end if to a For Next loop Converting an if ..end if to a For Next loop Converting an if ..end if to a For Next loop Converting an if ..end if to a For Next loop
Converting an if ..end if to a For Next loop Converting an if ..end if to a For Next loop
Converting an if ..end if to a For Next loop
Go Back  Xtreme Visual Basic Talk > > > Converting an if ..end if to a For Next loop


Reply
 
Thread Tools Display Modes
  #1  
Old 06-12-2011, 06:58 AM
45minutes 45minutes is offline
Regular
 
Join Date: Jan 2011
Posts: 75
Default Converting an if ..end if to a For Next loop


Hi, my function is to adjust a timer interval according to a integer variable.

Original code (works fine):

Code:
Dim UpdateSnakeSpeed

      Select Case UpdateSnakeSpeed

            Case currentscore > 199
                P1movement.Interval = 90

            Case currentscore > 299
                P1movement.Interval = 85


            Case currentscore > 399
                P1movement.Interval = 80


            Case currentscore > 999
                P1movement.Interval = 70


            Case currentscore > 1299
                P1movement.Interval = 55


            Case currentscore > 2199
                P1movement.Interval = 45

            Case currentscore > 2799
                P1movement.Interval = 40

            Case currentscore > 3499
                P1movement.Interval = 35

            Case currentscore > 3999
                P1movement.Interval = 30


            Case currentscore > 4499
                P1movement.Interval = 25

            Case currentscore > 4899
                P1movement.Interval = 15

            Case currentscore > 5000
                P1movement.Interval = 10


        End Select
I had this code previously in if ..end if statement (worked fine too) With the case though I do not get the updateSnakeSpeed variable. I just used it so It would follow proper structure and syntax, surprisingly it works. If I replace "UpdateSnakeSpeed" with "currentscore" (my changing variable) it does not take effect. i.e. snake just travels the constant default slow speed.


Now I have tried to revamp this code into a for next loop:


Code:
  Dim ScoreValueToPass As Integer = 199
        Dim scoreValueToStayUnder As Integer = 299

        For SpeedIndex As Integer = 0 To 14
            If (currentscore > ScoreValueToPass And currentscore < scoreValueToStayUnder) Then
                P1movement.Interval = P1movement.Interval - 10
            End If

            ScoreValueToPass += 200
            scoreValueToStayUnder += 200

        Next SpeedIndex
once it hits the specified range, it just keeps subtracting the P1movement interval, until it can no longer do so and crashes. This is a logical problem and I do not know as of this moment how to work around it.

Any help is appreciated thanks.

EDIT:

Code:
 ' updates the snake speed according to how high the current score is. (higher the score, faster the snake goes).

        If (currentscore > 199 And currentscore < 398) Then
            P1movement.Interval = 90
        End If

        If (currentscore > 399 And currentscore < 998) Then
            P1movement.Interval = 80
        End If

        If (currentscore > 999 And currentscore < 1298) Then
            P1movement.Interval = 70
        End If

        If (currentscore > 1299 And currentscore < 2198) Then
            P1movement.Interval = 55
        End If

        If (currentscore > 2199 And currentscore < 2798) Then
            P1movement.Interval = 45
        End If

        If (currentscore > 2799 And currentscore < 3498) Then
            P1movement.Interval = 40
        End If

        If (currentscore > 3499 And currentscore < 3998) Then
            P1movement.Interval = 35
        End If

        If (currentscore > 3999 And currentscore < 4498) Then
            P1movement.Interval = 30
        End If

        If (currentscore > 4499 And currentscore < 4898) Then
            P1movement.Interval = 25
        End If

        If (currentscore > 4899 And currentscore < 4999) Then
            P1movement.Interval = 15
        End If
        If currentscore > 5000 Then
            P1movement.Interval = 10
        End If
This is the code I'm using right now. (works fine and is more logically correct than the above case statement. I have chosen to go with if .. end if statements over case, as I do not have a full understanding of what the variable SnakeUpdatespeed is doing in the Select case statement. If someone explains then I'll consider it. Also I know case statments are only meant to be used for 1 option selections, however I'm amazed that it still works in case. Atm it's going to be if end if. Now I'm trying to get the for next loop going with this (if it's logically possible). that's what i'm aiming overall out of this thread. To make a convenient loop.

Last edited by 45minutes; 06-12-2011 at 07:31 AM.
Reply With Quote
  #2  
Old 06-12-2011, 10:06 AM
AtmaWeapon's Avatar
AtmaWeaponConverting an if ..end if to a For Next loop AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

Loops work best when everything has a pattern. If it requires addition of an offset to a value, that's the best case. If the value can be derived from a function, that's good too. Sometimes you have to use a lookup table if there's no real pattern. Here's what each of the three cases looks like. If you have a grasp of basic algebra, it's a piece of cake. (If you don't, teach yourself! You won't get far in programming without it.)

Addition of an Offset
Code:
Dim appleCost As Double = 0.20
Dim currentCost As Double = 0
For i As Integer = 1 To 10
    currentCost += appleCost
    Console.WriteLine("{0} apples cost {1}." i, currentCost)
Next
If you want to reduce complexity, you can exploit that multiplication is repeated addition:
Code:
Dim appleCost As Double = 0.20
For i As Integer = 1 To 10
    Dim currentCost as Integer = appleCost * i
    Console.WriteLine(...)
Next
This technique is easy to spot in repetitive if statements; you'll find many values separated by the same amount each time:
Code:
If currentScore < 200 Then
    interval = 90
ElseIf currentScore < 400 Then
    interval = 80
ElseIf currentScore < 600 Then
    interval = 70
End If
The pattern 200, 400, 600 shows a linear increase by 200 each time. The function is f(x) = x * 200. The pattern 90, 80, 70 is a linear decrease by 10 each time; f(x) = 90 - 10(x - 1) is a good way to describe it since we assumed x starts with 1 in the last one. So the loop would look like this:
Code:
For index = 1 To ???
    If currentScore < 200 * index
        interval = 90 - (10 * (index - 1))
    End If
Next
Does your code look like it has a simple linear pattern like this? Spend a few minutes thinking about it before you move on.

Derivation from a Function
Right. Your code doesn't have an easy linear pattern. The scores go +100, +100, +600, +300, +900, +600, +700. The intervals go -5, -5, -10, -15, -10, -5, -5. Since the numbers change each time, we'll have to figure out if a function fits.

First, let's see what a loop that uses function derivation looks like. We start with the tedious code to print the first 10 squares:
Code:
Console.WriteLine(1) ' 1 * 1
Console.WriteLine(4) ' 2 * 2
Console.WriteLine(9) ' 3 * 3
...
We know our loop variable's going to go in sequence 1, 2, 3... Can you think of a function that seems like a good fit? What about f(x) = x * x?
Code:
Function Square(ByVal x As Integer) As Integer
    Return x * x
End Function
Code:
For i As Integer = 1 To 10
    Console.WriteLine(Square(i))
Next
Now look at your pattern. Can you think of a function that produces the patterns? It might help to plot them on paper. Give it a try for a few minutes before going on; you might not need the next one.

Lookup Tables
If you try really hard you can probably find a polynomial that fits those points. But polynomial math's slower than linear math, so you don't want to fool with it. When faced with numbers that have no pattern at all (or one that's expensive to calculate), the best you can do is use a lookup table. This consists of creating an array with the appropriate value for each index. The nice thing about lookup tables is they always work and are rarely slower than offsets or functions. The not nice thing is all the typing involved.

For example, suppose I had data about the cost of an apple each month. Odds are these prices aren't related by a simple function, so I'd have to use a lookup table to print each month's data:
Code:
Dim applePrices() As Double = { 0.20, 0.25, 0.80, 0.41, ... }

For i As Integer = 0 To applePrices.Length - 1
    Console.WriteLine("In month {0} apples cost {1}.", GetMonth(i), applePrices(i))
Next
This is what you're going to have to do if you don't want to use a more reasonable pattern. It'd look something like this:
Code:
Dim scoreThresholds() As Integer = { 199, 299, 399, ... }
Dim intervals() As Integer = { 90, 85, 80, ... }

For i As Integer = 0 To scoreThresholds.Length
    If currentScore < scoreThresholds(i) Then
        P1movement.Interval = intervals(i)
        Exit For
    End If
Next
The Exit For is important. Suppose it's not there and the score is 387. 387 > 199, so index 0 fails the If. 387 > 299, so it fails the if. 387 < 399, so the if is taken and the interval is set. But if we keep going, 387 is also less than 999, 1299, and all of the other scores! So we have to quit as soon as we find a match or do the more complicated test to see if it's between the current and last.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #3  
Old 06-12-2011, 08:38 PM
45minutes 45minutes is offline
Regular
 
Join Date: Jan 2011
Posts: 75
Default

Quote:
Code:
Dim scoreThresholds() As Integer = { 199, 299, 399, ... }
Dim intervals() As Integer = { 90, 85, 80, ... }

For i As Integer = 0 To scoreThresholds.Length
    If currentScore < scoreThresholds(i) Then
        P1movement.Interval = intervals(i)
        Exit For
    End If
Next
The Exit For is important. Suppose it's not there and the score is 387. 387 > 199, so index 0 fails the If. 387 > 299, so it fails the if. 387 < 399, so the if is taken and the interval is set. But if we keep going, 387 is also less than 999, 1299, and all of the other scores! So we have to quit as soon as we find a match or do the more complicated test to see if it's between the current and last.
does that last code, loop? Because I don't see it incrementing the index anywhere. It just says for - to scorethresholds.length. then runs once? and Exits for?
Reply With Quote
  #4  
Old 06-13-2011, 07:56 AM
AtmaWeapon's Avatar
AtmaWeaponConverting an if ..end if to a For Next loop AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

Do you know how a For loop works?

i is the index variable. The loop sets it to an initial value. The "To" part tells the loop how high I want it to go, we'll call it the target value. Here's how a For loop executes:
Code:
1) Set the index variable to its initial value.
2) If the index variable >= the target value:
    2.1) Quit looping
3) Else:
    3.1) Execute the body of the loop.
    3.2) Add 1 to the index variable.
    3.3) Goto 2.
It could be compared to this While loop:
Code:
Dim i As Integer = 0
While i < scoreThresholds.Length
    If currentScore < ...
        ...
    End If

    i += 1
End While
For loops are an easier way to manage that kind of loop.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
Converting an if ..end if to a For Next loop
Converting an if ..end if to a For Next loop
Converting an if ..end if to a For Next loop Converting an if ..end if to a For Next loop
Converting an if ..end if to a For Next loop
Converting an if ..end if to a For Next loop
Converting an if ..end if to a For Next loop Converting an if ..end if to a For Next loop Converting an if ..end if to a For Next loop Converting an if ..end if to a For Next loop Converting an if ..end if to a For Next loop Converting an if ..end if to a For Next loop Converting an if ..end if to a For Next loop
Converting an if ..end if to a For Next loop
Converting an if ..end if to a For Next loop
 
Converting an if ..end if to a For Next loop
Converting an if ..end if to a For Next loop
 
-->