user1739123
user1739123

Reputation: 93

Visual Basic loop never ends

I am attempting to print a diamond in Visual Basic. The top half of my code works perfectly, but for some reason I can't get the bottom half to work in a similar manner. In the bottom half, spaces are printed out after the o(used to make the diamond), and the decreasing number of o's sends the program into an infinite loop? Can anyone help?

The bottom half may be completely wrong, I'm still working on it

Here is the code:

Option Explicit On
Imports System

Module diamond
    Sub Main()
        ' The o variable will make the "o" part of the diamond, the space variable will be for places without an "o". 
        Dim row, spaces, o as Integer  
        'Dim index as integer

        'For top half
        ' Count the row number.
        row = 1
        spaces = 9
        o = 1
        Do until row = 20
            ' Count of row increases every loop until half of diamond is done.
            row +=1
            ' Write 1 less space every line.
            For row = 1 to spaces
                console.write(" ")
            Next row
            spaces -=1
            'Write 2 more "o"'s every loop.
            For row = 1 to o 
                Console.write("o")
            Next row    
            o +=2
            Console.Writeline
        Loop
        'Top of the diamond is done

        'This is the bottom half, which will not work.
        row = 20

        Do until row = 40
            row +=1
            For row = 20 to spaces
                Console.write(" ")
            Next row
            spaces +=1
            'Write 2 less "o"'s every loop.
            For row = 20 to o 
                Console.write("o")
            Next row    
            o -=2
            Console.Writeline
        Loop
    End Sub
End Module 

Upvotes: 2

Views: 1101

Answers (1)

Andrew Cooper
Andrew Cooper

Reputation: 32576

The problem is that you're using row as your row counter for the while loops and also as the loop index for the for loops. It's accidental that the first half works at all. In the second half row never gets to 40 because it keeps getting hijacked by the for loops.

Try For i = 20 to spaces, etc, instead.

Upvotes: 3

Related Questions