Nested loop with same variable - vb.net

Is that possible for me to do nested loop in VB with same counter
The code is somehow like this
For a As Integer = 1 to Console.ReadLine
For a = 1 to a
Console.WriteLine("*")
Next
Console.WriteLine()
Next
The program is designed for drawing a triangle of * with just a single variable at all
VB just disallow me to use a in nested loop again
Error: ...Variable 'a' is alreay used by a independent loop.
I have my own usage, can only use 1 variable.

What changing the second FOR loop to a WHILE loop?
For a As Integer = 1 to Console.ReadLine
Do While a <=5
Console.WriteLine("Line: " & a)
Exit Do
Loop
Next

Here's a different idea. You may consider splitting your integer variable into 2 parts 16-bit parts, keep user's input in the upper 16-bits, and current iteration value in the lower 16-bits (you'll need to use WHILE instead of FOR).

In fact, what you need is to start your inner counter by the value of a, if I've understand. And what you are doing is create another loop inside starting by 1.
For a As Integer = 1 to Console.ReadLine
For b As Integer = a to 5
Console.WriteLine("Line: " & a)
Next
Next

You cannot declare another variable with the same name in the same scope. But the inner loop is in the same scope as the outer loop. That's why you get that compiler error.
You can use a different name:
Dim i As Int32
If Int32.TryParse(Console.ReadLine, i) AndAlso i > 0 Then
For a As Integer = 1 To i
For aa = 1 To i
Console.WriteLine("Line: {0} {1}", a, aa)
Next
Next
End If

To draw a triangle, as you describe, you need two variables, like this:
For a As Integer = 1 to Console.ReadLine
For b As Integer = 1 to a
Console.Write("*")
Next
Console.WriteLine()
Next
If you used the same variable in the inner loop, the inner loop would change the value of the variable, which in most cases would not be what you want, and in all cases would be incredibly confusing. For that reason, VB forces you to use a different iterator in each nested For loop.

Related

How do I add a string input to an array?

basically i need to add a name to an array of candidates for an election. the user enters the candidates names, and i want to store them in an array. so far i have this:
Dim CandidateNames(candidates) As String
Dim x As Integer
'entering the names of each candidate so students can vote for them.
For x = 1 To candidates
Console.WriteLine("Enter a candidates name:")
CandidateNames(candidates) = Console.ReadLine()
Next
For x = 0 To candidates - 1
Console.WriteLine(CandidateNames(candidates) & " is candidate " & x)
Next
i want to then output all the names, which is what the second for loop does, but it only outputs the last entered name.
im in my second GCSE year of computer science, having never done any programming before so go easy on me please.
Here is the working code:
Dim candidates as Integer
candidates=5
Dim CandidateNames(candidates) As String
Dim x As Integer
For x = 0 To candidates
Console.WriteLine("Enter a candidates name:")
CandidateNames(x) = Console.ReadLine()
Next
For x = 0 To candidates
Console.WriteLine(CandidateNames(x) & " is candidate ")
Next
In your code, you are not storing and accessing the strings correctly.
There are two issues with your code. The first is with your loop bounds: the first loop is this:
For x = 1 to candidates
And the second loop is this:
For x = 0 to candidates - 1
In .NET, the lower bound for one-dimensional arrays is always 0 (insert rant about .NET array indexing design choices here), so you should be starting from 0 as in the second loop. I can never remember if VB arrays specify the upper bound or the count when you declare them, but conceptually the second is correct for the final index: if you want an array of n items, then it will be indexed from 0 to n - 1.
The second issue is that inside each loop, you are referring to CandidateNames(candidates) instead of CandidateNames(x). Instead of moving through each item in the loop in turn, you are only operating on the last item in the array.
Unless this is for an assignment requiring to use arrays, I'd suggest you consider using List(Of String) instead. Arrays make sense for a more limited set of uses cases, and I don't think this is one of them. Usually, the number of candidates for an election will be variable; with a list, you can have the user enter candidates until they're done, and the list will automatically expand as you go. Then, you can use a For Each loop to write out the contents of the list (though note you could use a For Each loop with an array as well). A list can still be accessed by index like an array.

Even Odd numbers using Nested For Next Loop VBA

How do I create a For-Next loop determining whether the numbers listed are even or odd
You can try something like this:
Dim i As Integer
For i = 1 To 6
If i mod 2 = 0 Then
'i is even
Else
'i is odd
End If
Next i

Remove elements in an arraylist that exist in another arraylist

i have 2 array list, dateListDead and dateListNotMinggu. Both is DateTime List of Array. This is the ilustration of the date value in list of array
The arrayList value
its supposed to remove specific element that exist in other array list.
so far i tried, this code it's not working.
Dim d, x As Integer
For x = 0 To dateListDead.Count - 1
For d = 0 To dateListNotMinggu.Count - 1
If dateListNotMinggu(d) = dateListDead(x) Then
dateListNotMinggu.RemoveAt(d)
End If
Next
Next
the error is : index out of range. how could it be ? i define the parameter of end looping base on arraylist.count -1
The main is that you are using a For loop from the first index to the last index but you don't account for the change of index when you remove a value. If there might be multiple values then you should start and the end rather than the beginning. In that case, removing an item won't affect the indexes of the items you are yet to test. If there can only be one match then you should be exiting the loop when you find one.
Either way, while you don't have to, I would suggest using a For Each loop on the outside. If you want to perform an action for each item in a list then that's exactly what a For Each loop is for. Only use a For loop if you need to use the loop counter for something other than accessing each item in turn.
For multiple matches:
For Each dateDead As Date In dateListDead
For i = dateListNotMinggu.Count - 1 To 0 Step -1
If CDate(dateListNotMinggu(i)) = dateDead Then
dateListNotMinggu.RemoveAt(i)
End If
Next
Next
For a single match:
For Each dateDead As Date In dateListDead
For i = 0 To dateListNotMinggu.Count - 1
If CDate(dateListNotMinggu(i)) = dateDead Then
dateListNotMinggu.RemoveAt(i)
Exit For
End If
Next
Next
Note that I have also cast the Date values as that type for comparison, which is required with Option Strict On. Option Strict is Off by default but you should always turn it On because it will help you write better code by focusing on data types.
Also, the code above would work with a List(Of Date) as well as an ArrayList but the casts would not be required with a List(Of Date). That's one of the advantages of using a generic List(Of T) over an ArrayList, which paces no restrictions on what it can contain.
If you really must use a For loop because that's what your homework assignment says then it would look like this:
For i = 0 To dateListDead.Count - 1
For j = dateListNotMinggu.Count - 1 To 0 Step -1
If CDate(dateListNotMinggu(j)) = CDate(dateListDead(i)) Then
dateListNotMinggu.RemoveAt(j)
End If
Next
Next
and this:
For i = 0 To dateListDead.Count - 1
For j = 0 To dateListNotMinggu.Count - 1
If CDate(dateListNotMinggu(j)) = CDate(dateListDead(i)) Then
dateListNotMinggu.RemoveAt(j)
Exit For
End If
Next
Next
Note that it is convention to use i as a first option for a loop counter, then j for the first nested loop, then k for the second nested loop. You should only use something else if you have good reason to do so. Remember that the loop counter doesn't represent the value in the list but rather its index. That's why you use i for index and not d for date or the like.
EDIT:
As per Jimi's comment below, the way this would usually be tackled is with a simple LINQ query. If you were using LINQ then you definitely wouldn't be using an ArrayList but rather a List(Of Date). In that case, the code would look like this:
dateListNotMinggu = dateListNotMinggu.Except(dateListDead).ToList()
If you were completely insane and wanted to use LINQ and ArrayLists then this would work:
dateListNotMinggu = New ArrayList(dateListNotMinggu.Cast(Of Date)().
Except(dateListDead.Cast(Of Date)()).
ToArray())
Take note that, as I replied in the comments, using LINQ will generate a new list, rather than changing the existing one.

For loop to print control characters

Alright, so I am editing a Macro for Reflection Workspace Terminal Emulator. I have a macro (it is long and not necessarily relevant, I can post the full code if anyone wants, it is about a page)
At the very end of the macro, a "Good Morning" Message is printed, and then also the value of a string variable named myName. This works fine.
What I want to do is then use a For loop to print a number of control characters (tab) equal to the amount printed in the Good Morning User. Here is the code I have so far:
Dim X As Integer
For i = 1 To i = (13 + Len(myName)) 'Good Morning + a space character will always = 13
ibmCurrentScreen.SendKeys (ControlKeyCode_Tab)
Next i
End Sub
I would use the Chr() function to print the control characters, but it seems that this particular program uses ControlKeyCode_X to print them.
The For...Next loop in VBA is a simple single variable counter based loop and cannot have complex criteria or multiple counters like in some other languages (e.g. in C# for(int i = 0, int j = 10; i < 10; i++, j--)). In VBA, therefore, the i = after To is redundant because it cannot be anything other than i.
The 'For' loop in VBA therefore only specifies the counter once. It should be:
For i = startVal To endVal [step incrementVal]
...
Next [i]
i = variable to vary
startVal = start value
endVal = end value (inclusive, i.e. To 10 will include 10 as the final value)
incrementVal = optional value to increment/decrement by each loop
(default = 1)
The counter is always incremented/decremented at the end of each loop then evaluated against endVal (i.e. for a vanilla increment by one loop, after exiting the loop it will be endValue + 1).
Note (unrelated to your situation) that you can change the value of i in the loop, e.g. to increment twice because of some special circumstance.
Specifying the variable with the Next statement is optional and has no effect on behaviour (any nested loop must always be closed before an outer loop) but is good practice for reference when you have many For...Next loops so it is clear which loop the Next is closing (although you should be religiously indenting or otherwise delineating your code)
So in your case For i = 1 To (13 + Len(myName)) instead.

The do while loop structure

In the do while loop structure usually there's a part where you declare a variable equal to a number (in this case i) and then in a second part you make a increment (i+1). I've made this example in vba, but the structure could be repeated in several different programming languages like the for in php when you're getting data from a database. Now, what I would like to understand better is the relation between the previous mentioned declarations, that is i = some number and i = i + 1 . Wouldn't this generate a problem of interpretation since you're declaring a variable to something and then assigning a different value right after it? Is the second declaration of the variable value, i = i + 1, a new variable calling the previous one or both i's are the same? This is the general orientation I intend with this question. I think explaining the scoop of both variables would help understanding. Thanks!
Sub DoWhile()
Dim x, i, sum
x = 10
i = 1
sum = 0
Do While i < x
sum = sum + i
i = i + 1
Loop
MsgBox “Sum = ” & sum
End Sub
A variable is really just a location in memory. That location can have any value. By setting i=i+1, you're really saying "take the value at position i, add 1 to it, and store it at position i". No new variable is created. There's no problem with the computer interpreting this- what it cares about is the location of i, which isn't changing. It still knows where to find i, regardless of how many times you change the value there.
Since you have created the variable i as a global variable, any reference or modification to i in the sub will be on the same variable. That being said:
Dim i as int
i = 1
Do while i < 11
MsgBox("The value of i is: " & i)
i = i + 1
Loop
would display 10 messageboxes showing the value of i being between 1 and 10.
When the program encounters i = i + 1, the computer 'sees' this as take the value of i, add one to it, and store the result in the variable i.
Hope that helps.