vb language2

40
Visual Basic Language

Upload: getamesay-berihun

Post on 21-Jan-2015

224 views

Category:

Documents


5 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Vb language2

Visual Basic Language

Page 2: Vb language2

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

Page 3: Vb language2

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

Page 4: Vb language2

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

Page 5: Vb language2

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

Page 6: Vb language2

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

Page 7: Vb language2

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

Page 8: Vb language2

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

Page 9: Vb language2

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

Page 10: Vb language2

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

Page 11: Vb language2

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)

Page 12: Vb language2

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

Page 13: Vb language2

Performing Calculations with Variables

Arithmetic Operators^ Exponential* Multiplication/ Floating Point Division\ Integer DivisionMOD Modulus (remainder from division)+ Addition– Subtraction& String Concatenation

(putting them together)

Page 14: Vb language2

Common Arithmetic Operators

Examples of use: decTotal = decPrice + decTax decNetPrice = decPrice - decDiscount dblArea = dblLength * dblWidth sngAverage = sngTotal / intItems dblCube = dblSide ^ 3

Page 15: Vb language2

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

Page 16: Vb language2

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”

Page 17: Vb language2

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

Page 18: Vb language2

Operators Precedence

ParenthesisExponentialMultiplication / DivisionInteger DivisionMODAddition / SubtractionString ConcatenationRelational Operators (< , > , >= , <=

, <>)Logical Operators (AND, OR, NOT)

Page 19: Vb language2

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

Page 20: Vb language2

Conditionals

Page 21: Vb language2

If Condition Syntax

If Condition Then [statements]

End If

Page 22: Vb language2

If Else Conditional Syntax

If Condition Then [statements]

Else If Condition Then [statements]

End If

Page 23: Vb language2

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

Page 24: Vb language2

Select Case syntax

Select Case testexpression [Case expressoinlist-n[Statement-n]][Case Else Else statement]]End Select

Page 25: Vb language2

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

Page 26: Vb language2

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

Page 27: Vb language2

Using Do Loop

Keeps executing its enclosed statements While or Until (depending on which keyword you use, While or Until) condition is true

Page 28: Vb language2

Using Do Loop syntax

Do [{while|until}condition][statements][Exit Do][statements]Loop

ORDo[statements][Exit Do][statements]Loop [{while|until}condition]

Page 29: Vb language2

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

Page 30: Vb language2

The For ... Next Loop

Page 31: Vb language2

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

Page 32: Vb language2

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

Page 33: Vb language2

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.

Page 34: Vb language2

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

Page 35: Vb language2

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.

Page 36: Vb language2

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

Page 37: Vb language2

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()).

Page 38: Vb language2

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.

Page 39: Vb language2

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

Page 40: Vb language2

END OF CHAPTER TWO

THANYOU