0% found this document useful (0 votes)
21 views11 pages

CH 2

Uploaded by

menber988
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)
21 views11 pages

CH 2

Uploaded by

menber988
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/ 11

Chapter 2

Type Example

3. Language Fundamentals in Visual Basic .Net

3.1 What are Data Types?

Data types determine the type of data that any variable can store. Data types are a broad
mechanism for declaring variables or functions of various types. A variable's type dictates how much
storage space it takes up and how the bit pattern recorded is interpreted. Variables belonging to
different data types are allocated different amounts of space in the memory. There are
various data types in VB.NET. They include:

 Boolean: the allocated storage depends on the platform of implementation. Its


value can be either True or False.
 Byte: allocated storage space of 1 byte. Values range from 0 to 255 (unsigned).
 Char: allocated a space of 2 bytes. Values range from 0 to 65535 (unsigned).
 Date: allocated storage space of 8 bytes.
 Integer: has a storage space of 4 bytes. Values range between -2,147,483,648
to 2,147,483,647 (signed).
 Long: has a storage space of 8 bytes. Numbers range from -
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807(signed).
 String: The storage space allocated depends on the platform of implementation.
Values range from 0 to about 2 billion Unicode characters.

3.2 Variables in VB.NET

 A variable is simply the name provided to a storage location that the programs can access. Each
variable in VB.Net has a unique type, which governs the size and layout of the variable's
memory, the range of values that may be stored inside that memory, and the set of operations that
can be performed on the variable.

 Data kinds have already been covered. The basic value types given by VB.Net are classified as follows:
Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong and Char

Floating-point types Single and Double

Decimal types Decimal

Boolean types True or False values, as assigned

Date types Date

Variable Declaration
 Declaration of a variable involves giving the variable a name and defining the data type
to which it belongs.
 We use the following syntax:
 Dim Variable_Name as Data_Type
 Here is an example of a valid variable declaration in VB.NET:
 Dim x As Integer
 In the above example, ‘x’ is the variable name while Integer is the data type to which
variable x belongs.

Visual Basic naming rules

 Use the following rules when you name procedures, constants, variables, and arguments
in a Visual Basic module:
 You must use a letter as the first character.
 You can't use a space, period (.), exclamation mark (!), or the characters @, &, $,
# in the name.
 Name can't exceed 255 characters in length.
 Generally, you shouldn't use any names that are the same as the
 function,
 statement,
 method, and intrinsic constant names used in Visual Basic or by the host
application.
 You can't repeat names within the same level of scope.
 For example, you can't declare two variables named age within the same
procedure. However, you can declare a private variable named age and a
procedure-level variable named age within the same module.

Note

 Visual Basic isn't case-sensitive, but it preserves the capitalization in the statement
where the name is declared.
Variable Initialization
 Initializing a variable means assigning a value to the variable. Examples
1. Dim x AsInteger
x = 10
‘or accepting from user
Console. WriteLine (“Please enter integer value”)
x= Console.ReadLine
2. Dim name AsString
name = "Haftom"
or
Console. WriteLine (“Please enter your name”)
name = Console.ReadLine()

3. Dim checker As Boolean


checker = True
VB.Net Constants
Constants are fixed values that are not changed during the execution of the program. These fixed values
are also referred to as literals.

Constants can be of any basic data kinds, such as integers, characters, floating points, or string literals.
Enumeration constants are also available.

Constants are processed similarly to regular variables, except that their values cannot be changed after
they are defined.

Example
Const pi AsSingle = 3.14
OR
Const x = 10

Console. WriteLine ("the value of the constant is:"& pi)


Console.ReadLine()

Summary

 Each variable must belong to a data type. The data type determines the amount
of memory space allocated to the variable.
 We can convert a variable from one data type to another.
 Initializing variables means assigning values to the variables.
 We create a console application to help us get input from the users via the
console using the ReadLine function.
 And use WriteLine () Function to display values and results.

3.3 Control Flow

a program proceeds through its statements from beginning to end. Some very simple programs
can be written with only this unidirectional flow. However, much of the power and utility of any
programming language comes from the ability to change execution order with control statements
and loops.
Control structures allow you to regulate the flow of your program's execution. Using control
structures, you can write Visual Basic code that makes decisions or that repeats actions.
Decision making structures require that the programmer specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and
optionally, other statements to be executed if the condition is determined to be
false.

3.3.1Control Statements

VB.Net
provides the Statement Description
following
types of If ... Then An If...Then statement consists of a boolean
decision-
making statement expression followed by one or more statements.
statements.
Click the If...Then...Else An If...Then statement can be followed by an
following
links to statement optional Else statement, which executes when the
check their boolean expression is false.
details.
nested If You can use one If or Else if statement inside
statements another If or Else if statement(s).

Select Case A Select Case statement allows a variable to be tested


statement for equality against a list of values.

nested Select You can use one select case statement inside
Case another select case statement(s).
statements
1. If Else Condition

Syntax
If condition Then
[Statement(s)]
End If

'Example Write a program that checks if the two values are the same,
' if they are the same it displays true else false
ModuleModule1

Sub Main()
Dim x, y AsString
x = Console.ReadLine
y = Console.ReadLine
If x = y Then
Console.WriteLine("True")
Console.ReadLine()
Else
Console.WriteLine("False")
Console.ReadLine()
EndIf

EndSub

EndModule
Example 2

2. Select Case

A Select Case statement allows a variable to be tested for equality against a list
of values. Each value is called a case, and the variable being switched on is
checked for each select case.
Syntax

The syntax for a Select Case statement in VB.Net is as follows −


Select [ Case ] expression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select

Where,

 expression − is an expression that must evaluate to any of the elementary


data type in VB.Net, i.e., Boolean, Byte, Char, Date, Double, Decimal,
Integer, Long, Object,.

 expressionlist − List of expression clauses representing match values


for expression. Multiple expression clauses are separated by commas.

 statements − statements following Case that run if the select expression


matches any clause in expressionlist.

 elsestatements − statements following Case Else that run if the select


expression does not match any clause in the expressionlist of any of the
Case statements.
Example:

ModuleModule1
Dim def AsChar
Console.WriteLine(" Please enter any input")
def = Console.ReadLine()
Select def
Case"c"

Console.WriteLine(" Computer Science")


Case"S"

Console.WriteLine("Information Technology ")


EndSelect
End sub

3.3.2 loops
Visual Basic loop structures allow you to run one or more lines of code repetitively. You can
repeat the statements in a loop structure until a condition is True, until a condition is False, a
specified number of times, or once for each element in a collection.

There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −
VB.Net provides following types of loops to handle looping requirements. Click the following
links to check their details.

The following illustration shows a loop structure that runs a set of statements until a condition
becomes true:

Loop Type Description

Do Loop It repeats the enclosed block of statements while a Boolean condition is


True or until the condition becomes True. It could be terminated at any
time with the Exit Do statement.

For...Next It repeats a group of statements a specified number of times and a loop


index counts the number of loop iterations as the loop executes.

For Each...Next It repeats a group of statements for each element in a collection. This
loop is used for accessing and manipulating all elements in an array or a
VB.Net collection.
While... End While It executes a series of statements as long as a given condition is True.

Control Statement Description

Exit statement Terminates the loop or select case statement and transfers execution to
the statement immediately following the loop or select case.

Continue statement Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.

GoTo statement Transfers control to the labeled statement. Though it is not advised to
use GoTo statement in your program.

Examples :

1. Write a Vb.net Program that display 10-20 using for, while and do loops

Console.WriteLine("diplay Using Do loop")


Do
Console.WriteLine("=>"& b)
b = b + 1
LoopUntil (b = 21)
'==============================================

Console.WriteLine("diplay Using For loop")


For a = 10 To 20
Console.WriteLine("=>"& a)
Next
'=================================================

Console.WriteLine("diplay Using while loop")


While (b <= 20)
Console.WriteLine("=>"& b)
b = b + 1
EndWhile

2. Write a Vb.net Program that display 10-20 except 15 using for, while and do loops

Sub Main()
Dim a AsInteger = 10
Do
If (a = 15) Then
' skip the iteration '
a = a + 1
Continue Do
EndIf
Console.WriteLine("value of a: {0}", a)
a = a + 1
LoopWhile (a < 20)
Console.ReadLine()
EndSub
Example 2
'Define the While Loop Condition
Whilei< 20

Ifi = 15 Then
Console.WriteLine(" you Skipped {0}", i)
i += 1 ' skip the define iteration
Continue While
EndIf
Console.WriteLine(" Value of i is {0}", i)
i += 1 ' Update the variable i by 1
EndWhile
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()

3.2Methods and Their Types

We can create the Methods either by using Sub or Function keywords like as shown below. If we
create a method with Sub keyword that will not allow us to return any value. If you want to return any
value, you need to use Function keyword to create the method.

Syntax
<Access_Specifier> Sub Method_Name(<Parameters>)
// Statements to Execute
End Sub

Or

<Access_Specifier> Function Method_Name(<Parameters>) As <Return_Type>


// Statements to Execute
Return return_val
End Function
Example

ModuleModule1

Sub Main()
Dim result AsString = GetUserDetails("Haftom", 31)
Console.WriteLine(result)
GetDetails()
Console.ReadLine()
EndSub
PublicSubGetDetails()
Console.WriteLine("this is Using SUB Key word")
EndSub
PublicFunctionGetUserDetails(ByVal name AsString, ByVal age AsInteger)
AsString
Dim info AsString = String.Format("Name: {0}, Age: {1}", name, age)
Return info
EndFunction
EndModule

3.5 Events

Events are basically a user action like key press, clicks, mouse movements, etc., or some
occurrence like system generated notifications. Applications need to respond to events when they
occur.
Clicking on a button, or entering some text in a text box, or clicking on a menu item, all are
examples of events. An event is an action that calls a function or may cause another event. Event
handlers are functions that tell how to respond to an event.
VB.Net is an event-driven language. There are mainly two types of events −
 Mouse events
 This event gets triggered when the pointer of the mouse enters the
control.

 Keyboard events
 These are the events that are triggered when the events are fired upon
any action done on the keyboard. This includes actions such as
keypress, keydown, enter, etc. Let us study some of the keyboard-
based events in detail.

3.5 Classes and Objects


When you define a class, you're essentially creating a blueprint for a data type. This does not
describe any data, but it does define what the class name signifies, that is, what a class object will
consist of and what operations may be performed on such an object.

You might also like