Visual Basic 2008 9.0 .NET Examples and Ebook

Introduction to Visual Basic

Vorig Onderwerp

New in Visual Basic 2008 - 9.0

|

Arrays

Volgend Onderwerp

Iterations

Vorig Onderwerp

Nested Structures

|

Selections

Volgend Onderwerp
Do While ... Loop

Do While ... Loop

Do Until ... Loop

Do Until ... Loop

Do ... Loop While ... and Do ... Loop Until ...

Do ... Loop While ... and Do ... Loop Until ...

For ... Next

For ... Next

For Each ... Next

For Each ... Next

Exercises

Exercises



Do While ... Loop


Following example brings all number from 1 to 10 to the console.


Module Example1
    Sub Main()
        Dim value As Integer
        '
        Do While value < 10
            value = value + 1
            Console.WriteLine(value)
        Loop
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10

Klik hier om terug naar boven te gaan.  Up



Do Until ... Loop


A variation of previous example could use Until instead of While.

When While is used, the body of the iteration will repeat while the condition is True, or until the condition is False.
In case of Until, the body of the iteration will repeat until the condition is True, or while the condition is False.


Module Example2
    Sub Main()
        Dim value As Integer
        '
        Do Until value >= 10
            value = value + 1
            Console.WriteLine(value)
        Loop
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10

Klik hier om terug naar boven te gaan.  Up



Do ... Loop While ... and Do ... Loop Until ...


It is also possible to place the While or Until clause at the end of the iteration ( following Loop ). In that case the condition is evaluated after execution of the body of the iteration. The body of the iteration will execute at least one time.

Following examples use a Do ... Loop with a While or Until clause at the end of the iteration to bring all numbers from 1 to 10 to the console.


Module Example3
    Sub Main()
        Dim value As Integer
        '
        Do
            value = value + 1
            Console.WriteLine(value)
        Loop While value < 10
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10

Module Example4
    Sub Main()
        Dim value As Integer
        '
        Do
            value = value + 1
            Console.WriteLine(value)
        Loop Until value >= 10
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10

To convert a condition of a While to Until iteration, or vice versa, you need to invert the condition.
A value is only not "less than ten" when it is "more than or equal to ten". _
So iteration While value < 10 can be converted to Until value >= 10.

Later on we'll see how condition can be inverted with the 'Not' operator.

Suppose we need a program that iterates over all integral value ( starting with 1 ) up to the value provided by the user.


Module Example5
    Sub Main()
        Console.WriteLine("Highest Value ?")
        Dim highest As Integer = Console.ReadLine()
        '
        Console.WriteLine("Row :")
        Dim value As Integer
        Do
            value = value + 1
            Console.WriteLine(value)
        Loop Until value >= highest
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 Highest Value ?
 5
 Row :
 1
 2
 3
 4
 5

The problem with the above algorithm is that when we enter 0, we don't get an empty row, but the row contains 1.


Output :

 Highest Value ?
 0
 Row :
 1

By placing the condition before the body of the iteration that problem gets solved.


Module Example6
    Sub Main()
        Console.WriteLine("Highest Value ?")
        Dim highest As Integer = Console.ReadLine()
        '
        Console.WriteLine("Row :")
        Dim value As Integer
        Do Until value >= highest
            value = value + 1
            Console.WriteLine(value)
        Loop
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 Highest Value ?
 5
 Row :
 1
 2
 3
 4
 5

Output :

 Highest Value ?
 0
 Row :

Klik hier om terug naar boven te gaan.  Up


For ... Next


Instead of stating how long ( While ) or until when ( Until ) some instructions need to be repeated, one could use a For ... Next iteration that repeats instructions for every value a variable can take within a defined range.

Again all value from 1 to 10 are brought to the console.


Module Example7
    Sub Main()
        Dim value As Integer
        '
        For value = 1 To 10
            Console.WriteLine(value)
        Next
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10

The body of this iteration is repeated 10 times, or repeated for every value from 1 to 10 ( including 1 and 10 ), with a default step of 1.

It is not necessary to start with 1, every value the countervariable ( value ) can take, is a legal startvalue.


Module Example8
    Sub Main()
        Dim value As Integer
        '
        For value = 10 To 15
            Console.WriteLine(value)
        Next
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 10
 11
 12
 13
 14
 15

An optional Step clause can be used to divert from the default stepvalue 1.


Module Example9
    Sub Main()
        Dim value As Integer
        '
        For value = 2 To 10 Step 2
            Console.WriteLine(value)
        Next
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 2
 4
 6
 8
 10

Negative stepvalue are possible. But make sure the startvalue is more than the endvalue, otherwise the body would never execute.


Module Example10
    Sub Main()
        Dim value As Integer
        '
        For value = 10 To 0 Step -2
            Console.WriteLine(value)
        Next
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 10
 8
 6
 4
 2
 0

The countervariable can be of any numeric datatype ( including enumeration types ).

Automatically the countervalue is raised with the stepvalue when reaching Next.

Variables ( or any variable expression ) can be used to define then start-, end- and stepvalues.


Module Example11
    Sub Main()
        Dim countValue As Integer
        Dim startValue As Integer = 1
        Dim endValue As Integer = 10
        Dim stepValue As Integer = 2
        '
        Console.WriteLine("values during iteration :")
        For countValue = startValue To endValue Step stepValue
            Console.WriteLine("count-value : " & countValue)
            '
            countValue = countValue + 1
            startValue = startValue + 1
            endValue = endValue + 1
            stepValue = stepValue + 1
        Next
        '
        Console.WriteLine("values after iteration :")
        Console.WriteLine("count-value : " & countValue)
        Console.WriteLine("start-value : " & startValue)
        Console.WriteLine("end-value   : " & endValue)
        Console.WriteLine("step-value  : " & stepValue)
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 values during iteration :
 count-value : 1
 count-value : 4
 count-value : 7
 count-value : 10
 values after iteration :
 count-value : 13
 start-value : 5
 end-value   : 6
 step-value  : 6

Be aware of the fact that start-, end- or stepvalues are evaluated only once for the For ... Next iteration.
If start-, end- or stepvalues change within the body of the iteration, this will have no effect on the iteration itself.

It is inadvisable to change start-, end- or stepvalues within the body of the iteration. As you can see in the above example, this leads to code that is very difficult to read/understand.


Klik hier om terug naar boven te gaan.  Up


For Each ... Next


Later on we'll see how we can iterate over the elements of an iteration using a 'For Each ... Next' iteration.


Klik hier om terug naar boven te gaan.  Up


Exercises


Task :

Create a program to calculate the factorial for a given value.

The factorial of a value X equals X * (X-1) * (X-2) * ... * 1, for instance 5! = 5 * 4 * 3 * 2 * 1 = 120.


Output :

 Value ?
 <i>5</i>
 5! = 120

Solution :


Module Exercise1Solution
    Sub Main()
        Console.WriteLine("Value ?")
        Dim value As Integer = Console.ReadLine()
        '
        Dim factorial As Integer = value
        Dim factor As Integer = value - 1
        '
        For factor = value - 1 To 2 Step -1
            factorial = factorial * factor
        Next
        '
        Console.WriteLine(value & "! = " & factorial)
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Task :


Bring all seconds of all minutes of all hours to the console. Do this in following format.


Output :

 00h00m00s
 00h00m01s
 ...
 00h00m59s
 00h01m00s
 ...
 00h59m59s
 01h00m00s
 ...
 23h59m59s

Solution :


Module Exercise2Solution
    Sub Main()
        Dim hours, minutes, seconds As Integer
        Dim timeLabel As String
        For hours = 0 To 23
            For minutes = 0 To 59
                For seconds = 0 To 59
                    timeLabel = ""
                    If hours < 10 Then
                        timeLabel = "0"
                    End If
                    timeLabel = timeLabel & hours & "h"
                    If minutes < 10 Then
                        timeLabel = timeLabel & "0"
                    End If
                    timeLabel = timeLabel & minutes & "m"
                    If seconds < 10 Then
                        timeLabel = timeLabel & "0"
                    End If
                    timeLabel = timeLabel & seconds & "s"
                    Console.WriteLine(timeLabel)
                Next
            Next
        Next
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Task :


Create a program that converts seconds to a format using days, hours, minutes and seconds.

The conversions are repeated until the user enters 0.

When a negative value is entered, an error is produced.

Only include number of days, hours, minutes or seconds when the amounts are above 0.


Output :

 Seconds ?
 <i>-1</i>
 Error : Only positive values are accepted !
 Seconds ?
 <i>1000000</i>
 Result :
 days
 13 hours
 46 minutes
 40 seconds
 Seconds ?
 <i>999960</i>
 Result :
 11 days
 13 hours
 46 minutes
 Seconds ?
 <i>49600</i>
 Result :
 13 hours
 46 minutes
 40 seconds
 Seconds ?
 <i>2800</i>
 Result :
 46 minutes
 40 seconds
 Seconds ?
 <i>2760</i>
 Result :
 46 minutes
 Seconds ?
 <i>0</i>
 End.

Solution :


Module Exercise3Solution
    Sub Main()
        Dim totalSeconds, remainingSeconds As Integer
        Dim days, hours, minutes, seconds As Integer
        '
        Do
            Console.WriteLine("Seconds ?")
            totalSeconds = Console.ReadLine()
            If totalSeconds = 0 Then
                Console.WriteLine("End.")
            Else
                If totalSeconds < 0 Then
                    Console.WriteLine("Error : " & _
                                      "Only positive values are accepted !")
                Else
                    remainingSeconds = totalSeconds
                    days = remainingSeconds \ 86400
                    remainingSeconds = remainingSeconds - days * 86400
                    hours = remainingSeconds \ 3600
                    remainingSeconds = remainingSeconds - hours * 3600
                    minutes = remainingSeconds \ 60
                    seconds = remainingSeconds - minutes * 60
                    Console.WriteLine("Result :")
                    If days > 0 Then
                        Console.WriteLine(days & " days")
                    End If
                    If hours > 0 Then
                        Console.WriteLine(hours & " hours")
                    End If
                    If minutes > 0 Then
                        Console.WriteLine(minutes & " minutes")
                    End If
                    If seconds > 0 Then
                        Console.WriteLine(seconds & " seconds")
                    End If
                End If
            End If
        Loop Until totalSeconds = 0
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Task :


Make a program to add values. The number of values to add is undefined.


Output :

 <i>1</i>
 +
 <i>2</i>
 +
 <i>3</i>
 +
 <i>4</i>
 +
 <i>5</i>
 +
 <i>0</i>
 =
 15

Output :

 <i>0</i>
 =
 0

Solution :


Module Exercise4Solution
    Sub Main()
        Dim number, sum As Integer
        '
        Do
            number = Console.ReadLine()
            If number = 0 Then
                Console.WriteLine("=")
                Console.WriteLine(sum)
            Else
                sum = sum + number
                Console.WriteLine("+")
            End If
        Loop Until number = 0
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Task :


Make a program to add or subtract values. The number of values to add is undefined.

The program needs to support the + ( to add ), - ( to subtract ) and = ( to get the result ) operators.


Output :

 <i>1</i>
 <i>=</i>
 1

Output :

 <i>1</i>
 <i>+</i>
 <i>2</i>
 <i>=</i>
 3

Output :

 <i>1</i>
 <i>-</i>
 <i>-5</i>
 <i>=</i>
 6

Output :

 <i>1</i>
 <i>+</i>
 <i>2</i>
 <i>-</i>
 <i>3</i>
 <i>-</i>
 <i>4</i>
 <i>+</i>
 <i>5</i>
 <i>-</i>
 <i>0</i>
 <i>+</i>
 <i>0</i>
 <i>=</i>
 1

Solution :


Module Exercise5Solution
    Sub Main()
        Dim number, result As Integer
        Dim operatorSymbol As String
        '
        number = Console.ReadLine()
        '
        result = number
        Do
            operatorSymbol = Console.ReadLine()
            If operatorSymbol = "=" Then
                Console.WriteLine(result)
            Else
                number = Console.ReadLine()
                If operatorSymbol = "+" Then
                    result = result + number
                Else
                    If operatorSymbol = "-" Then
                        result = result - number
                    End If
                End If
            End If
        Loop Until operatorSymbol = "="
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode




This version ( published on 2008-06-24 ) is printed from http://www.studyvb.com, visit the website for more recent information.

Updated On : 2008-02-25

Download Broncode

Published On : 2008-06-24

Iterations

Vorig Onderwerp

Nested Structures

|

Selections

Volgend Onderwerp

Introduction to Visual Basic

Vorig Onderwerp

New in Visual Basic 2008 - 9.0

|

Arrays

Volgend Onderwerp
Nederlands  Nederlands

Add to favorites (IE).