Vb language2
-
Upload
getamesay-berihun -
Category
Documents
-
view
225 -
download
5
description
Transcript of Vb language2
Visual Basic Language
Variables
A storage location in memory (RAM) Holds data/information while the program is running These storage locations can be referred to by their
namesEvery variable has three properties:
Name - reference to the location - cannot be changed
Value - the information that is stored - can be changed during program execution, hence the name “variable”
Data Type - the type of information that can be stored - cannot be changed
How to Think About Variables
You the programmer make up a name for the variable
Visual Basic associates that name with a location in the computer's RAM
The value currently associated with the variable is stored in that memory location
You simply use the name you chose when you need to access the value
Data Type
Data type - Specifies type of data variable can store
Integer variables: Long, Integer, Short, Byte Floating-point variables: Single, Double Fixed decimal point variable: Decimal Boolean variables: True, False Character variable: Char Text variable: String The Object variable
Default data type assigned by Visual Basic Can store many different types of data Less efficient than other data types
Visual Basic Data Types
Data type Prefix Size Values
Byte byt 1 byte positive integer value from 0 to 255Short shr 2 byte integer from –32,768 to +32,767Integer int 4 byte integer from +/- 2,147,483,647Long lng 8 byte integer from +/- 9,223,372,036,854,775,807
Singlesng 4 byte single-precision, floating-point number Double dbl 8 byte double-precision, floating-point number Decimal dec 16 byte number with up to 28 significant digits
Char chr 2 byte Any single characterBoolean bln 2 byte True or False
String str (4 byte)Text - Any number/combination of charactersDate dtm8 byte 8 character date: #dd/mm/yyyy#Object obj (4 byte)An address that refers to an object
Variable Names
First character must be a letter or underscore
Must contain only letters, numbers, and underscores (no spaces, periods, etc.)
Can have up to 255 charactersCannot be a VB language keywordNaming Conventions
Should be meaningful Follow 3 char prefix style - 1st 3 letters in
lowercase to indicate the data type After that, capitalize the first letter of each word Example: intTestScore
Declaring a Variable
A variable declaration is a statement that creates a variable in memory
Syntax: Dim VariableName As DataType Dim (short for Dimension) - keyword VariableName - name used to refer to
variable As - keyword DataType - one of many possible
keywords to indicate the type of value the variable will contain
Example: Dim intLength as Integer
Declaring and Initializing a Variable
A starting or initialization value may be specified with the Dim statement
Good practice to set an initial value unless assigning a value prior to using the variable
Syntax: Dim VariableName As DataType = Value Just append " = value” to the Dim
statement= 5 assigning a beginning value to the
variableExample: Dim intLength as Integer = 5
Variable Declaration Rules
Variable MUST be declared prior to the code where they are used
Variable should be declared first in the procedure (style convention)
Declaring an initial value of the variable in the declaration statement is optional
Default Values for Data Types
Data type Default (Initial) value
All numeric types Zero (0)Boolean FalseChar Binary 0String or Object EmptyDate 12:00 a.m. on January
1, 0001
Scope of Variables What – Indicates the part of the program where
the variable can be used When – From the variable declaration until the end
of the code block (procedure, method, etc.) where it is declared Variable cannot be used before it is declared Variable declared within a code block is only visible to
statements within that code block▪ Called Local Variable
Can be declared at the beginning of the class code window (General Declarations section) and be available to all blocks▪ Called Form Level Variable
Variables that share the same scope cannot have the same name (same name ok if different scope)
Lifetime of Variables
What – Indicates the part of the program where the variable exists in memory
When – From the beginning of the code block (procedure, method, etc.) where it is declared until the end of that code block When the code block begins the space is
created to hold the local variables▪ Memory is allocated from the operating system
When the code block ends the local variables are destroyed▪ Memory is given back to the operating system
Performing Calculations with Variables
Arithmetic Operators^ Exponential* Multiplication/ Floating Point Division\ Integer DivisionMOD Modulus (remainder from division)+ Addition– Subtraction& String Concatenation
(putting them together)
Common Arithmetic Operators
Examples of use: decTotal = decPrice + decTax decNetPrice = decPrice - decDiscount dblArea = dblLength * dblWidth sngAverage = sngTotal / intItems dblCube = dblSide ^ 3
Special Modulus Operator
This operator can be used in place of the backslash operator to give the remainder of a division operationintRemainder = 17 MOD 3 ‘result is 2dblRemainder = 17.5 MOD 3 ‘result is 2.5
Any attempt to use of the \ or MOD operator to perform integer division by zero causes a DivideByZeroException runtime error
Concatenating Strings Concatenate: connect strings together Concatenation operator: the ampersand (&) Include a space before and after the &
operator How to concatenate character strings
strFName = “Bob" strLName = "Smith" strName = strFName & " “ “Bob
” strName = strName & strLName
“Bob Smith”
intX = 1 intY = 2 intResult = intX + intY strOutput = intX & “ + “ & intY & “ = “ & intResult
“1 + 2 = 3”
Combined Assignment Operators
Often need to change the value in a variable and assign the result back to that variable
For example: var = var – 5Subtracts 5 from the value stored in var
Operator Usage Equivalent toEffect += x += 2 x = x + 2 Add to-= x -= 5 x = x – 5Subtract from*= x *= 10 x = x * 10 Multiply by/= x /= y x = x / y Divide by\= x \= y x = x \ y Int Divide by&= x &= “.” x = x & “.”Concatenate
Operators Precedence
ParenthesisExponentialMultiplication / DivisionInteger DivisionMODAddition / SubtractionString ConcatenationRelational Operators (< , > , >= , <=
, <>)Logical Operators (AND, OR, NOT)
Precedence Examples
6 * 2 ^ 3 + 4 / 2 = 507 * 4 / 2 – 6 = 85 * (4 + 3) – 15 Mod 2 = 34
intX = 10 intY = 5 intResultA = intX + intY * 5 'iResultA is 35 iResultB = (intX + intY) * 5 'iResultB is 75 dResultA = intX - intY * 5 'dResultA is -15 dResultB = (intX - intY) * 5 'dResultB is 25
Conditionals
If Condition Syntax
If Condition Then [statements]
End If
If Else Conditional Syntax
If Condition Then [statements]
Else If Condition Then [statements]
End If
Using Select Case
If your program can handle multiple values of a particular variable and you don`t want to stack up a lot of If Else to handle them, you should consider Select Case
We use Select Case to test an expression, determine which of several cases it matches and execute the code
Select Case syntax
Select Case testexpression [Case expressoinlist-n[Statement-n]][Case Else Else statement]]End Select
Example
Module Module1 Sub Main() Dim intNumber As IntegerSystem.Console.WriteLine("enter integer number....")intNumber = Val(System.Console.ReadLine()) Select Case intNumber Case 1System.Console.WriteLine("10q") Case 2 System.Console.WriteLine("OK")Case 3 To 7System.Console.WriteLine("it is b/n 3 and 7")Case Is > 7System.Console.WriteLine("10q") Case ElseSystem.Console.WriteLine("i don`t know nthis number")End SelectSystem.Console.ReadLine()End SubEnd Module
Loop In VBLoop is used to execute a series of statements repeatedly
BUT doesn`t mean you perform one identical task repeatedly, you might be operating on Different data items each time through the loop
Using Do Loop
Keeps executing its enclosed statements While or Until (depending on which keyword you use, While or Until) condition is true
Using Do Loop syntax
Do [{while|until}condition][statements][Exit Do][statements]Loop
ORDo[statements][Exit Do][statements]Loop [{while|until}condition]
Example:
Module Module1
Sub Main() Dim a As Integer a = 1 Do While a < 100 a = a * 2 System.Console.WriteLine("Product is::" & a) Loop System.Console.ReadLine()End Sub
End Module
The For ... Next Loop
Example
Module Module1
Sub Main() Dim i As Integer For i = 1 To 10 System.Console.WriteLine(i) Next i System.Console.ReadLine() End Sub
End Module
Methods In VB.NET
They are a series of statements that are executed when called. Methods allow us to handle code in a simple and organized fashion. There are two types of methods in VB .NET: those that return a value (Functions) and those that do not return a value (Sub Procedures).
Sub Procedures
Sub procedures are methods which do not return a value. Each time when the Sub procedure is called the statements within it are executed until the matching End Sub is encountered.
Sub Main(): the starting point of the program itself is a sub procedure. When the application starts execution, control is transferred to Main Sub procedure automatically which is called by default.
Example of a Sub Procedure
Module Module1Sub Main()'sub procedure Main() is called by defaultDisplay()'sub procedure display() which we are creatingEnd SubSub Display()System.Console.WriteLine("Using Sub Procedures")'executing sub procedure Display()End SubEnd Module
Functions
Function is a method which returns a value. Functions are used to evaluate data, make calculations or to transform data. Declaring a Function is similar to declaring a Sub procedure. Functions are declared with the Function keyword.
Example of Function
Imports System.ConsoleModule Module1
Sub Main()Write("Sum is"&""&Add())'calling the functionEnd Sub
Public Function Add() As Integer'declaring a function addDim i, j As Integer'declaring two integers and assigning values to themi = 10j = 20Return (i + j)'performing the sum of two integers and returning it's valueEnd FunctionEnd Module
Calling Methods
A method is not executed until it is called. A method is called by referencing it's name along with any required parameters. For example, the above code called the Add method in Sub main like this:Write("Sum is" & " " & Add()).
Method Variables
Variables declared within methods are called method variables. They have method scope which means that once the method is executed they are destroyed and their memory is reclaimed. For example, from the above code (Functions) the Add method declared two integer variables i, j. Those two variables are accessible only within the method and not from outside the method.
Parameters
A parameter is an argument that is passed to the method by the method that calls it. Parameters are enclosed in parentheses after the method name in the method declaration. You must specify types for these parameters. The general form of a method with parameters looks like this:
Public Function Add(ByVal x1 as Integer, ByVal y1 as Integer)------------Implementation------------End Function
END OF CHAPTER TWO
THANYOU