Control Statements in VB.net – Control Flow Statements in VB.net

What is Control Statements in VB.net?

The Control Statements in VB.NET are the statements that control the execution of the program on the basis of the specified condition.

It is useful for determining whether a condition is true or not. If the condition is true, a single or block of statements is executed.

In the control statement, we will use if- Then, if Then Else, if Then ElseIf, and the Select case statement.

Control statements VB.net is a complete instruction in Visual Basic programs. It may contain keywords, operators, variables, literal values, constants, and expressions.

Control Statement in VB.net could be categorized as:

Declaration statements

Declaration statements − these are the statements where you name a variable, constant, or procedure, and can also specify a data type.

The declaration statements are used to name and define procedures, variables, properties, arrays, and constants.

When you declare a programming element, you can also define its data type, access level, and scope.

The programming elements you may declare include variables, constants, enumerations, classes, structures, modules, interfaces, procedures, procedure parameters, function returns, external procedure references, operators, properties, events, and delegates.

Following are the declaration statements in VB.net:

Sr.NoControl Statements in VB.net and DescriptionExample
1.Dim Statement
Declares and allocates storage space for one or more variables.
Dim number As Integer
Dim quantity As Integer = 100
Dim message As String = “Hello!”
2.Const Statement
Declares and defines one or more constants.
Const maximum As Long = 1000 Const naturalLogBase As Object = CDec(2.7182818284)
3.Enum Statement
Declares an enumeration and defines the values of its members.
Enum CoffeeMugSize
Jumbo
ExtraLarge
Large
Medium
Small
End Enum
4.Class Statement
Declares the name of a class and introduces the definition of the variables, properties, events, and procedures that the class comprises.
Class Box
Public length As Double
Public breadth As Double
Public height As Double
End Class
5.Structure Statement
Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that the structure comprises.
Structure Box
Public length As Double
Public breadth As Double
Public height As Double
End Structure
6.Module Statement
Declares the name of a module and introduces the definition of the variables, properties, events, and procedures that the module comprises.
Public Module
myModule Sub Main()
Dim user As String = InputBox(“What is your name?”)
MsgBox(“User name is” & user)
End Sub
End Module
7.Interface Statement
Declares the name of an interface and introduces the definitions of the members that the interface comprises.
Public Interface MyInterface
Sub doSomething()
End Interface
8.Function Statement
Declares the name, parameters, and code that define a Function procedure.
Function myFunction
(ByVal n As Integer) As Double Return 5.87 * n
End Function
9.Sub Statement
Declares the name, parameters, and code that define a Sub procedure.
Sub mySub (ByVal s As String)
Return
End Sub
10.Declare Statement
Declares a reference to a procedure implemented in an external file.
Declare Function getUserName Lib “advapi32.dll” Alias “GetUserNameA” ( ByVal lpBuffer As String, ByRef nSize As Integer) As Integer
11.Operator Statement
Declares the operator symbol, operands, and code that define an operator procedure on a class or structure.
Public Shared Operator + (ByVal x As obj, ByVal y As obj) As obj Dim r As New obj ‘ implemention code for r = x + y Return r End Operator
12.Property Statement
Declares the name of a property, and the property procedures used to store and retrieve the value of the property.
ReadOnly Property quote() As String Get Return quoteString End Get End Property
13.Event Statement
Declares a user-defined event.
Public Event Finished()
14.Delegate Statement
Used to declare a delegate.
Delegate Function MathOperator( ByVal x As Double, ByVal y As Double ) As Double
Declaration Statements and Description

Executable statements

Executable statements − these are the statements, which initiate actions.

These statements can call a method or function, loop or branch through blocks of code, or assign values or expressions to a variable or constant.

In the last case, it is called an Assignment statement.

An executable statement performs an action. Statements calling a procedure, branching to another place in the code, looping through several statements, or evaluating an expression are executable statements.

An assignment statement is a special case of an executable statement.

We can define more than one condition to be evaluated by the program with statements.

If the defined condition is true, the statement or block executes according to the condition, and if the condition is false, another statement is executed.

Decision Control Statements in VB.net

The following figure shows a common format of the decision control statements to validate and execute a statement:

vb.net control statement condition
vb.net control statement condition

The above diagram shows that if the defined condition is true, statement 1 will be executed, and if the condition is false, statement 2 will be executed.

Decision-Making Statements in VB.net

VB.NET provides the following conditional or decision-making statements.

If-Then Statement

The If-Then Statement is a control statement that defines one or more conditions, and if the particular condition is satisfied, it executes a piece of information or statements.

Syntax:

'syntax for if-then statement'

If condition Then  
[Statement or block of Statement]  
End If  

In If-Then Statement, the condition can be a Boolean, logical, or relational condition, and the statement can be a single or group of statements that will be executed when the condition is true.

Example 1: Write a simple program to print a statement in VB.NET.

Module Module1  
    ' Declaration of variable str '
    Dim str As String = "IT SOURCECODE"  
    Sub Main()  
        ' if str equal to "IT SOURCECODE", below Statement will be executed.'
        If str = "IT SOURCECODE" Then  
            Console.WriteLine("Welcome to the IT SOURCECODE")  
        End If  
    Console.WriteLine("press any key to exit?")  
    Console.ReadKey()  
    End Sub  
End Module 

When the above code is compiled and executed, it produces the following result:

Welcome to the IT SOURCECODE
press any key to exit?

You can test the above example here! ➡ VB.net Online Compiler

Example 2: Write a program to print a number that is greater than another number in VB.NET.

Module if_statement2  
    Sub Main()  
        'Definition of variables' 
        Dim no1, no2 As Integer  
        Console.WriteLine("Enter any two number:")  
        no1 = Console.ReadLine() 'read no1 from user'  
        no2 = Console.ReadLine() 'read no2 from user'  
        If no1 > no2 Then  
            Console.WriteLine("First number is greater than second number")  
        End If  
        If no1 < no2 Then  
            Console.WriteLine("Second number is greater than First number")  
        End If  
        Console.WriteLine("press any key to exit...")  
        Console.ReadKey()   
End Sub  
End Module

When the above code is compiled and executed, it produces the following result:

Enter any two number:
10
27
First number is greater than second number
press any key to exit…

In the above program, we enter two numbers to find the greater number using the relational operator.

If the first number is greater than the other, the first statement is executed; otherwise, the second statement will be executed.

You can test the above example here! ➡ VB.net Online Compiler

If-Then-Else Statement

The If-Then Statement can execute single or multiple statements when the condition is true, but when the expression evaluates to false, it does nothing.

So, here comes the If-Then-Else Statement. The IF-Then-Else Statement tells what the If condition does when the statement is false, it executes the Else statement.

Following is the If-Then-Else statement syntax in VB.NET as follows:

'syntax for if-then-else statement'

If (Boolean_expression) Then  
'This statement will execute if the Boolean condition is true ' 
Else  
'Optional statement will execute if the Boolean condition is false'  
End If  

Flow Chart:

If Then Else Statement in vb.net
If Then Else Statement in vb.net

The above diagram represents that if the Boolean expression (condition) is true, the if statement will execute, and if the Boolean expression is false, the Else code or statement will be executed.

After that, the control transfers to the next statement.

Example 1: Write a program to check whether the number is even or odd.

Module If_Else_statement  
    Sub Main()  
        Dim num As Integer  
        Console.WriteLine("Enter the Number")  
        num = Console.ReadLine() 'read data from console  
  
        If (num Mod 2 = 0) Then ' if condition is true, print the if statement  
            Console.WriteLine("It is an even number")  
  
        Else 'otherwise, Else statement is executed.  
            Console.WriteLine("It is an odd number")  
        End If  
  
    Console.WriteLine("press any key to exit...")  
        Console.ReadKey()  
    End Sub  
End Module 

When the above code is compiled and executed, it produces the following result:

Enter the Number
5
It is an odd number
press any key to exit…

You can test the above example here! ➡ VB.net Online Compiler

Example 2: Write a program to print the larger and smaller of the two numbers.

Module if_else_statement2  
    Sub Main()  
        Dim a As Integer  
        Dim b As Integer  
        Console.WriteLine("Enter the first number : ")  
        a = Console.ReadLine()  
  
        Console.WriteLine("Enter the second number : ")  
        b = Console.ReadLine()  
  
        If a > b Then  
            Console.WriteLine(" larger number = {0} and smaller number = {1} ", a, b)  
        Else  
            Console.WriteLine(" larger number = {0} and smaller number = {1} ", b, a)  
        End If  
  
        Console.WriteLine("press any key to exit...")  
        Console.ReadKey()  
    End Sub  
End Module  

When the above code is compiled and executed, it produces the following result:

Enter the first number :
5
Enter the second number :
7
larger number = 7 and smaller number = 5
press any key to exit…

You can test the above example here! ➡ VB.net Online Compiler

If-Then ElseIf Statement

The If-Then-ElseIf Statement provides a choice to execute only one condition or statement from multiple statements.

Execution starts from the top to bottom, and it checks for each If condition. And if the condition is met, the block of If the statement is executed.

If none of the conditions are true, the last block is executed.

Following is the syntax of If-Then-ElseIf Statement in VB.NET as follows:

'syntax for if-then-elseif statement'

If(condition 1)Then  
   ' Executes when condition 1 is true   
ElseIf( condition 2)Then  
   ' Executes when condition 2 is true   
ElseIf( boolean_expression 3)Then  
   ' Executes when the condition 3 is true   
Else   
   ' executes the default statement when none of the above conditions is true.   
End If  

Flow Chart:

The following diagram represents the functioning of the If-Else-If Statement in the VB.NET programming language.

If Then Else IF Statement in VB.net
If Then Else IF Statement in VB.net

If this condition is true in the flowchart of the if-else-if statement, the statement is executed within the if block.

If the condition is not true, it passes control to the next ElseIf condition to check whether the condition is matched.

And if none of the conditions are matched, the else block is executed.

Example 1: Write a program to show the uses of If… ElseIf statements.

Module if_elseIf  
    Sub Main()  
        Dim var1 As Integer  
  
        Console.WriteLine(" Input the value of var1: ")  
        var1 = Console.ReadLine()  
        If var1 = 20 Then  
            'if condition is true then print the following statement'  
            Console.WriteLine(" Entered value is equal to 20")  
        ElseIf var1 < 50 Then  
            Console.WriteLine(" Entered value is less than 50")  
          
         ElseIf var1 >= 100 Then  
            Console.WriteLine(" Entered value is greater than 100")  
        Else  
            'if none of the above condition is satisfied, print the following statement  
            Console.WriteLine(" Value is not matched with above condition")  
        End If  
        Console.WriteLine(" You have entered : {0}", var1)  
        Console.WriteLine(" press any key to exit...")  
        Console.ReadKey()  
    End Sub  
End Module

When the above code is compiled and executed, it produces the following result:

Input the value of var1:
20
Entered value is equal to 20
You have entered : 20
press any key to exit…

You can test the above example here! ➡ VB.net Online Compiler

Example 2: Write a program to use the If-Then-ElseIf Statement for calculating the division obtained by the student.

Also, take the marks obtained by the student in 5 different subjects from the keyboard.

Module If_elseIf2    
    Sub Main()      ' execution start from Main() method  
        Dim m1, m2, m3, m4, m5, per As Integer  
        Console.WriteLine("Enter marks in five subjects ")  
        ' Read the marks of five subject  
        m1 = Console.ReadLine()  
        m2 = Console.ReadLine()  
        m3 = Console.ReadLine()  
        m4 = Console.ReadLine()  
        m5 = Console.ReadLine()  
        per = (m1 + m2 + m3 + m4 + m5) / 5  
        If (per >= 70) Then  
            'if condition is true, print the first division  
            Console.WriteLine(" First division")  
        ElseIf (per >= 60) Then  
            'if ElseIf condition is true, print the second division  
            Console.WriteLine(" Second division")  
        ElseIf (per >= 50) Then  
            'if ElseIf condition is true, print the third division  
            Console.WriteLine(" Third division")  
        ElseIf (per >= 40) Then  
            'if ElseIf condition is true, print only pass with grace   
            Console.WriteLine(" Only Pass with Grace")  
        Else  
            'if none of the condition is true, print the Failed  
            Console.WriteLine(" Failed")  
        End If  
        Console.WriteLine("press any key to exit...")  
        Console.ReadKey()  
    End Sub  
  
End Module  

When the above code is compiled and executed, it produces the following result:

Enter marks in five subjects
90
87
88
95
80
First division
press any key to exit…

You can test the above example here! ➡ VB.net Online Compiler

Select Case Statement

The Select Case Statement in VB.NET is a collection of multiple case statements, which allows the execution of a single case statement from the list of statements.

A selected case statement uses a variable to test for equality against multiple cases or statements in a program.

If the variable is matched with any test cases, that statement will be executed. If the condition is not matched with any cases, it executes the default statement.

Using the select case statement in VB.NET programming, you can replace the uses of multiple If-Then-Else If statements from the program for better readability and ease of use.

Syntax:

The following is the syntax of the Select Case statement in VB.NET:

Select Case [variable or expression]  
Case value1 'defines the item or value that you want to match.  
// Define a statement to execute  
  
Case value2 'defines the item or value that you want to match.  
// Define a statement to execute  
  
Case Else  
// Define the default statement if none of the conditions is true.  
End Select  

Furthermore, you can also set more than one condition in a single case statement, such as:

Select Case Variable / expression  
Case value1  
Statement1  
  
Case value2, value3  
Statement2  
  
Case Else  
// define the default statement if none of the condition is true  
End Select   

Flowchart of Select Case Statement

The following flowchart represents the functioning of the Select case statement in the VB.NET programming language.

Select Case Statement in VB.net
Select Case Statement in VB.net

In the Flowchart, the Select Case statement represents the evaluation of the process starting from top to bottom.

If the expression or value is matched with the first select case, statement -1 is executed else the control transfers to the next case for checking whether the expression matches or not.

Similarly, it checks all Select case statements for evaluation. If none of the cases are matched, the Else block statement will be executed, and finally, the Select Case Statement will come to an end.

Example 1: Write a program to display the day’s name using the select case statement in VB.NET.

Imports System  
Module Select_case  
    Sub Main()  
        'define a local variable.   
        Dim Days As String  
        Days = "Thurs"  
        Select Case Days  
            Case "Mon"  
                Console.WriteLine(" Today is Monday")  
            Case "Tue"  
                Console.WriteLine(" Today is Tuesday")  
            Case "Wed"  
                Console.WriteLine("Today is Wednesday")  
            Case "Thurs"  
                Console.WriteLine("Today is Thursday")  
            Case "Fri"  
                Console.WriteLine("Today is Friday")  
            Case "Sat"  
                Console.WriteLine("Today is Saturday")  
            Case "Sun"  
                Console.WriteLine("Today is Sunday")  
            Case Else  
                Console.WriteLine(" You have typed Something wrong")  
  
        End Select  
        Console.WriteLine("You have selected : {0}", Days)  
        Console.WriteLine("Press any key to exit...")  
        Console.ReadLine()  
    End Sub  
End Module  

When the above code is compiled and executed, it produces the following result:

Today is Thursday
You have selected : Thurs
Press any key to exit…

You can test the above example here! ➡ VB.net Online Compiler

In the select case statement, the value of Days “Thurs” will compare all the available select cases‘ values in a program.

If a value matches with any condition, it prints the particular statement, and if the value is not matched with any select case statement, it prints the default message.

Example 2: Write a program to perform an arithmetic operation using the Select case statement in VB.NET.

Imports System  
Module Operation  
    Sub main()  
        'declaration of the variables  
        Dim num1, num2, sum As Integer  
        Dim def As Char  
        'initialization of num1 and num2 variable  
        num1 = 2  
        num2 = 6  
        Console.WriteLine(" Want to perform any operation?")  
        Console.WriteLine(" A for Addition")  
        Console.WriteLine(" S for Subtraction")  
        Console.WriteLine(" M for Multiplication")  
        Console.WriteLine(" D for Division")  
        Console.WriteLine(" Please enter any input")  
        def = Console.ReadLine()  
        Select Case def  
            Case "A"  
                'perform Addition  
                sum = num1 + num2  
                Console.WriteLine(" Addition of two number is :{0}", sum)  
            Case "S"  
                'perform Subtraction  
                sum = num2 - num1  
                Console.WriteLine(" Subtraction of two number is :{0}", sum)  
            Case "M"  
                'perform Multiplication  
                sum = num1 * num2  
                Console.WriteLine(" Multiplication of two number is :{0}", sum)  
            Case "D"  
                'Peform Division  
                sum = num2 / num1  
                Console.WriteLine(" Division of two number is :{0}", sum)  
            Case Else  
                'If none of the operation matched, call default statement  
                Console.WriteLine(" Please enter only define operation With Capital letter")  
        End Select  
        Console.WriteLine("Press any key to exit...")  
        Console.ReadKey()  
    End Sub  
End Module

When the above code is compiled and executed, it produces the following result:

Want to perform any operation?
A for Addition
S for Subtraction
M for Multiplication
D for Division
Please enter any input
M
Multiplication of two number is :12
Press any key to exit…

You can test the above example here! ➡ VB.net Online Compiler

In the above example, we defined Select with multiple case statements, and if the user-defined input is matched with any defined case statement, it executes that statement.

If the condition is not matched with any case, it executes a default statement in VB.NET.

Here, we provide ‘M‘ as input, which checks all case statements, and if any case is matched with M, it executes the statement within the respective Case statement.

Nested Select Case Statements

When a Select Case statement is written inside the body of another Select Case statement is called a nested Select Case statement.

Syntax:

Select Case "num"  
' code to be executed if num = 1  
Case 1  
' nested Select case  
     Select Case n  
          
                                 ' code to be executed if n = 5  
                                  Case 5  
                                 Statement 1  
                                  
                                ' code to be executed if n = 10  
                                 Case 10  
                                 Statement 2  
                                   
                                  ' code to be executed if n = 15  
                                  Case 15  
                                 Statement 3  
  
                               ' code to be executed if n doesn't match with any cases.  
                               Case Else  
                                Statement  
  
           ' code to be executed if num = 2  
            Case 2  
            Statement 2  
             
            ' code to be executed if num = 3  
            Case 3  
           Statement 3  
             
            ' code to be executed if num doesn't match with any cases.  
            Case Else  
           Statement  

Example 1: Write a program to use a nested select case statement in VB.NET.

Module Module1  
  
    Sub Main()  
  
        Dim x As Integer = 10, y As Integer = 5  
        Select Case x  
  
            Case 10  
                Console.WriteLine("X Value: 10")  
  
  
                Select Case y  
                    Case 5  
                        Console.WriteLine("Nested Switch Value: 5")  
  
   
                        Select Case y - 2  
                            Case 3  
                                Console.WriteLine("Another Nested Switch Value: 3")  
  
                        End Select  
                End Select  
   
            Case 15  
                Console.WriteLine("X Value: 15")  
  
            Case 20  
                Console.WriteLine("X Value: 20")  
  
            Case Else  
                Console.WriteLine("Not Known")  
  
        End Select  
        Console.WriteLine("Press Enter Key to Exit..")  
        Console.ReadLine()  
    End Sub  
End Module  

When the above code is compiled and executed, it produces the following result:

X Value: 10
Nested Switch Value: 5
Another Nested Switch Value: 3
Press Enter Key to Exit..

You can test the above example here! ➡ VB.net Online Compiler

Example 2: Write a program to use the nested select case statement in VB.NET.

Imports System  
Module nested_selectcase  
    Sub Main()  
        Dim num As Integer  
        Dim str As String  
        str = "F"  
  
        Console.WriteLine(" Enter only First three number like 1, 2, 3")  
        num = Console.ReadLine() 'take input from the user  
        Select Case num  
            Case 1  
                Console.WriteLine(" You are in block 1")  
                Console.WriteLine("Only First two letter such as A and B")  
  
                str = Console.ReadLine()  
                Select Case str  
                    Case "A", "a"  
                        Console.WriteLine(" This is a VB.NET Tutorial")  
                    Case "B", "b"  
                        Console.WriteLine(" Welcome to the IT SOURCECODE")  
                    Case Else  
                        Console.WriteLine(" Something is wrong")  
                End Select  
  
            Case 2  
                Console.WriteLine(" You are in block 2")  
                Console.WriteLine("Only First two letter such as C and D")  
                str = Console.ReadLine()  
                Select Case str  
                    Case "C", "c"  
                        Console.WriteLine(" Welcome to the Programming World!")  
                    Case "D", "d"  
                        Console.WriteLine(" Want to go in Heaven")  
                    Case Else  
                        Console.WriteLine(" Something is wrong")  
                End Select  
  
            Case 3  
                Console.WriteLine(" You are in block 3")  
                Console.WriteLine("Only First two letter such as E and F")  
                str = Console.ReadLine()  
                Select Case str  
                    Case "E", "e"  
                        Console.WriteLine(" VB.NET is a programming language to develop web, window, and console-based application. ")  
                    Case "F", "f"  
                        Console.WriteLine(" You have to basic knowledge of c and c++")  
                    Case Else  
                        Console.WriteLine(" Something is wrong")  
                End Select  
            Case Else  
                Console.WriteLine(" Something is wrong")  
        End Select  
        Console.ReadLine()  
    End Sub  
End Module

When the above code is compiled and executed, it produces the following result:

Enter only First three number like 1, 2, 3
1
You are in block 1
Only First two letter such as A and B
B
Welcome to the IT SOURCECODE

You can test the above example here! ➡ VB.net Online Compiler

In the above example, we have only defined the first three numbers 1-3 and if the number matches any case statement, the select statement is executed.

Here, we have entered 1 that is matched with case 1 and it executes a block as shown above.

This block executes the statement “Only the First two letters such as A and B“.

Therefore, we enter a letter B, letter B is matched with the nested select case statement, and if a match is found, it executes the select case statement as shown above.

Conclusion

The article explains control statements in VB.NET, which help control a program’s execution based on specified conditions.

It covers declaration statements for defining variables, constants, procedures, and more, and executable statements that initiate actions.

The article delves into decision control statements like If-Then, If-Then-Else, If-Then ElseIf, and Select Case statements, providing syntax and examples for each.

It also illustrates nested select case statements and concludes by summarizing the concepts covered in the article.





Leave a Comment