Get up to 80 % extra points for free! More info:

Lesson 5 - Conditions (branching) in VB.NET

In the previous exercise, Solved tasks for Visual Basic .NET lesson 4, we've practiced our knowledge from previous lessons.

Lesson highlights

Are you looking for a quick reference on conditions (branching) in VB.NET instead of a thorough-full lesson? Here it is:

Controlling the program's flow using the If, Then and End If keywords:

Console.WriteLine("Enter your name:")
Dim name As String = Console.ReadLine()
If name = "Peter" Then
    Console.WriteLine("Hey, I'm Peter too!") ' printed only when Peter is entered
End If
Console.WriteLine("Thanks for your name!") ' printed always
Console.ReadKey()

Reacting to both situations (when the condition is met and when not) using Else:

Console.WriteLine("Enter your name:")
Dim name As String = Console.ReadLine()
If name = "Peter" Then
    Console.WriteLine("Hey, I'm Peter too!") ' printed only when Peter is entered
    Console.WriteLine("Nice to meet you!") ' printed only when Peter is entered
Else
    Console.WriteLine("Nice to meet you, I'm Peter!") ' printed for any other name
End If
Console.WriteLine("Thanks for your name!") ' printed always
Console.ReadKey()

Using the And and Or operators and eventually additional ()/If...Then/Else/End If statements:

Console.WriteLine("Enter your name:")
Dim name As String = Console.ReadLine()
If name = "Peter" Then
    Console.WriteLine("Hey, I'm Peter too!") ' printed only when Peter is entered
    Console.WriteLine("Nice to meet you!") ' printed only when Peter is entered
Else
    If name = "Mike" Or name = "Michael" Then
        Console.WriteLine("My brother's name is Michael too!") ' printed only when Michael is entered
    End If
    Console.WriteLine("Nice to meet you, I'm Peter!") ' printed for any other name than Peter
End If
Console.WriteLine("Thanks for your name!") ' printed always
Console.ReadKey()

Reacting to multiple states of one variable using a Select Case statement:

Console.WriteLine("Welcome to our calculator")
Console.WriteLine("Enter the first number:")
Dim a As Double = Console.ReadLine()
Console.WriteLine("Enter the second number:")
Dim b As Double = Console.ReadLine()
Console.WriteLine("Choose one of the following operations:")
Console.WriteLine("1 - addition")
Console.WriteLine("2 - subtraction")
Console.WriteLine("3 - multiplication")
Console.WriteLine("4 - division")
Dim choice As Integer = Console.ReadLine()
Dim result As Double = 0
Select Case choice
    Case 1
        result = a + b
    Case 2
        result = a - b
    Case 3
        result = a * b
    Case 4
        result = a / b
End Select
If choice > 0 And choice < 5 Then
    Console.WriteLine("Result: {0}", result)
Else
    Console.WriteLine("Invalid option")
End If
Console.WriteLine("Thank you for using our calculator. Press any key to end the program")
Console.ReadKey()

Would you like to learn more? A complete lesson on this topic follows.

In the previous lesson, Solved tasks for Visual Basic .NET lesson 4, we discussed Visual Basic .NET data types in details. We need to react somehow to different situations if we want to program something. It may be, for example, a value entered by the user, according to which we would like to change the running of the program. We metaphorically say that the program branches, and for branching we use conditions. We will pay attention to those in today's article. We're going create a program which calculates square roots, and which we're going to use to improve our calculator.

Conditions

We write conditions using the If keyword, which is followed by a logical expression and the Then keyword. If the expression is true, the following statement will be executed. If it's not true, the following statement will be skipped, and the program will continue with the next statement. The condition is terminated by the End If sequence. Let's try it out:

If 15 > 5 Then
    Console.WriteLine("True")
End If
Console.WriteLine("The program continues here...")
Console.ReadKey()

The output:

Console application
True
The program continues here...

If the condition is true, the command which writes text to the console will be executed. In both cases the program continues. Of course, a variable can also be part of the expression:

Console.WriteLine("Enter a number")
Dim a As Integer = Console.ReadLine()
If a > 5 Then
    Console.WriteLine("The number you entered is greater than 5!")
End If
Console.WriteLine("Thanks for the input!")
Console.ReadKey()

Let's look at the relational operators which we can use in expressions:

Meaning Operator
Equal to =
Greater than >
Less than <
Greater than or equal to >=
Less than or equal to <=
Not equal <>
Negation Not

We use the = operator for both equality or assigning a value to a variable. If we want to negate an expression, we write the Not keyword before it. Let's try another example:

Console.WriteLine("Enter some number and I'll calculate a square root:")
Dim a As Integer = Console.ReadLine()
If a > 0 Then
    Console.WriteLine("The number you entered is greater than 0, so I can calculate it!")
    Dim root As Double = Math.Sqrt(a)
    Console.WriteLine("The square root of " & a & " is " & root)
End If
Console.WriteLine("Thanks for the input")
Console.ReadKey()

The output:

Console application
Enter some number and I'll calculate a square root:
144
You've entered a number greater than 0, I can calculate it!
Square root of 144 is 12
Thanks for the input

The program retrieves a number from the user, and if it's greater than 0, it calculates the square root. We have used the Math class, which contains plenty of useful mathematical methods. At the end of this course, we'll learn more about them. Sqrt() returns the value as a double data type. It'd be nice if our program warned us if we entered a negative number. With what we know up until now, we could write something like this:

Console.WriteLine("Enter a number and I'll get its square root:")
Dim a As Integer = Console.ReadLine()
If a > 0 Then
    Console.WriteLine("The number you entered is greater than 0, so I can calculate it!")
    Dim root As Double = Math.Sqrt(a)
    Console.WriteLine("The square root of " & a & " is " & root)
End If
If a <= 0 Then
    Console.WriteLine("I can't calculate the square root of a negative number!")
End If
Console.WriteLine("Thanks for the input!")
Console.ReadKey()

We must keep in mind the case where a = 0, but also when it's less than 0. The code can be greatly simplified by using the Else keyword which executes the following statement or block of statements if the condition was not true:

Console.WriteLine("Enter a number and I'll get its square root:")
Dim a As Integer = Console.ReadLine()
If a > 0 Then
    Console.WriteLine("The number you entered is greater than 0, so I can calculate it!")
    Dim root As Double = Math.Sqrt(a)
    Console.WriteLine("The square root of " & a & " is " & root)
Else
    Console.WriteLine("I can't calculate the square root of a negative number!")
End If
Console.WriteLine("Thanks for the input!")
Console.ReadKey()

The code is much clearer, and we don't have to make up the negate condition which could be very difficult with complex conditions sometimes.

We also use the Else keyword when we need to modify the variable used in a condition so we can't evaluate it later again. The program remembers that the condition didn't apply and it'll move to the Else branch. Let's look at an example: Consider a number which value will be either 0 or 1 and we'll be asked to swap those values (if there is 0, we put a 1 there, and the other way around). Naively, we could write a code like this:

Dim a As Integer = 0 'the variable is initialized with a value of 0

If a = 0 Then 'if the value is 0, we change its value to 1
    a = 1
End If
If a = 1 Then 'if the value is 1, we change its value to 0
    a = 0
End If

Console.WriteLine(a)
Console.ReadKey()

It doesn't work, does it? Let's take a closer look at the program. At the very beginning, a contains the value 0, the first condition is undoubtedly fulfilled and it assigns 1 into a. Well, suddenly, the second condition becomes true as well. What should we do? When we swap the conditions, we'll have the same problem with 1. Now, how do we solve this? You guessed it, using Else!

Dim a As Integer = 0 'the variable is initialized with a value of 0

If a = 0 Then 'if the value is 0, we change its value to 1
    a = 1
Else 'if the value is 1, we change its value to 0
    a = 0
End If

Console.WriteLine(a)
Console.ReadKey()

Conditions can be composed by using two basic logical operators:

Operator VB.NET syntax
Logical AND And
Logical OR Or

Let's take a look at the example:

Console.WriteLine("Enter a number between 10-20:")
Dim a As Integer = Console.ReadLine()
If a >= 10 And a <= 20 Then
    Console.WriteLine("The condition has been met.")
Else
    Console.WriteLine("You did it wrong.")
End If
Console.ReadKey()

Of course operators can be combined with parentheses:

Console.WriteLine("Enter a number between 10-20 or 30-40:")
Dim a As Integer = Console.ReadLine()
If ((a >= 10) And (a <= 20)) Or ((a >= 30) And (a <= 40)) Then
    Console.WriteLine("The condition has been met.")
Else
    Console.WriteLine("You did it wrong.")
End If
Console.ReadKey()

Select Case

Select Case allows us to relatively simplify the usage of If-Else command sequences. Let's remember our calculator from the first lesson, which had read two numbers and calculated all 4 operations. Now, we want to choose the operation. Without the Select Case, we'd write the code like this:

Console.WriteLine("Welcome to our calculator")
Console.WriteLine("Enter the first number:")
Dim a As Double = Console.ReadLine()
Console.WriteLine("Enter the second number:")
Dim b As Double = Console.ReadLine()
Console.WriteLine("Choose one of the following operations:")
Console.WriteLine("1 - addition")
Console.WriteLine("2 - subtraction")
Console.WriteLine("3 - multiplication")
Console.WriteLine("4 - division")
Dim choice As Integer = Console.ReadLine()
Dim result As Double = 0
If choice = 1 Then
    result = a + b
Else
    If choice = 2 Then
        result = a - b
    Else
        If choice = 3 Then
            result = a * b
        Else
            If choice = 4 Then
                result = a / b
            End If
        End If
    End If
End If
If choice > 0 And choice < 5 Then
    Console.WriteLine("Result: {0}", result)
Else
    Console.WriteLine("Invalid choice")
End If
Console.WriteLine("Thank you for using our calculator. Press any key to end the program.")
Console.ReadKey()

The output:

Console application
Welcome to our calculator
Enter the first number:
3.14
Enter the second number:
2.72
Choose one of the following operations:
1 - addition
2 - subtraction
3 - multiplication
4 - division
2
Result: 0.42
Thank you for using our calculator. Press any key to end the program.

Notice that we've declared the variable result at the beginning, so we could later assign something to it. If we declared it at every assignment, Visual Basic would not compile the code and report an error since the variable would be already declared. A variable can be declared only once. VB.NET is not able to tell whether a value has been already assigned to the result variable. It would report an error on the line where we're printing to the console because VB.NET doesn't like the fact that the variable being printed is not guaranteed to contain a value. For this reason, we have to assign zero to the result variable at the beginning. Another trick is validating the user's choice. The program should still work the same even without all the Elses (but why keep on asking if we already have a result).

Now here's the same program using a Select Case:

Console.WriteLine("Welcome to our calculator")
Console.WriteLine("Enter the first number:")
Dim a As Double = Console.ReadLine()
Console.WriteLine("Enter the second number:")
Dim b As Double = Console.ReadLine()
Console.WriteLine("Choose one of the following operations:")
Console.WriteLine("1 - addition")
Console.WriteLine("2 - subtraction")
Console.WriteLine("3 - multiplication")
Console.WriteLine("4 - division")
Dim choice As Integer = Console.ReadLine()
Dim result As Double = 0
Select Case choice
    Case 1
        result = a + b
    Case 2
        result = a - b
    Case 3
        result = a * b
    Case 4
        result = a / b
End Select
If choice > 0 And choice < 5
    Console.WriteLine("result: {0}", result)
Else
    Console.WriteLine("Invalid choice")
End If
Console.WriteLine("Thank you for using our calculator. Press any key to end the program.")
Console.ReadKey()

Beside of Case x, the Select Case can also contain the Case Else branch, which will be executed if neither of the Cases applied. It's up to you whether you use a Select Case or not. Generally, it's useful only for a larger amount of branches and you always could always it with an If-Else sequence. Obviously, you can use a Select Case for string variables as well.

That is all for today. In the next lesson, Solved tasks for Visual Basic .NET lesson 5, we'll take a look at arrays and loops, i.e. finish up with the absolute basics of the VB.NET language. Look forward to it :)

In the following exercise, Solved tasks for Visual Basic .NET lesson 5, we're gonna practice our knowledge from previous lessons.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 24x (101.41 kB)
Application includes source codes in language VB.NET

 

Previous article
Solved tasks for Visual Basic .NET lesson 4
All articles in this section
Visual Basic (VB.NET) Basic Constructs
Skip article
(not recommended)
Solved tasks for Visual Basic .NET lesson 5
Article has been written for you by Michal Zurek
Avatar
User rating:
4 votes
Activities