Hi, I would like to terminate a do until ....loop when future value is greater than 1000 without using a Exit or Continue statement. Any suggestions? Thanks

Do Until inti > intMonths

            decFutureValue = (decFutureValue +  decMonthlyInvestment)  * (1 + decMonthlyInterestRate)

If decFutureValue > 1000 Then

End if
             
            inti += 1
        Loop

Dani AI

Generated

A simple, robust approach is to fold the threshold test into the loop condition instead of using Exit Do. As noted, Exit Do will work, and hinted at adding an Or clause — the key choice left is whether the loop condition is evaluated before or after the body runs. Use the post-tested form when the stop test depends on the value computed inside the loop.

Example (post-tested Do...Loop Until):

Dim monthIndex As Integer = 0
Dim fv As Decimal = startingValue

Do
    fv = (fv + monthlyInvestment) * (1 + monthlyRate)
    monthIndex += 1
Loop Until monthIndex > maxMonths Or fv > 1000D

Notes and gotchas:

  • Use Do ... Loop Until (bottom-tested) when you want the new fv to be computed first, then checked. If you use Do Until ... Loop (top-tested), the condition is checked before each iteration and may not see a value that becomes >1000 during that iteration.
  • Watch off-by-one issues: decide whether the increment should happen before or after the check depending on whether the current iteration counts toward maxMonths.
  • For money calculations prefer Decimal to avoid floating-point rounding issues and consider >= if hitting exactly 1000 should also stop.
  • If you must avoid both Exit Do and changing the loop form, a boolean flag set inside the loop and included in the exit condition is another pattern (but the Do ... Loop Until with an Or is cleaner).

For language details and all loop forms see the Visual Basic reference: Do Loop statement.

Recommended Answers

All 4 Replies

>Any suggestions?

Exit Do

>Any suggestions?

Exit Do

I am actually trying to do it without using an Exit Do or a continue statement. Any ideas? - Thanks

Add an "Or" clause to your loop exit criteria. Example:

Sub Main()

        Dim i As Integer = 0
        Dim j As Integer = 0

        Do Until i > 100 Or j > 120
            i += 3
            j += 5
        Loop

        Console.WriteLine("i: {0}", i)
        Console.WriteLine("j: {0}", j)
        Console.Read()

    End Sub

Thank You very much! I really appreciate the support from this community!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.