Sebastien Cangy - 9 months ago 37

Vb.net Question

I've written this code to sort an array of 5 numbers in ascending order but I've got an error:

A first chance exception of type 'System.IndexOutOfRangeException' occurred in ConsoleApplication1.exe

Here is the code:

`Module Module1`

Dim numbers(5) As Integer

Dim flag As Boolean

Dim i As Integer = 0

Sub InputNumbers()

For i = 0 To 4

Console.WriteLine("Input Numbers ")

numbers(i) = Console.ReadLine()

Next i

End Sub

Sub Sort()

Dim temp As Integer

Do

flag = False

For i = 0 To 4

If numbers(i) > numbers(i + 1) Then

temp = numbers(i + 1)

numbers(i + 1) = numbers(i)

numbers(i) = temp

End If

Next i

Loop Until flag = True

End Sub

Sub Output()

For i = 0 To 4

Console.WriteLine("The result is : " & numbers(i))

Next i

End Sub

Sub Main()

InputNumbers()

Sort()

Output()

Console.ReadKey()

End Sub

The error is found here:

`For i = 0 To 4`

If numbers(i) > numbers(i + 1) Then

temp = numbers(i + 1)

numbers(i + 1) = numbers(i)

numbers(i) = temp

End If

Next i

Can someone please help?

Answer

As Sage Pourpre pointed out, where you are using `i + 1`

to reference the next element in the array, you have to make sure that `i + 1`

is not greater than the last index of the array. There is more than one way to do that.

Also, with the code in your question, you will have an unending loop because you haven't set the value of `flag`

appropriately. I suggest naming that variable `isSorted`

because it is more meaningful:

```
Sub Sort()
' perform a bubble sort
Dim temp As Integer
Dim isSorted As Boolean
Do
isSorted = True
For i = 0 To numbers.Length - 2
If numbers(i) > numbers(i + 1) Then
temp = numbers(i + 1)
numbers(i + 1) = numbers(i)
numbers(i) = temp
isSorted = False
End If
Next i
Loop Until isSorted
End Sub
```