Jump to content

Programming Fundamentals/Loops/VB.NET

From Wikiversity

loops.vb

[edit | edit source]
' This program demonstrates While, Do, and For loop counting using
' user-designated Start, stop, and Increment values.
'
' References:
'     https://en.wikibooks.org/wiki/Visual_Basic_.NET

Imports System

Public Module Loops
    Sub Main
        Dim Start As Integer
        Dim Finish As Integer
        Dim Increment As Integer
        
        Start = GetValue("Starting")
        Finish = GetValue("ending")
        Increment = GetValue("Increment")

        WhileLoop(Start, Finish, Increment)
        DoLoop(Start, Finish, Increment)
        ForLoop(Start, Finish, Increment)
    End Sub
    
    Private Function GetValue(Name As String)
        Dim Input as String
        Dim Value As Integer
        
        Console.WriteLine("Enter " & Name & " value:")
        Input = Console.ReadLine()
        Value = Convert.ToInt32(Input)
        Return Value
    End Function
    
    Private Sub WhileLoop(
        Start As Integer, Finish As Integer, Increment As Integer)
        Console.WriteLine("While loop counting from " & Start & " to " & 
            Finish & " by " & Increment & ":")
        Dim Count As Integer
        
        Count = Start
        Do While Count <= Finish
            Console.WriteLine(Count)
            Count = Count + Increment
        Loop
    End Sub
    
    Private Sub DoLoop(
        Start As Integer, Finish As Integer, Increment As Integer)
        Console.WriteLine("Do loop counting from " & Start & " to " & 
            Finish & " by " & Increment & ":")
        Dim Count As Integer
        
        Count = Start
        Do
            Console.WriteLine(Count)
            Count = Count + Increment
        Loop While Count <= Finish
    End Sub
    
    Private Sub ForLoop(
        Start As Integer, Finish As Integer, Increment As Integer)
        Console.WriteLine("For loop counting from " & Start & " to " & 
            Finish & " by " & Increment & ":")
        Dim Count As Integer
        
        For Count = Start To Finish Step Increment
            Console.WriteLine(Count)
        Next
    End Sub
End Module

Try It

[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own VB.NET compiler / interpreter / IDE.

See Also

[edit | edit source]