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

Page 1 of 1

## 3 Replies - 866 Views - Last Post: 24 April 2013 - 12:43 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=319443&amp;s=42d5e7efb710a16ebdc5dacab2e3d70a&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 sagarpathare

Reputation: -2
• 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

• blow up my boots

Reputation: 6549
• Posts: 26,553
• 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

### #3 sagarpathare

Reputation: -2
• 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.

### #4 lar3ry

• Coding Geezer

Reputation: 314
• Posts: 1,296
• Joined: 12-September 12

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

Posted 24 April 2013 - 12:43 PM

sagarpathare, 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

```