0% found this document useful (0 votes)
96 views32 pages

Cpprog1 - Chapter 4 PDF

This document discusses operators and control statements in VB.NET programming. It covers different types of operators like arithmetic, comparison, logical and bitwise operators. It provides examples of using various arithmetic operators like addition, subtraction, multiplication etc. and comparison operators like equal, not equal, greater than, less than etc. It demonstrates the usage of these operators with code examples and output. The objective is to understand operators and conditional statements used in VB.NET and create programs to test conditions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views32 pages

Cpprog1 - Chapter 4 PDF

This document discusses operators and control statements in VB.NET programming. It covers different types of operators like arithmetic, comparison, logical and bitwise operators. It provides examples of using various arithmetic operators like addition, subtraction, multiplication etc. and comparison operators like equal, not equal, greater than, less than etc. It demonstrates the usage of these operators with code examples and output. The objective is to understand operators and conditional statements used in VB.NET and create programs to test conditions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

MODULE INTRO TO VB.

NET PROGRAMMING– CPPROG1

CHAPTER 4: VB.NET OPERATORS AND CONTROL


STATEMENTS

Objectives:
a.) Discuss the VB.Net operators.
b.) Differentiate the types of conditional statements that is being
used in VB.Net.
c.) Create a program that will test and verify the conditions in a
program.

Lesson 1: VB.NET Operators


In VB.NET programming, the Operator is a symbol that is used to perform various
operations on variables. VB.NET has different types of Operators that help in performing logical
and mathematical operations on data values. The Operator precedence is used to determine the
execution order of different Operators in the VB.NET programming language.
What is VB.NET Operator?
In VB.NET, operator is a special symbol that tells the compiler to perform the specific logical or
mathematical operation on the data values. The data value itself (which can be either a variable
or a constant) is called an operand, and the Operator performs various operations on the
operand.
For example: In the expression,
3+2-1
The symbol + and - are the Operators, and the 3, 2, and 1 are operands.
Different Types of VB.NET Operators

Following are the different types of Operators available in VB.NET:


o Arithmetic Operators
o Comparison Operators
o Logical and Bitwise Operators
o Bit Shift Operators
o Assignment Operators
o Concatenation Operators
o Miscellaneous Operators

Page | 1
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

Arithmetic Operators
The Arithmetic Operators in VB.NET, used to perform mathematical operations such
as subtraction, addition, multiplication, division, etc. on the operands in VB.NET. These are as
follows:
Arithmetic Operators in VB.NET

Operators Description Example

^ It is an exponentiation Operator that is used to raises one operand Y ^ X (X to


to the power of another operand. the
power Y)

+ The addition Operator is used to add numeric data, as well as X+Y


concatenate two string variables.

- It is a subtraction Operator, which is used to subtract the second X-Y


operand from the first operand.

* The multiplication Operator is used to multiply the operands X*Y

/ It is a division Operator used to divide one operand by another X/Y


operand and returns a floating-point result.

\ It is an integer division Operator, which is similar to division X\Y


Operator, except that it returns an integer result while dividing one
operand to another operand.

Mod It is a modulo (Modulus) Operator, which is used to divide two X Mod Y


operands and returns only a remainder.
Example of Arithmetic Operators in VB.NET:

Arithmetic_Operator.vb
1. Imports System
2. Module Arithmetic_Operator
3. Sub Main()
4. 'Declare a, b And c as integer Data Type()
5. Dim a, b, c As Integer
6. Dim d As Single
7. a = 17
8. b=4

Page | 2
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

9. ' Use of + Operator


10. c=a+b
11. Console.WriteLine(" Sum of a + b is {0}", c)
12.
13. 'Use of - Operator
14. c=a-b
15. Console.WriteLine(" Subtraction of a - b is {0}", c)
16.
17. 'Use of * Operator
18. c=a*b
19. Console.WriteLine(" Multiplication of a * b is {0}", c)
20.
21. 'Use of / Operator
22. d=a/b
23. Console.WriteLine(" Division of a / b is {0}", d)
24.
25. 'Use of \ Operator
26. c=a\b
27. Console.WriteLine(" Similar to division Operator (return only integer value) of a - b i
s {0}", c)
28.
29. 'Use of Mod Operator
30. c = a Mod b
31. Console.WriteLine(" Modulus of a Mod b is {0}", c)
32.
33. 'Use of ^ Operator
34. c=a^b
35. Console.WriteLine(" Power of a ^ b is {0}", c)
36. Console.WriteLine("Press any key to exit...")
37. Console.ReadKey()
38. End Sub
39. End Module
Now compile and execute the above program, by pressing the F5 button or Start button from the
Visual Studio; then it shows the following result:

Page | 3
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

Comparison Operators
As the name suggests, the Comparison Operator is used to compare the value of two variables
or operands for the various condition such as greater, less than or equal, etc. and returns a
Boolean value either true or false based on the condition.

Operator Description Example

= It checks whether the value of the two operands is equal; (A = B)


If yes, it returns a true value, otherwise it shows False.

<> It is a Non-Equality Operator that checks whether the (A <> B), check Non-
value of the two operands is not equal; it returns true; Equality
otherwise, it shows false.

> A greater than symbol or Operator is used to determine (A > B); if yes, TRUE,
whether the value of the left operand is greater than the Else FALSE
value of the right operand; If the condition is true, it
returns TRUE; otherwise, it shows FALSE value.

< It is a less than symbol which checks whether the value (A < B); if the
of the left operand is less than the value of the right condition is true,
operand; If the condition is true, it returns TRUE; returns TRUE else
otherwise, it shows FALSE value. FALSE

>= It is greater than equal to which checks two conditions A >= B


whether the first operand is greater than or equal to the
second operand; if yes, it returns TRUE; otherwise, it
shows False.

<= This symbol represents less than equal to which A <= B


determines the first operand is less than or equal to the
second operand, and if the condition is true, it returns
TRUE; otherwise, it shows FALSE.

Is The Is Operator is used to validate whether the two result = obj1 Is obj2
objects reference the same variable or object; If the test
is true, it returns True; otherwise, the result is False. In
short, it checks the equality of the objects. An Is Operator
is also used to determine whether the object refers to a
valid object.

Page | 4
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

IsNot The IsNot Operator is similar to Is Operator, except that Result = obj1 IsNot
the two object references the different object; if yes, the obj2
result is True; otherwise, the result is False.

Like The Like Operator is used to check the pattern expression result = string Like
of string variable; And if the pattern matched, the result the pattern, the
is True; otherwise, it returns False. pattern represents
the series of
characters used by
Like Operator.
Example of Comparison Operators in VB.NET
Comparison_Operator.vb

1. Imports System
2. Module Comparison_Operator
3. Sub Main()
4. 'declaration of Integer, Object and String Data Type variables
5. Dim x As Integer = 5
6. Dim y As Integer = 10
7. Dim Result, obj, obj2 As Object
8. Dim str, str2 As String
9. str = "Apple12345"
10. str2 = "Apple12345"
11. obj = 10
12. obj2 = 20
13.
14. Console.WriteLine(" Program of Comparison Operator")
15. 'Use of > Operator
16. Console.WriteLine(" Output of x > y is {0}", x > y)
17.
18. 'Use of < Operator
19. Console.WriteLine(" Output of x < y is {0}", x < y)
20.
21. 'Use of = Operator
22. Console.WriteLine(" Output of x = y is {0}", x = y)
23.
24. 'Use of <> Operator
25. Console.WriteLine(" Output of x <> y is {0}", x <> y)
26.
27. 'Use of >= Operator

Page | 5
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

28. Console.WriteLine(" Output of x >= y is {0}", x >= y)


29.
30. 'Use of <= Operator
31. Console.WriteLine(" Output of x <= y is {0}", x <= y)
32.
33. 'Use of Is Operator
34. Result = obj Is obj2
35. Console.WriteLine(" Output of obj Is obj2 is {0}", Result)
36.
37. 'Use of Is Operator
38. Result = obj IsNot obj2
39. Console.WriteLine(" Output of obj IsNot obj2 is {0}", Result)
40.
41. 'Use of Like Operator
42. Result = str Like str2
43. Console.WriteLine(" Output of str Like str2 is {0}", Result)
44.
45. Console.WriteLine(" Press any key to exit...")
46. Console.ReadKey()
47. End Sub
48. End Module
Now compile and execute the above code by pressing the F5 button or Start button in Visual
studio, it returns the following output:

Logical and Bitwise Operators


The logical and bitwise Operators work with Boolean (true or false) conditions, and if the
conditions become true, it returns a Boolean value. The following are the logical and bitwise
Operators used to perform the various logical operations such as And, Or, Not, etc. on the
operands (variables). Suppose there are two operand A and B, where A is True, and B is False.

Page | 6
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

Operator Description Example

And The And Operator represents, whether both the operands are true; (A And B),
the result is True. result =
False

Or It is an Or Operator that returns a true value; if anyone operand is (A Or B),


true from both the operands. result =
True

Not The Not Operator is used to reverse the logical condition. For Not A
example, if the operand's logic is True, it reveres the condition and Or
makes it False. Not(A And
B) is True

Xor It is an Exclusive OR Operator that represents, whether both the A Xor B is


expression is true or false, the result is True; otherwise, the result is True
False.

AndAlso It is a logical AND Operator that performs short-circuit operation on A AndAlso


the variables, and if both the operands are true, the result is True B = False
else the result is False.

OrElse It is a logical OR Operator that perform short-circuit operation on A OrElse B


Boolean data. If anyone of the operand is true, the result is True else = True
the result is False.

IsFalse The IsFalse Operator is used to determine whether an expression is


False.

IsTrue The IsTrue Operator is used to determine whether an expression is


True.
Example of Logical and Bitwise Operator:
Logic_Bitwise.vb
1. Imports System
2. Module Logic_Bitwise
3. Sub Main()
4. Dim A As Boolean = True
5. Dim B As Boolean = False
6. Dim c, d As Integer

Page | 7
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

7. c = 10
8. d = 20
9.
10. 'Use of And Operator
11. If A And B Then
12. Console.WriteLine(" Operands A And B are True")
13. End If
14.
15. 'Use of Or Operator
16. If A Or B Then
17. Console.WriteLine(" Operands A Or B are True")
18. End If
19.
20. 'Use of Xor Operator
21. If A Xor B Then
22. Console.WriteLine(" Operands A Xor B is True")
23. End If
24.
25. 'Use of And Operator
26. If c And d Then
27. Console.WriteLine(" Operands c And d is True")
28. End If
29.
30. 'Use of Or Operator
31. If c Or d Then
32. Console.WriteLine(" Operands c Or d is True")
33. End If
34.
35. 'Use of AndAlso Operator
36. If A AndAlso B Then
37. Console.WriteLine(" Operand A AndAlso B is True")
38. End If
39.
40. 'Use of OrElse Operator
41. If A OrElse B Then
42. Console.WriteLine(" Operand A OrElse B is True")
43. End If
44.
45. 'Use of Not Operator
46. If Not (A And B) Then
47. Console.WriteLine(" Output of Not (A And B) is True")
Page | 8
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

48. End If
49.
50. Console.WriteLine(" Press any key to exit?")
51. Console.ReadKey()
52. End Sub
53. End Module
Now compile and execute the above code by pressing the F5 button or Start button in Visual
studio, it returns the following output:

Bit Shift Operators


The Bit Shit Operators are used to perform the bit shift operations on binary values either to the
right or to the left.
Bit Shift operations in VB.NET

Operator Description

AND The Binary AND Operator are used to copy the common binary bit in the result if
the bit exists in both operands.

OR The Binary OR Operator is used to copy a common binary bit in the result if the
bit found in either operand.

XOR The Binary XOR Operator in VB.NET, used to determine whether a bit is available
to copy in one operand instead of both.

Not The binary NOT Operator is also known as the binary Ones' Compliment
Operator, which is used to flip binary bits. This means it converts the bits from 0
to 1 or 1 to 0 binary bits.

<< The Binary Left Shift Operator is used to shift the bit to the left side.

>> The Binary Right Shift Operator is used to shift the bit to the right side.

Page | 9
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

Example of Bit Shift Operator in VB.NET:


BitShift_Operator.vb
1. Imports System
2. Module Bitshift_Operator
3. Sub Main()
4. Dim x, y, z As Integer
5. x = 12
6. y = 25
7. Dim a, b As Double
8. a = 5 ' a = 5(00000101)
9. b = 9 ' b = 9(00001001)
10.
11. ' Use of And Operator
12. z = x And y
13. Console.WriteLine(" BitShift Operator x And y is {0}", z)
14.
15. 'Use of Or Operator
16. z = x Or y
17. Console.WriteLine(" BitShift Operator x Or y is {0}", z)
18.
19. z = x Xor y
20. Console.WriteLine(" BitShift Operator x Xor y is {0}", z)
21.
22. z = Not y
23. Console.WriteLine(" BitShift Operator Not y is {0}", z)
24.
25. 'Use of << Left-Shift Operator
26. ' Output is 00001010
27. Console.WriteLine(" Bitwise Left Shift Operator - a<<1 = {0}", a << 1)
28.
29. 'Output is 00010010
30. Console.WriteLine(" Bitwise Left Shift Operator - b<<1 = {0}", b << 1)
31.
32. 'Use of >> Right-Shift Operator
33. 'Output is 00000010
34. Console.WriteLine(" Bitwise Right Shift Operator - a>>1 = {0}", a << 1)
35.
36. 'Output is 00000100
37. Console.WriteLine(" Bitwise Right Shift Operator - b>>1 = {0}", a << 1)
38.
Page | 10
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

39. Console.WriteLine(" Press any key to exit...")


40. Console.ReadKey()
41. End Sub
42. End Module
Now compile and execute the above code by pressing the F5 button or Start button in Visual
studio, it returns the following output:

Assignment Operators

The Assignment Operators are used to assign the value to variables in VB.NET.
Assignment Operators in VB.NET

Operator Description Example

= It is a simple assignment Operator used to assign a right- X = 5, X assign a value


side operand or value to a left side operand. 5
X = P + Q, (P + Q)
variables or value
assign to X.

+= An Add AND assignment Operator is used to add the X += 5, which means


value of the right operand to the left operand. And the X= X+5 ( 5 will add and
result is assigned to the left operand. assign to X and then
result saved to Left X
operand)

-= It is a Subtract AND assignment Operator, which X -= P, which is same as


subtracts the right operand or value from the left X=X-P
operand. And then, the result will be assigned to the left
operand.

*= It is a Multiply AND assignment Operator, which X *= P, which is same


multiplies the right operand or value with the left as X = X - P

Page | 11
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

operand. And then, the result will be assigned to the left


operand.

/= It is a Divide AND assignment Operator, which divides X /= P, which is same


the left operand or value with the right operand. And as X = X - P
then, the result will be assigned to the left operand (in
floating-point).

\= It is a Divide AND assignment Operator, which divides X \= P, which is same


the left operand or value with the right operand. And as X = X - P
then, the result will be assigned to the left operand (in
integer-point division).

^= It is an expression AND assignment Operator, which X ^= P, which is same


raises the left operand or value to the right operand's as X = X ^ P
power. And then, the result will be assigned to the left
operand.

&= It is a concatenate string assignment Operator used to Str &= name, which is
bind the right-hand string or variable with the left-hand same as Str = Str &
string or variable. And then, the result will be assigned name
to the left operand.
Example of Assignment Operator in VB.NET:

Assign_Operator.vb
1. Imports System
2. Module Assign_Operator
3. Sub Main()
4. 'Declare variable and b As Integer
5. Dim A As Integer = 5
6. Dim B As Integer
7. Dim Str, name As String
8. name = "come"
9. Str = "Wel"
10.
11. 'Use of = Operator
12. B=A
13. Console.WriteLine(" Assign value A to B is {0}", B)
14.
15. 'Use of += Operator

Page | 12
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

16. B += A
17. Console.WriteLine(" Output of B += A is {0}", B)
18.
19. 'Use of -= Operator
20. B -= A
21. Console.WriteLine(" Output of B -= A is {0}", B)
22.
23. 'Use of *= Operator
24. B *= A
25. Console.WriteLine(" Output of B *= A is {0}", B)
26.
27. 'Use of /= Operator
28. B /= A
29. Console.WriteLine(" Output of B /= A is {0}", B)
30.
31. 'Use of = Operator
32. B \= A
33. Console.WriteLine(" Output of B \= A is {0}", B)
34.
35. 'Use of ^= Operator
36. B ^= A
37. Console.WriteLine(" Output of B ^= A is {0}", B)
38.
39. 'Use of &= Operator
40. Str &= name
41. Console.WriteLine(" Output of Str &= name is {0}", Str)
42.
43. Console.WriteLine(" Press any key to exit...")
44. Console.ReadKey()
45. End Sub
46. End Module
Now compile and execute the above code by pressing the F5 button or Start button in Visual
studio, it returns the following output:

Page | 13
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

Concatenation Operators
In VB.NET, there are two concatenation Operators to bind the operands:

Operator Description Example

& It is an ampersand symbol that is used to bind two or more operand Result =
together. Furthermore, a nonstring operand can also be Wel &
concatenated with a string variable ( but in that case, Option Strict is come,
on). Result =
Welcome

+ It is also used to add or concatenate two number or string. Result =


Wel +
come,
Result =
Welcome
Example of Concatenation Operators in VB.NET.

MyProgram.vb
1. Imports System
2. Module MyProgram
3. Sub Main()
4. Dim str As String = "Wel"
5. Dim str2 As String = "come"
6. Dim str3 As String = " "
7. Dim str4 As String = "to JavatPoint"
8. Dim result As String
9. Dim result2 As String
10. result = str & str2
11. Console.WriteLine(" Result = str & str2 gives = {0}", result)
12. result2 = str + str2 + str3 + str4
13. Console.WriteLine(" Result = str + str2 + str3 +str4 gives = {0}", result2.ToString)
14. Console.ReadLine()
15. End Sub
16. End Module
Now compile and execute the above code by pressing the F5 button or Start button in Visual
studio, it returns the following output:

Page | 14
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

Miscellaneous Operators

There are some important Operator in VB.NET

Operator Description Example

Await An Await Operator is used in an operand Dim output as out = Await


to suspend the execution of an AsyncMethodThatReturnsResult()
asynchronous method or lambda Await AsyncMethod()
expression until the awaited task
completes.

AddressOf The AddressOf Operator is used to provide AddHandler Button2.Click,


a reference to the address of a procedure. AddressOf Button2_Click

GetType A GetType Operator is used to retrieve the MsgBox(GetType(String).ToString())


type of the specified object. In addition,
the retrieved object type provides various
information such as methods, properties,
and events.

Function It defines the lambda expression, which Dim mul2 = Function(num As


Expression declares the parameter and code. A Integer) num * 4
Lambda expression is a function that is Console.WriteLine(mul2(4))
used to calculate and return value without
defining the name.

If The If Operator using short circuit Dim a = -4


evaluation to conditionally return a single Console.WriteLine(If (a >= 0,
object value from two defined object "Positive", "Negative"))
values. The If Operator can be used with
two or three defined arguments.

Page | 15
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

Example of Miscellaneous Operators in VB.NET.


Misc_Operator.vb
1. Imports System
2. Module Misc_Operator
3. Sub Main()
4. ' Initialize a variable
5. Dim a As Integer = 50
6. ' GetType of the Defined Type
7. Console.WriteLine(GetType(Double).ToString())
8. Console.WriteLine(GetType(Integer).ToString())
9. Console.WriteLine(GetType(String).ToString())
10. Console.WriteLine(GetType(Single).ToString())
11. Console.WriteLine(GetType(Decimal).ToString())
12.
13. 'Use of Function()
14. Dim multiplywith10 = Function(sum As Integer) sum * 10
15. Console.WriteLine(multiplywith10(10))
16. Console.WriteLine(If(a >= 0, "Negative", "Positive"))
17.
18. Console.WriteLine(" Press any key to exit...")
19. Console.ReadLine()
20.
21. End Sub
22. End Module
Now compile and execute the above code by pressing the F5 button or Start button in Visual
studio, it returns the following output:

Operator Precedence in VB.NET

Operator precedence is used to determine the order in which different Operators in a complex
expression are evaluated. There are distinct levels of precedence, and an Operator may belong

Page | 16
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

to one of the levels. The Operators at a higher level of precedence are evaluated first. Operators
of similar precedents are evaluated at either the left-to-right or the right-to-left level.
The Following table shows the operations, Operators and their precedence -

Operations Operators Precedence

Await Highest

Exponential ^

Unary identity and negation +, -

Multiplication and floating-point *, /


division

Integer division \

Modulus arithmetic Mod

Addition and Subtraction +, -

Arithmetic bit shift <<, >>

All comparison Operators =, <>, <, <=, >, >=, Is, IsNot, Like,
TypeOf …is

Negation Not

Conjunction And, AndAlso

Inclusive disjunction Or, Else

Exclusive disjunction Xor Lowest


Example of Operator Precedence in VB.NET.
Operator_Precedence.vb
1. Imports System
2. Module Operator_Precedence
3. Sub Main()
4. 'Declare and Initialize p, q, r, s variables
5. Dim p As Integer = 30
6. Dim q As Integer = 15

Page | 17
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

7. Dim r As Integer = 10
8. Dim s As Integer = 5
9. Dim result As Integer
10.
11. Console.WriteLine("Check Operator Precedence in VB.NET")
12. 'Check Operator Precedence
13. result = (p + q) * r / s ' 45 * 10 / 5
14. Console.WriteLine("Output of (p + q) * r / s is : {0}", result)
15.
16. result = (p + q) * (r / s) ' (45) * (10/5)
17. Console.WriteLine("Output of (p + q) * (r / s) is : {0}", result)
18.
19. result = ((p + q) * r) / s ' (45 * 10 ) / 5
20. Console.WriteLine("Output of ((p + q) * r) / s is : {0}", result)
21.
22. result = p + (q * r) / s ' 30 + (150/5)
23. Console.WriteLine("Output of p + (q * r) / s is : {0}", result)
24.
25. result = ((p + q * r) / s) ' ((30 + 150) /5)
26. Console.WriteLine("Output of ((p + q * r) / s) is : {0}", result)
27.
28. Console.WriteLine(" Press any key to exit...")
29. Console.ReadKey()
30. End Sub
31. End Module
Now compile and execute the above code by pressing the F5 button or Start button in Visual
studio, it returns the following output:

For more knowledge about operators, please check the link provided;
https://www.youtube.com/watch?v=5-
zYdoUBYf8&list=PLsJBMeqEdtggJi2khGAjgnQ3ssgzWw_uz&index=4

Page | 18
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

Lesson 2: VB.NET Control Statements


In VB.NET, the control statements are the statements that controls 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 statement is executed. In the control
statement, we will use if- Then, if Then Else, if Then ElseIf and the Select case 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.
The following figure shows a common format of the decision control statements to validate and
execute a statement:

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.
VB.NET provides the following conditional or decision-making statements.

o If-Then Statement
o If-Then Else Statement
o If-Then ElseIf Statement
o Select Case Statement
o Nested Select Case Statements

Page | 19
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

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:
1. If condition Then

2. [Statement or block of Statement]


3. End If
In If-Then Statement, the condition can be a Boolean, logical, or relational condition, and the
statement can be 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.
Module1.vb

1. Module Module1
2. ' Declaration of variable str
3. Dim str As String = "JavaTpoint"
4. Sub Main()
5. ' if str equal to "JavaTpoint", below Statement will be executed.
6. If str = "JavaTpoint" Then
7. Console.WriteLine("Welcome to the JavaTpoint")
8. End If
9. Console.WritLine("press any key to exit?")
10. Console.ReadKey()
11. End Sub
12. End Module
Now compile and execute the above program by clicking on the Start or F5 button, it shows the
following output:

As we can see in the above example, if the value of str is equal to JavaTpoint, the condition
is true, and it prints the Statement.

Page | 20
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

Example 2: Write a program to print a number is greater than another number in VB.NET.
if_statment2.vb
1. Module if_statement2
2. Sub Main()
3. ?Definition of variables
4. Dim no1, no2 As Integer
5. Console.WriteLine("Enter any two number:")
6. no1 = Console.ReadLine() ?read no1 from user
7. no2 = Console.ReadLine() ?read no2 from user
8. If no1 > no2 Then
9. Console.WriteLine("First number is greater than second number")
10. End If
11. If no1 < no2 Then
12. Console.WriteLine("Second number is greater than First number")
13. End If
14. Console.WriteLine("press any key to exit...")
15. Console.ReadKey()
16. End Sub
17. End Module
Now compile and execute the above program by clicking on the Start or F5 button, it shows the
following output:

In the above program, we enter two numbers to find the greater number using the relational
operator. And if the first number is greater than the other, the first statement is executed;
otherwise, the second statement will be executed.
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 is telling what If condition to do when if the
statement is false, it executes the Else statement. Following is the If-Then-Else statement syntax
in VB.NET as follows:

Page | 21
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

Syntax:
1. If (Boolean_expression) Then
2. 'This statement will execute if the Boolean condition is true
3. Else
4. 'Optional statement will execute if the Boolean condition is false
5. End If
Flow chart

The above diagram represents that if the Boolean expression (condition) is true, the if statement
will execute, and if the Boolean expression is false, Else code or statement will be executed. After
that, the control transfer to the next statement, which is immediately after the If-Then-Else
control statement.
Example 1: Write a program to check whether the number is even or odd.

If_Else_statment.vb
1. Module If_Else_statement
2. Sub Main()
3. Dim num As Integer
4. Console.WriteLine("Enter the Number")
5. num = Console.ReadLine() 'read data from console
6.
7. If (num Mod 2 = 0) Then ' if condition is true, print the if statement
8. Console.WriteLine("It is an even number")
9.
10. Else 'otherwise, Else statement is executed.

Page | 22
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

11. Console.WriteLine("It is an odd number")


12. End If
13.
14. Console.WriteLine("press any key to exit...")
15. Console.ReadKey()
16. End Sub
17. End Module
Now compile and execute the above program by clicking on the Start or F5 button, it shows the
following output:

Example 2: Write a program to print the larger and smaller of the two numbers.
if_else_statment2.vb
1. Module if_else_statement2
2. Sub Main()
3. Dim a As Integer
4. Dim b As Integer
5. Console.WriteLine("Enter the first number : ")
6. a = Console.ReadLine()
7.
8. Console.WriteLine("Enter the second number : ")
9. b = Console.ReadLine()
10.
11. If a > b Then
12. Console.WriteLine(" larger number = {0} and smaller number = {1} ", a, b)
13. Else
14. Console.WriteLine(" larger number = {0} and smaller number = {1} ", b, a)
15. End If
16.
17. Console.WriteLine("press any key to exit...")
18. Console.ReadKey()
19. End Sub
20. End Module

Page | 23
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

Now compile and execute the above program by clicking on the Start or F5 button, it shows the
following output:

VB.NET 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 checked for each If
condition. And if the condition is met, the block of If the statement is executed. And 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
1. If(condition 1)Then
2. ' Executes when condition 1 is true
3. ElseIf( condition 2)Then

4. ' Executes when condition 2 is true


5. ElseIf( boolean_expression 3)Then
6. ' Executes when the condition 3 is true
7. Else
8. ' executes the default statement when none of the above conditions is true.

9. End If

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

Page | 24
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

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.
if_elseIf.vb
1. Module if_elseIf
2. Sub Main()
3. Dim var1 As Integer
4.
5. Console.WriteLine(" Input the value of var1: ")
6. var1 = Console.ReadLine()
7. If var1 = 20 Then
8. 'if condition is true then print the following statement'
9. Console.WriteLine(" Entered value is equal to 20")
10. ElseIf var1 < 50 Then
11. Console.WriteLine(" Entered value is less than 50")
12.
13. ElseIf var1 >= 100 Then
14. Console.WriteLine(" Entered value is greater than 100")
15. Else
16. 'if none of the above condition is satisfied, print the following statement
17. Console.WriteLine(" Value is not matched with above condition")

Page | 25
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

18. End If
19. Console.WriteLine(" You have entered : {0}", var1)
20. Console.WriteLine(" press any key to exit...")
21. Console.ReadKey()
22. End Sub
23. End Module
Now compile and execute the above program by clicking on the Start or F5 button, it shows the
following output:

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.
if_elseIf2.vb
1. Module If_elseIf2
2. Sub Main() ' execution start from Main() method
3. Dim m1, m2, m3, m4, m5, per As Integer
4. Console.WriteLine("Enter marks in five subjects ")
5. ' Read the marks of five subject
6. m1 = Console.ReadLine()
7. m2 = Console.ReadLine()
8. m3 = Console.ReadLine()
9. m4 = Console.ReadLine()
10. m5 = Console.ReadLine()
11. per = (m1 + m2 + m3 + m4 + m5) / 5
12. If (per >= 70) Then
13. 'if condition is true, print the first division
14. Console.WriteLine(" First division")
15. ElseIf (per >= 60) Then
16. 'if ElseIf condition is true, print the second division
17. Console.WriteLine(" Second division")
18. ElseIf (per >= 50) Then
19. 'if ElseIf condition is true, print the third division

Page | 26
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

20. Console.WriteLine(" Third division")


21. ElseIf (per >= 40) Then
22. 'if ElseIf condition is true, print only pass with grace
23. Console.WriteLine(" Only Pass with Grace")
24. Else
25. 'if none of the condition is true, print the Failed
26. Console.WriteLine(" Failed")
27. End If
28. Console.WriteLine("press any key to exit...")
29. Console.ReadKey()
30. End Sub
31.
32. End Module
Now compile and execute the above program by clicking on the Start or F5 button, it shows the
following output:

For more knowledge about IF Then statement, please check the link provided;
https://www.youtube.com/watch?v=MRnlg_V_0BI&list=PLC601DEA22187BBF1&ind
ex=13

Lesson 3: Select Case Statement


In VB.NET, the Select Case statement is a collection of multiple case statements, which allows
executing 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. And if the condition is not matched
with any cases, it executes the default statement.

Page | 27
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

Using the select case statement in VB.NET programming, you can replace the uses of multiple If-
Then-Else If statement from the program for better readability and easy to use.
Syntax
Following is the syntax of the Select Case statement in VB.NET, as follows:
1. Select Case [variable or expression]

2. Case value1 'defines the item or value that you want to match.
3. // Define a statement to execute
4.
5. Case value2 'defines the item or value that you want to match.
6. // Define a statement to execute

7.
8. Case Else
9. // Define the default statement if none of the conditions is true.
10. End Select
Furthermore, you can also set more than one condition in a single case statement, such as:

1. Select Case Variable / expression


2. Case value1
3. Statement1
4.
5. Case value2, value3

6. Statement2
7.
8. Case Else
9. // define the default statement if none of the condition is true
10. End Select

Flowchart of Select Case Statement


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

Page | 28
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

In Flowchart, the Select Case statement represents the evaluating of the process start from top
to bottom. If the expression or value is matched with the first select case, statement -1 is
executed else the control transfer to the next case for checking whether the expression is
matching or not. Similarly, it checks all Select case statements for evaluating. 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 Days name using the select case statement in VB.NET.
Select_case.vb
1. Imports System
2. Module Select_case
3. Sub Main()
4. 'define a local variable.
5. Dim Days As String
6. Days = "Thurs"
7. Select Case Days
8. Case "Mon"
9. Console.WriteLine(" Today is Monday")
10. Case "Tue"
11. Console.WriteLine(" Today is Tuesday")

Page | 29
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

12. Case "Wed"


13. Console.WriteLine("Today is Wednesday")
14. Case "Thurs"
15. Console.WriteLine("Today is Thursday")
16. Case "Fri"
17. Console.WriteLine("Today is Friday")
18. Case "Sat"
19. Console.WriteLine("Today is Saturday")
20. Case "Sun"
21. Console.WriteLine("Today is Sunday")
22. Case Else
23. Console.WriteLine(" You have typed Something wrong")
24.
25. End Select
26. Console.WriteLine("You have selected : {0}", Days)
27. Console.WriteLine("Press any key to exit...")
28. Console.ReadLine()
29. End Sub
30. End Module
Now compile and execute the above program by clicking on the Start or F5 button, it shows the
following output:

In the select case statement, the value of Days "Thurs" will compare all the available select cases'
values in a program. If a value matched 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.

Operation.vb
Operation.vb
1. Imports System
2. Module Operation
3. Sub main()

Page | 30
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

4. 'declaration of the variables


5. Dim num1, num2, sum As Integer
6. Dim def As Char
7. 'initialization of num1 and num2 variable
8. num1 = 2
9. num2 = 6
10. Console.WriteLine(" Want to perform any operation?")
11. Console.WriteLine(" A for Addition")
12. Console.WriteLine(" S for Subtraction")
13. Console.WriteLine(" M for Multiplication")
14. Console.WriteLine(" D for Division")
15. Console.WriteLine(" Please enter any input")
16. def = Console.ReadLine()
17. Select Case def
18. Case "A"
19. 'perform Addition
20. sum = num1 + num2
21. Console.WriteLine(" Addition of two number is :{0}", sum)
22. Case "S"
23. 'perform Subtraction
24. sum = num2 - num1
25. Console.WriteLine(" Subtraction of two number is :{0}", sum)
26. Case "M"
27. 'perform Multiplication
28. sum = num1 * num2
29. Console.WriteLine(" Multiplication of two number is :{0}", sum)
30. Case "D"
31. 'Peform Division
32. sum = num2 / num1
33. Console.WriteLine(" Division of two number is :{0}", sum)
34. Case Else
35. 'If none of the operation matched, call default statement
36. Console.WriteLine(" Please enter only define operation With Capital letter")
37. End Select
38. Console.WriteLine("Press any key to exit...")
39. Console.ReadKey()
40. End Sub
41. End Module
Now compile and execute the above program by clicking on the Start or F5 button, it shows the
following output:

Page | 31
MODULE INTRO TO VB.NET PROGRAMMING– CPPROG1

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. And 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.

For more knowledge about select case statement, please check the link provided;
https://www.youtube.com/watch?v=3wvvD4Vfr4k&list=PLC601DEA22187BBF1&inde
x=24

REFERENCES

https://www.javatpoint.com/vb-net-operators

https://www.javatpoint.com/vb-net-control-statements

Page | 32

You might also like