Arithmetic Operators in Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

This lesson describes the Arithmetic operators in Visual Basic

An arithmetic operator is a code element that performs some operation on one or more values and creates a result. Those values are called operands. For example, in the next statement, the operator is * (multiplication), the operands are A and B while the result is assigned to the variable C:

                        C = A * B
                    

Here we have a table that lists the most used arithmetic operators provided by Visual Basic:

OPERATOR PURPOSE EXAMPLE RESULT
+ Addition 2 + 2 4
- Substraction 4 - 2 2
- Negation 1 operand* - 2 -2
* Multiplication 2 * 2 4
/ Division 4 / 2 2
\ Integer Division 9 \ 2 4
^ Exponentiation 2 ^ 3 2 * 2 * 2 = 8
Mod Modulus 4 Mod 2 0

Most of you are already familiar with these except maybe Modulus and Integer Division that may need a little more explanation:

As shown in the table, \ operator performs integer division and returns the result of dividing the first operand by the second, dropping any remainder.
It's very important to understand that the result is truncated toward zero, not rounded.

The Mod operator returns the remainder after dividing the operand by the second one e.g. 5 Mod 2 = 1 because 5 = 2 * 2 + 1

The following example code prints all even numbers in range 1 to 10:

                        For i As Integer = 1 To 10
                            If i Mod 2 = 0 Then
                                Console.WriteLine(i) ' an even number
                            Else
                                ' we do nothing as the number is odd
                            End If
                        Next
                    


Share This

Home | About | Contact | Privacy Policy

Copyright visual-basic-tutorials.com 2017 - All Rights Reserved.