Echo
Echo

Reputation: 75

Nested loop with same variable

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.

Upvotes: 0

Views: 611

Answers (5)

dotNET
dotNET

Reputation: 35450

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).

Upvotes: 1

Leopold Stotch
Leopold Stotch

Reputation: 1522

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

Upvotes: 1

Steven Doggart
Steven Doggart

Reputation: 43743

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.

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460288

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

Upvotes: 0

Nadeem_MK
Nadeem_MK

Reputation: 7699

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

Upvotes: 0

Related Questions