3 Replies - 497 Views - Last Post: 24 April 2013 - 12:43 PM Rate Topic: -----

#1 sagarpathare  Icon User is offline

  • New D.I.C Head

Reputation: -2
  • View blog
  • Posts: 11
  • Joined: 24-April 13

Unable to convert a For-Next loop into Do-Loop.

Posted 24 April 2013 - 11:10 AM

Hello
I am trying to convert a for next loop into a do loop because I want to add a condition.
This code works perfectly:
        Dim LastNonEmpty As Integer = -1
        For i As Integer = 0 To mnar.Length - 1
            If mnar(i) <> "" Then
                LastNonEmpty += 1
                mnar(LastNonEmpty) = mnar(i)
            End If
        Next


But when I converted it:
i = 0
Do while i = wnar.Length - 1
   If wnar(i) <> "" Then
      LastNonEmpty2 += 1
      wnar(LastNonEmpty2) = wnar(i)
   End If
Loop


This doesn't work at all.
Please suggest me the correct code.
Or tell me how to add condition in a for next loop.

Is This A Good Question/Topic? 0
  • +

Replies To: Unable to convert a For-Next loop into Do-Loop.

#2 andrewsw  Icon User is offline

  • It's just been revoked!
  • member icon

Reputation: 3838
  • View blog
  • Posts: 13,595
  • Joined: 12-December 12

Re: Unable to convert a For-Next loop into Do-Loop.

Posted 24 April 2013 - 11:18 AM

i = 0
Do while i = wnar.Length - 1
   If wnar(i) <> "" Then
      LastNonEmpty2 += 1
      wnar(LastNonEmpty2) = wnar(i)
   End If
Loop

Assuming wnar has a length > 0 then the loop will never be entered. So use:

Do while i <= wnar.Length - 1

However, within the loop you don't increment i, so you need i = i + 1 just before the end of the loop, otherwise it will never end!

Mind you, you should have studied before attempting to create the loop: dotnetperls
Was This Post Helpful? 1
  • +
  • -

#3 sagarpathare  Icon User is offline

  • New D.I.C Head

Reputation: -2
  • View blog
  • Posts: 11
  • Joined: 24-April 13

Re: Unable to convert a For-Next loop into Do-Loop.

Posted 24 April 2013 - 11:22 AM

Yes it worked.
Was This Post Helpful? 0
  • +
  • -

#4 lar3ry  Icon User is offline

  • Coding Geezer
  • member icon

Reputation: 310
  • View blog
  • Posts: 1,290
  • Joined: 12-September 12

Re: Unable to convert a For-Next loop into Do-Loop.

Posted 24 April 2013 - 12:43 PM

View Postsagarpathare, on 24 April 2013 - 12:22 PM, said:

Yes it worked.

As andrewsw, mentioned in giving you a link, it pays to learn the basics. There are quite a number of ways to do what you were trying to do. You also mentioned wanting to place a condition within the For Loop, and yes, sometimes a For Loop is easiest to visualize. Here's one way..

Dim LastNonEmpty As Integer
For i As Integer = 0 To mnar.Length - 1
    If mnar(i) <> "" Then
        LastNonEmpty += 1
        mnar(LastNonEmpty) = mnar(i)
    Else
        Exit For
    End If
Next


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1