0% found this document useful (0 votes)
4 views48 pages

Data Types, Operators, Constants, Variables

The document provides an overview of data types in VB.Net, categorizing them into numeric and non-numeric types, with examples such as Boolean, Char, Date, Double, Integer, and String. It also discusses operators in VB.Net, including arithmetic, comparison, logical, and bitwise operators, as well as the setup of the VB.Net environment using Visual Studio. Additionally, it covers the process of creating a VB.Net program, including variable declaration, identifiers, and the importance of comments in programming.

Uploaded by

kimmaurice4
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)
4 views48 pages

Data Types, Operators, Constants, Variables

The document provides an overview of data types in VB.Net, categorizing them into numeric and non-numeric types, with examples such as Boolean, Char, Date, Double, Integer, and String. It also discusses operators in VB.Net, including arithmetic, comparison, logical, and bitwise operators, as well as the setup of the VB.Net environment using Visual Studio. Additionally, it covers the process of creating a VB.Net program, including variable declaration, identifiers, and the importance of comments in programming.

Uploaded by

kimmaurice4
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/ 48

SIT 103

Data Types in VB.Net


Introduction
• In any operation we interact with various types of data raging from
people’s names, dates, currencies, figures etc.
• In computing these types of data are categorized into categories known as data
types.
• Data types therefore refer to an extensive system used for declaring
variables or functions of different types.
• The type of a variable determines how much space it occupies in storage and how
the bit pattern stored is interpreted.
• Visual basic.net supports multiple data types. They are categorized into
either numeric or non-numeric data types.
• Numeric data types are those which contain figures while non-numeric contain
characters. The most commonly used data types include;
Commonly Used Datatypes in VB.Net
1. Boolean
• Holds values that can be only True or False. i.e binary condition.
• The keywords True and False correspond to the two states of Boolean
variables.
2. Char
• Holds unsigned 16-bit (2-byte) code points ranging in value from 0 through
65535. Each code point, or character code, represents a single Unicode
character.
• Use the Char data type when you need to hold only a single character and
do not need the overhead of String. E.g “A”
• In some cases you can use Char(), in an array of Char elements, to hold multiple
characters such as in passwords. E.g {“mut2022!@”}
Cont.
3. Date
• Use the Date data type to contain date values, time values, or date and
time values.
• You must enclose a Date literal within number signs (# #). You must specify
the date value in the format M/d/yyyy, for example #5/31/1993#, or yyyy-
MM-dd, for example #1993-5-31#.
• You can use slashes when specifying the year first. This requirement is independent
of your locale and your computer's date and time format settings.
4. Double
• The Double data type provides the largest and smallest possible
magnitudes for a number. It also handles decimal values. E.g 10.5 , 10.0
Cont.
5. Integer
• Stores whole numbers. It provides optimal performance on a 32-bit
processor. The other integral types are slower to load and store from and
to memory. E.g 10
6. String
• Use the String data type to hold multiple characters without the array
management overhead of Char(), in an array of Char elements. E.g names
like “Murang’a”
• String also supports alphanumeric characters. For example your
registration number has a combination of alphabets, special characters,
and numbers. E.g “SC232/5456/2030”
Cont.
• Others that are not commonly used include:
• Byte
• Long
• Short
• Sbyte
• Single
• Most of them function similar to the 6 most commonly used
datatypes with the only difference being the range of value that each
dataset can support.
Visual Basic Operators
Introduction
• Operators are special symbols that are used to perform specific types of
operations. Operators perform a very special role as they make
computation and operations easier.
• The number of operators used in any VB program are purely dependent on
what the program is expected to do.
• In programming the elements that appear on either side of the operator
are known as operands.
• E.g A+B: A and B are operands while as + is an operator.
• For example:
• A simple program to output your name may just use a few operators while Control
structures have the propensity to use a huge combination of operators to achieve
their objective.
Types of Operators in VB.Net
• Arithmetic Operators
• Comparison Operators
• Logical/Bitwise Operators.
• Bit Shift Operators.
• Assignment Operators.
Arithmetic Operators Operators Meaning Example

^ Raises one operand to the power of another x ^ y (x to the power y)

• Arithmetic operators + Adds two operands x+y


are used for – Subtracts second operand from the first x–y
performing
mathematical * Multiplies both operands x*y

operations like / Divides one operand by another and returns x/y


addition, subtraction,
a floating-point result
division, multiplication,
etc. \ Divides one operand by another and returns x\y

an integer result

MOD Modulus Operator and the remainder of a x MOD y (remainder of

result after an integer division x/y)


Comparison Operators Operators Meaning Example

= Equality Check -Returns True if both x == y

• Comparison values are the same


operators are
basically used to <> Non-Equality Returns True if both values x < > y
compare different
are unequal
values.
• These operators > Greater than Check-Returns true if the x>y
normally return
Boolean values first value specified is greater than the
either True or False
depending upon the second
condition.
< Less than-Returns true if the first value x<yx

specified is less than second


Comparison Operators Cont.
>= Checks for two conditions, If the first value is greater than or equal >= y

to the second value it returns true

<= Checks for two conditions, If the first value is less than or equal to x <= y

the second value it returns true

Is Compares two Object Variable for Reference, True If the same

object reference

IsNot Compares two Object Variable for Reference, False If the same

object reference

Like compares a string against a pattern.


Operators Example Equivalent to
Assignment Operators:
= x=4 x=4

• Assignment += x += 4 x=x+4
operators are used
for assigning values -= x -= 4 x=x–4
to variables in
VB.NET. *= x *= 4 x=x*4

/= x /= 4 x=x/4

\= x \= 4 x=x\4

^= x ^= 4 x=x^4
Logical operators Operators Meaning Example

And Returns True If both the operands are true x And y

• Used while Does not perform short-circuiting, i.e., it


implementing logic in
evaluates both the expressions
VB.Net programs
• They are known as Or Returns True If any of the two operands are x Or y
bitwise operators
true. It does not perform short-circuiting.
• Xor stands for
Exclusive or Not If True, then this operator will make it false.

Xor It returns False if both expressions are True or a Xor b


both expressions are False; otherwise, it returns

True. It does not perform short-circuiting


Logical Operators Cont.
AndAlso Logical AND operator. Works only on x AndAlso y

Boolean data. Performs short-circuiting.

OrElse Logical OR operator. Works only on Boolean x OrElse y

data. Performs short-circuiting.

IsFalse Determines whether an expression is False

IsTrue Determines whether an expression is True


Bit Shift operators
• They are used to perform shift operations on binary level or values.
They perform bit by bit operation. They include:
✓>>: Shifts binary bits to the right by the number of times specified by
operand. Example x>>3 will shift bits three steps to the right
✓<<: Shifts binary bits to the left by the number of times specified by
operand. Example x>>3 will shift bits three steps to the left
✓And: The Binary AND Operator is used to copy the common binary bit
in the result if the bit exists in both operands.
Cont.
✓Or: The Binary OR Operator is used to copy a common binary bit in
the result if the bit is found in either operand.
✓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.
✓XOR: The Binary XOR Operator in VB.NET, used to determine whether
a bit is available to copy in one operand instead of both.
Writing VB.Net Program
VB.Net Environment Setup
• Environment set-up refers to installing the appropriate tools needed
to code/ program in visual basic language.
• The most important tool that is needed is an integrated development
environment (IDE).
• An IDE is a comprehensive software that contains built-in tools to
enable a programmer to code and run programs. The main built-in
tools of an IDE include;
• A code editor for writing codes
• A debugger for checking errors
• A compiler or interpreter for converting source code to machine code
• Visual studio IDE is the most preferred IDE in coding visual basic.net
Cont.
• Download Visual Studio IDE and install it in your computer.
• There are various variants of Visual Studio IDE
• Community version (free)
• Professional version (proprietary)
• Enterprise version (proprietary)
• While installing visual studio it will install .Net to your computer. In
some cases it may need admin privileges make sure to grant it.
• Visual Studio is memory intensive, therefore, if you computer has a
RAM of less than 4GB its advisable that when using Visual Studio you
close other heavy software applications.
Types of VB.net Programs
• There are various types of programs that can be written in VB.net.
there include; console applications, windows form applications, class
library, windows library, windows control library, windows services,
net website.
• In this course, we will look at the console applications and windows
form applications although our main focus is on windows form
applications.
• A console application has no Graphical User Interface (G.U.I) while a
windows form application has a graphical user interface.
Process of Creating your first VB.net Program
• Open visual studio, click file , new, new project
• A window with three partitions will appear.
• On the left most column select Visual Basic
• In the middle column select console app (.Net core)
• At the bottom of this window you are provided with fields in which
you set the name of your project and location where you want it to
be saved.
• Ensure that in the framework combo box/ dropdown you have
selected the .net framework. Then click okay and the editor will open.
Cont.
Imports System • By default the program on the
Module Program left will be displayed.
Sub Main(args As String()) • If you run this program it will
output “hello world” in
Console.WriteLine("Hello command prompt then the
World!") display will disappear.
End Sub • To prevent that display from
End Module disappearing add this line of
code before end sub.
• Console.ReadKey()
The new modified program
Imports System
Module Program
Sub Main(args As String())
Console.WriteLine("Hello World!")
Console.ReadKey()
End Sub
End Module
Deciphering/Dissecting the program
• The first line of the program Imports System is used to include the System
namespace in the program.
• The next line has a Module declaration, the module Module1.
• VB.Net is completely object oriented, so every program must contain a module of a class that
contains the data and procedures that your program uses.
• Classes or Modules generally would contain more than one procedure.
• Procedures contain the executable code, or in other words, they define the
behavior of the class.
• A procedure could be any of the following: Function, Sub, Operator, Get, Set, AddHandler,
RemoveHandler, RaiseEvent
• The next line defines the Main procedure, which is the entry point for all VB.Net
programs.
• The Main procedure states what the module or class will do when executed.
Cont.
• The Main procedure specifies its behavior with the statement
Console.WriteLine ("Hello World")
• WriteLine is a method of the Console class defined in the System
namespace.
• This statement causes the message "Hello, World!" to be displayed on the
screen.
• The last line Console.ReadKey() will prevent the screen from running
and closing quickly when the program is launched from Visual Studio
.NET.
• End sub shows the end of the sub-module/end of the main method
while end module shows the end of the entire module.
A VB.Net program to output “Welcome to SIT
103”
Imports System
Module Program
Sub Main(args As String())
Console.WriteLine("Welcome to SIT 103!")
Console.ReadKey()
End Sub
End Module
Adding Comments/ Internal Documentation
• Comments in any programming language are statements that are not
executable.
• Their main purpose is to help programmers to explain what certain
parts of a program or lines of code are doing.
• Different programming languages have their own ways of declaring
comments. Example C, C++, and Java use // for single line comments
and /*..*/ for multiline comments. Python uses # to define
comments.
• VB.net uses and apostrophe ‘ to depict a comment as shown below
Example of comments in a VB.Net program
Imports System
Module Program
Sub Main(args As String())
'this program will output Welcome to SIT 103
Console.WriteLine("Welcome to SIT 103!")
Console.ReadKey()
End Sub
End Module
Exercise
• Write a VB program to output your name
• Write a VB program to output the names of three of your friends in
separate lines. Add at least one comment
• Discuss the importance of comments in a program
IDENTIFIERS IN VISUAL
BASIC.NET
Introduction
• In VB programming, identifiers are names given to VB entities, such as
variables, constants, functions, structures etc.
• All identifiers adhere to certain conventions of naming them.
• The rules of naming identifiers include the following:
• It must be less than 255 characters
• No spacing is allowed
• It must not begin with a number
• Period is not permitted
• Cannot use exclamation mark (!), or the characters @, &, $, #
• Cannot repeat names within the same level of scope.
Variables in VB.Net
• A variable is nothing but a name given to a storage area that our
programs can manipulate. Each variable in VB.Net has a specific type,
which determines;
• The size and layout of the variable's memory.
• The range of values that can be stored within that memory
• The set of operations that can be applied to the variable.
• Categories of Variables in Visual Basic.net
• Global variables- they are variables that are not confined to any specific
procedure, thus they can be used anywhere in the program after they have
been declared.
• Local variables- they are declared within a procedure and can only be used
within that procedure.
Cont.
• Examples of valid and invalid variable names

Valid Name Invalid Name


My_Car My.Car
This_year 1NewBoy
He&HisFather *
Long_Name_Can_beUSE
& is not acceptable
Declaring Variables Explicitly
• This refers to assigning names and data type to variables. In Visual Basic, it
is a good practice to declare the variables before using them.
• They are normally declared in the general section of the codes' windows
using the Dim statement.
• Dim stands for the dimension in which the variable is being declared. You should
choose a datatype that fits the kind of data you want your variable to store.
• The syntax is as follows:
• Dim VariableName As DataType
• Examples;
• Dim Student_Name As String
• Dim Price AS Double
Cont.
• If you want to declare more variables, you can declare them in
separate lines or you may also combine more in one line, separating
each variable with a comma, as follows:
• Dim VariableName1 As DataType1, VariableName2 As DataType2,Vari
ableName3 As DataType3
• Example:
• Dim Student_Name As String, Dim price AS Double
• its good programming practice to always declare all the variables you
desire to use.
Cont.
• For string declaration, there are two possible types, one for the
variable-length string and another for the fixed-length string.
• For the variable-length string, just use the same format as example above.
However, for the fixed-length string, you have to use the syntax as shown
below:
• Dim VariableName as String * n
• Where n defines the number of characters the string can hold.
• For example,
• Dim yourName as String * 10
• *yourName can holds no more than 10 Characters.
Scope of Declaration
• Other than using the Dim keyword to declare the data, you can also use
other keywords to declare the data. Three other keywords are private,
static and public. The forms are as shown below:
• Private VariableName as Datatype
• Static VariableName as Datatype
• Public VariableName as Datatype
• The above keywords indicate the scope of the declaration.
• Private declares a local variable or a variable that is local to a procedure or
module.
• However, Private is rarely used, we normally use Dim to declare a local
variable.
Cont.
• The Static keyword declares a variable that is being used multiple
times, even after a procedure has been terminated.
• Most variables created inside a procedure are discarded by Visual
Basic when the procedure is finished, static keyword preserves the
value of a variable even after the procedure is terminated.
• Public is the keyword that declares a global variable, which means it
can be used by all the procedures and modules of the whole program.
Initializing variables
• This refers to assigning values to a variable. There are various
approaches that can be used to initialize variables.
1. Declaring variables then initializing later
2. Declaring variables and initializing them at the same time.
Approach 1
Imports System
Module Program
Sub Main(args As String())
Dim number As Integer
number = 10
Console.WriteLine(number)
Console.ReadKey()
End Sub
End Module
Approach 2
Imports System
Module Program
Sub Main(args As String())
Dim number As Integer = 10
Console.WriteLine(number)
Console.ReadKey()
End Sub
End Module
A simple VB.Net program to add two numbers
Imports System • In this program we have
Module Program declared three variables
namely;
Sub Main(args As String()) • number1-to store the value of
Dim number1 As Integer = 10 the first number
Dim number2 As Integer = 5 • number2- to store the value of
Dim sum As Integer= number1+number2 the second number.
Console.WriteLine(sum) • Sum-to store the results
obtained after adding the two
Console.ReadKey() numbers
End Sub • Then we output sum.
End Module
Program to find the average of Three Numbers
Imports System Console.WriteLine(average)
Module Program Console.ReadKey()
Sub Main(args As String()) End Sub
Dim number1 As Integer = 10 End Module
Dim number2 As Integer = 7
Dim number3 As Integer = 11
Dim average As Double =
(number1 + number2 + number3)
/3
Constants in VB.Net
• Constant refers to a fixed value that cannot be changed during the
execution of a program.
• Constants are also known as literals. They can be of any data type,
such as Integer, Double, String, Decimal, Single, character, etc.
• The constants are treated just like regular variables except that their
values cannot be modified after their definition.
• In VB.NET, const is a keyword that is used to declare a variable as
constant.
• Syntax: Const constname As datatype = value
Example of Declaring Constants in a Program
• Think of a program that is Imports System
supposed to find the area Module Program
of a circle.
Sub Main(args As String())
• In any case pie will
always be 22/7 or 3.142. Const pie As Double = 3.142
• So here we declare our Dim radius As Integer = 10
pie as a constant since it Dim area As Double = pie * (radius * radius)
is never expected to Console.WriteLine(area)
change.
• The radius may change Console.ReadKey()
but pie can never change End Sub
End Module
Exercise
• Write a VB.Net console application that can be used to compute
marks for a student using the following formula.
Total_marks=(CAT1+CAT2+CAT3+Assignment)/3+Final Examination
• Write a VB.Net program that can be used to find the surface area of
Cylinder whose Diameter is 14cm and height is 25cm use the formula

• Write a VB.Net program to find the area of a sphere whose radius is


18cm use the formula
The End

You might also like