System.IndexOutOfRangeException in vb.net when using arrays - vb.net

Well, I have tried to complete a challenge that requires me to get all of the multiples of 5 or 3 from 0 to 1000 and then get the sum of them, I am new to vb.net so I thought that this would be a nice challenge for me to solve> I'm pretty sure I have the basics right, but I'm not quite sure why I'm getting this error :/.
Module Module1
Sub Main()
Dim Counter As Integer = 1
Dim Numbers() As Integer
Dim NumbersCounter As Integer = 0
Dim Total As Integer = 0
While (Counter <= 1000)
If (Counter Mod 3 = 0) Then
Numbers(NumbersCounter) = Counter '<--- The error is located on Numbers.
NumbersCounter = NumbersCounter + 1
Counter = Counter + 1
ElseIf (Counter Mod 5 = 0) Then
Numbers(NumbersCounter) = Counter
NumbersCounter = NumbersCounter + 1
Counter = Counter + 1
Else
Counter = Counter + 1
End If
End While
Counter = 0
While (Counter <= Numbers.Length)
If (Counter = 0) Then
Total = Numbers(Counter)
Counter = Counter + 1
Else
Total = Total * Numbers(Counter)
Counter = Counter + 1
End If
End While
PrintLine(Total)
End Sub
End Module
Any help or tips would be greatly appreciated! Thanks in advance.

You need to allocate memory to Numbers array and since the size is known initially you may allocate while declaring:
Dim Numbers(1000) As Integer

In looking over your code egghead is right in stating that you did not initialize your array. But after doing so I had to change a few other things in your code to get it to run.
Module Module1
Sub Main()
Dim Counter As Integer = 1
Dim Numbers(1000) As Integer 'Initialized the Array so it will be usable.
Dim NumbersCounter As Integer = 0
Dim Total As Integer = 0
While (Counter <= 1000)
If (Counter Mod 3 = 0) Then
Numbers(NumbersCounter) = Counter
NumbersCounter = NumbersCounter + 1
Counter = Counter + 1
ElseIf (Counter Mod 5 = 0) Then
Numbers(NumbersCounter) = Counter
NumbersCounter = NumbersCounter + 1
Counter = Counter + 1
Else
Counter = Counter + 1
End If
End While
Counter = 0
While (Counter <= Numbers.Length - 1) ' Arrays are zero based so you need to subtract 1 from the length or else you will overflow the bounds
If (Counter = 0) Then
Total = Numbers(Counter)
Counter = Counter + 1
Else
Total = Total + Numbers(Counter) 'You were multiplying here not adding creating a HUGE number
Counter = Counter + 1
End If
End While
Console.WriteLine(Total) 'Changed PrintLine which prints to a file to Console.WriteLine which writes to the screen
Console.ReadLine 'Added a Console.ReadLine so the Window doesn't close until you hit a key so you can see your answer
End Sub
End Module

Related

Creating a Quick Sort in VB [duplicate]

Well, I have tried to complete a challenge that requires me to get all of the multiples of 5 or 3 from 0 to 1000 and then get the sum of them, I am new to vb.net so I thought that this would be a nice challenge for me to solve> I'm pretty sure I have the basics right, but I'm not quite sure why I'm getting this error :/.
Module Module1
Sub Main()
Dim Counter As Integer = 1
Dim Numbers() As Integer
Dim NumbersCounter As Integer = 0
Dim Total As Integer = 0
While (Counter <= 1000)
If (Counter Mod 3 = 0) Then
Numbers(NumbersCounter) = Counter '<--- The error is located on Numbers.
NumbersCounter = NumbersCounter + 1
Counter = Counter + 1
ElseIf (Counter Mod 5 = 0) Then
Numbers(NumbersCounter) = Counter
NumbersCounter = NumbersCounter + 1
Counter = Counter + 1
Else
Counter = Counter + 1
End If
End While
Counter = 0
While (Counter <= Numbers.Length)
If (Counter = 0) Then
Total = Numbers(Counter)
Counter = Counter + 1
Else
Total = Total * Numbers(Counter)
Counter = Counter + 1
End If
End While
PrintLine(Total)
End Sub
End Module
Any help or tips would be greatly appreciated! Thanks in advance.
You need to allocate memory to Numbers array and since the size is known initially you may allocate while declaring:
Dim Numbers(1000) As Integer
In looking over your code egghead is right in stating that you did not initialize your array. But after doing so I had to change a few other things in your code to get it to run.
Module Module1
Sub Main()
Dim Counter As Integer = 1
Dim Numbers(1000) As Integer 'Initialized the Array so it will be usable.
Dim NumbersCounter As Integer = 0
Dim Total As Integer = 0
While (Counter <= 1000)
If (Counter Mod 3 = 0) Then
Numbers(NumbersCounter) = Counter
NumbersCounter = NumbersCounter + 1
Counter = Counter + 1
ElseIf (Counter Mod 5 = 0) Then
Numbers(NumbersCounter) = Counter
NumbersCounter = NumbersCounter + 1
Counter = Counter + 1
Else
Counter = Counter + 1
End If
End While
Counter = 0
While (Counter <= Numbers.Length - 1) ' Arrays are zero based so you need to subtract 1 from the length or else you will overflow the bounds
If (Counter = 0) Then
Total = Numbers(Counter)
Counter = Counter + 1
Else
Total = Total + Numbers(Counter) 'You were multiplying here not adding creating a HUGE number
Counter = Counter + 1
End If
End While
Console.WriteLine(Total) 'Changed PrintLine which prints to a file to Console.WriteLine which writes to the screen
Console.ReadLine 'Added a Console.ReadLine so the Window doesn't close until you hit a key so you can see your answer
End Sub
End Module

I want to pop up a MsgBox when counter is 3, 6, 9, 12.......99

I want to pop up a MsgBox when counter is 3, 6, 9, 12.......99.
Following code need to be reparied.
Dim Counter As Integer
Do While Counter Is threefold
MsgBox("Hello")
Counter = Counter + 1
Loop
You have to use the Mod Operator.
I don't know what is threefold, but you can test this loop :
For i As Integer = 0 To 99
If i > 0 Then
If i Mod 3 = 0 Then
MsgBox(i)
End If
End if
Next
EDIT : As Rubens mentioned, this is possible too :
For i As Integer = 3 To 99 Step 3
If i Mod 3 = 0 Then
MsgBox(i)
End If
Next
assuming 99 is your limit, using mod like below will help.
Mod gives you the ability to find divisors of a number, as the remainder is always 0. (in your case, you're after 'Mod 3')
Dim counter As Integer = 1
While counter < 100
If (counter mod 3) = 0 Then
MsgBox("Hello")
End If
Counter += 1
End While
Fiddle here: https://dotnetfiddle.net/gvFjGV
An alternative way to do it is with a For loop - this will save the need of declaring counter & remembering to increment within the loop

array without any duplicate value

the code to generate no. of arrays from one is working..I'm try to make some change to it like below
Function myarray(ByVal arra1() As Integer, ByVal arran() As Integer, ByVal arrNumber As Integer) As Integer()
arran = arra1.Clone()
For i As Integer = 0 To arra1.Length - 1
If i = (arrNumber - 1) Then ' IF arrNumber is 1 then +1 to index 0, If it is 2 then +1 to index 1
arran(i) = arra1(i) + 1
'If there are two duplicate value make on of them zero at a time
For k = 0 To arran.Length - 1
For j = k + 1 To arran.Length - 1
If arran(k) = arran(j) Then
arran(k) = 0
End If
'make any value great than 11 zero
If arran(i) > 11 Then
arran(i) = 0
End If
Next
Next
Else
arran(i) = arra1(i)
End If
Next
'Print the array
For i = 0 To arran.Length - 1
Console.Write(arran(i) & " ")
Next
Console.WriteLine()
Return arran
End Function
what I really need is to decompose for example {1,4,5,5} to be {1,4,0,5} and then {1,4,5,0} the above code generate only {1,4,0,5}
I haven't tested this, but I believe the following code will do what you want. Based on your comments, I've changed the function to return all resulting arrays as an array of arrays, rather than requiring the index to change as an input and returning one array. I also ignored matches of 0, as the conditions you describe don't seem designed to handle them. Because of it's recursion, I think this approach will successfully handle input such as {3, 3, 3, 3}.
Public Function jaggedArray(ByVal inputArray() As Integer) As Integer()()
If inputArray Is Nothing Then
Return Nothing
Else
Dim resultArrays()(), i, j As Integer
Dim arrayMax As Integer = inputArray.GetUpperBound(0)
If arrayMax = 0 Then 'prevents errors later if only one number passed
ReDim resultArrays(0)
If inputArray(0) > 11 Then
resultArrays(0) = {1}
ElseIf inputArray(0) = 11 Then
resultArrays(0) = {0}
Else
resultArrays(0) = {inputArray(0) + 1}
End If
Return resultArrays
End If
For i = 0 To arrayMax
Dim tempArray() As Integer = inputArray.Clone
For j = 0 To arrayMax
If tempArray(j) > 11 Then
tempArray(j) = 0
End If
Next
If tempArray(i) = 11 Then
tempArray(i) = 0
Else
tempArray(i) += 1
End If
splitArray(resultArrays, tempArray)
Next
Return resultArrays
End If
End Function
Private Sub splitArray(ByRef arrayList()() As Integer, ByVal sourceArray() As Integer)
Dim x, y As Integer 'positions of matching numbers
If isValid(sourceArray, x, y) Then
If arrayList Is Nothing Then
ReDim arrayList(0)
Else
ReDim Preserve arrayList(arrayList.Length)
End If
arrayList(arrayList.GetUpperBound(0)) = sourceArray
Else
Dim xArray(), yArray() As Integer
xArray = sourceArray.Clone
xArray(x) = 0
splitArray(arrayList, xArray)
yArray = sourceArray.Clone
yArray(y) = 0
splitArray(arrayList, yArray)
End If
End Sub
Private Function isValid(ByRef testArray() As Integer, ByRef match1 As Integer, ByRef match2 As Integer) As Boolean
For i As Integer = 0 To testArray.GetUpperBound(0) - 1
If testArray(i) > 11 Then
testArray(i) = 0
End If
For j As Integer = i + 1 To testArray.GetUpperBound(0)
If testArray(j) > 11 Then
testArray(j) = 0
End If
If testArray(i) = testArray(j) AndAlso testArray(i) > 0 Then 'added second test to prevent infinite recursion
match1 = i
match2 = j
Return False
End If
Next
Next
match1 = -1
match2 = -1
Return True
End Function

taking average of 10 sample in vb2010

I have used below code to find average of 10 sample . But during first time it take sample and do the averaging . during next cycle counter not become Zero.and text box not updating
Static counter As Integer = 0
DIm average_sum As Double = 0
If counter < 10 Then
counter = counter + 1
Count_val.Text = counter
Dim array(10) As Double
For value As Integer = 0 To counter
array(counter) = k
average_sum = average_sum + array(counter)
Next
If counter = 10 Then
average_sum = average_sum / array.Count
System.Threading.Thread.Sleep(250)
Array_count.Text = average_sum
End If
If counter > 10 Then
average_sum = 0
counter = 0
End If
End If
If Avg_count < 10 Then
Dim array(10) As Double
For value As Double = 0 To Avg_count
array(Avg_count) = k
average_sum = average_sum + array(Avg_count)
Avg_count = Avg_count + 1
Next
If Avg_count = 10 Then
average_sum = average_sum / Avg_count
System.Threading.Thread.Sleep(250)
Average.Text = average_sum
Avg_count = 0
End If
End If
Here count value setting properly . But after 2 to3 cycle Average will done earlier itself same thing i writen in excel to compare averages but not matching with average and excel sheet data
Below is excel sheet code.Both code are in timer1 block.
If counter < 10 Then
'counter = 0
'average_sum = 0
Dim headerText = ""
Dim csvFile As String = IO.Path.Combine(My.Application.Info.DirectoryPath, "Current.csv")
If Not IO.File.Exists((csvFile)) Then
headerText = "Date,TIME ,Current, "
End If
Using outFile = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True)
If headerText.Length > 0 Then
outFile.WriteLine(headerText)
End If
Dim date1 As String = "25-10-2014"
Dim time1 As String = TimeOfDay()
Dim x As String = date1 + "," + time1 + "," + distance
outFile.Write(x)
End Using
End If
If counter > 10 Then
counter = 0
End If

Max Value in VB?

Here is the code I'm working on for a project.
What I can't figure out is the max value and how to get it?
Even if I change it, it seems not to affect the outcome of the counter?
Can anyone lead me in the right direction on what to do for this?
Thanks!
Module
Module1
Dim counter As Integer
Const Max_Value As Double = 22
Sub Main()
Console.WriteLine("Are you ready to see which letter is 22? Press Enter")
Console.ReadLine()
For counter As Integer = 0 To Max_Value Step 1
 
Console.Write("a")
Console.WriteLine("0")
counter = counter + 1
Console.Write("b")
Console.WriteLine("1")
counter = counter + 1
Console.Write("c")
Console.WriteLine("2")
counter = counter + 1
Console.Write("d")
Console.WriteLine("3")
counter = counter + 1
Console.Write("e")
Console.WriteLine("4")
counter = counter + 1
Console.Write("f")
Console.WriteLine("5")
counter = counter + 1
Console.Write("g")
Console.WriteLine("6")
counter = counter + 1
Console.Write("h")
Console.WriteLine("7")
counter = counter + 1
Console.Write("i")
Console.WriteLine("8")
counter = counter + 1
Console.Write("j")
Console.WriteLine("9")
counter = counter + 1
Console.Write("k")
Console.WriteLine("10")
counter = counter + 1
Console.Write("l")
Console.WriteLine("11")
counter = counter + 1
Console.Write("m")
Console.WriteLine("12")
counter = counter + 1
Console.Write("n")
Console.WriteLine("13")
counter = counter + 1
Console.Write("o")
Console.WriteLine("14")
counter = counter + 1
Console.Write("p")
Console.WriteLine("15")
counter = counter + 1
Console.Write("q")
Console.WriteLine("16")
counter = counter + 1
Console.Write("r")
Console.WriteLine("17")
counter = counter + 1
Console.Write("s")
Console.WriteLine("18")
counter = counter + 1
Console.Write("t")
Console.WriteLine("19")
counter = counter + 1
Console.Write("u")
Console.WriteLine("20")
counter = counter + 1
Console.Write("v")
Console.WriteLine("21")
counter = counter + 1
Console.Write("w")
Console.WriteLine("22")
Console.ReadLine()
Next
Console.WriteLine()
Console.WriteLine("Summary of the Count: {0} So we've counted to 22{0} The Winning letter is W{0} Which is great because that's the letter of my first name{0} W also stands for War Eagle!", _
Environment.NewLine)
  
Console.WriteLine("Press Enter to Exit")
Console.ReadLine()
End Sub
End
Module
I think what you are trying to accomplish is something like this:
Module Module1
Dim counter As Integer
Const Max_Value As Integer = 22
Sub Main()
Console.WriteLine("Are you ready to see which letter is 22? Press Enter")
Console.ReadLine()
For counter As Integer = 0 To Max_Value Step 1
Select Case counter
Case 0
Console.Write("a")
Case 1
Console.Write("b")
Case 2
Console.Write("c")
Case 3
Console.Write("d")
Case 4
Console.Write("e")
Case 5
Console.Write("f")
Case 6
Console.Write("g")
Case 7
Console.Write("h")
Case 8
Console.Write("i")
Case 9
Console.Write("j")
Case 10
Console.Write("k")
Case 11
Console.Write("l")
Case 12
Console.Write("m")
Case 13
Console.Write("n")
Case 14
Console.Write("o")
Case 15
Console.Write("p")
Case 16
Console.Write("q")
Case 17
Console.Write("r")
Case 18
Console.Write("s")
Case 19
Console.Write("t")
Case 20
Console.Write("u")
Case 21
Console.Write("v")
Case 22
Console.Write("w")
End Select
Console.WriteLine(counter)
Console.ReadLine()
Next
Console.WriteLine()
Console.WriteLine("Summary of the Count: {0} So we've counted to 22{0} The Winning letter is W{0} Which is great because that's the letter of my first name{0} W also stands for War Eagle!", Environment.NewLine)
Console.WriteLine("Press Enter to Exit")
Console.ReadLine()
End Sub
End Module
In your version of the code, it outputs all of the letters each time it loops. In my version of the code, it only outputs one letter each time it loops. The Select Case statement is basically a simpler way of writing a bunch of separate If statements.
However, it's silly to write a big Select Case like that. The best way to implement a loop is to have it iterate over some sort of indexed data-structure. In this case, all you need is a list of letters. The simplest way to do that is to just store all of the letters in a single string, like this:
Dim letters As String = "abcdefghijklmnopqrstuvw"
For counter As Integer = 0 To Max_Value Step 1
Console.Write(letters(counter))
Console.WriteLine(counter)
Console.ReadLine()
Next
Create seperate variable to be used in for loop. What is happening is that you are looping with variable counter and then incrementing it inside loop. This will always loop 22 times.
So declare seperate variable and loop on it.
Dim intC as integer
For intC = 0 to Max_Value step 1
counter = counter + 1
Next
You are declaring counter on Module level and as a private variable for your iteration.
Every time your for loop goes to the next step, the private counter is overwritten with a new value. You should rename it something else
For c As Integer = 0 To Max_Value Step 1
counter = counter + 1
Next
or
For c As Integer = 0 To Max_Value Step 1
counter = c
Next
you probably want this:
For c as Integer = 0 To Max_Value ' Step 1 is default so you can skip that
Console.Write(Convert.ToChar(c + 97)) ' 97 = a
Console.WriteLine(c)
Next
Update: This has not much to do with your original code but is an alternative approach
Dim maxvalue As Integer = 22
Dim counter As Integer = 0
For Each c As Char In "abcdefghijklmnopqrstuvw".ToCharArray()
counter += 1
If counter = maxvalue Then
Dim ordinal As String = "th"
Select Case counter
Case 1 : ordinal = "st"
Case 2 : ordinal = "nd"
Case 3 : ordinal = "rd"
End Select
Console.WriteLine("{0} is the {1}{2} letter in the alphabet", c, maxvalue, ordinal)
Exit For
End If
Next