cis 115 lecture05 vb-variables

Upload: vikash-yadav

Post on 02-Jun-2018

227 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    1/34

    CIS 115 Lecture 5

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    2/34

    A storage location in memory (RAM)

    Holds data/information while the program is running

    These storage locations can be referred to by their

    names

    Every variable has three properties:

    Name- reference to the location - cannot be changed

    Value- the information that is stored - can be changedduring program execution, hence the name variable

    Data Type- the type of information that can be stored -

    cannot be changed

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    3/34

    You the programmer make up a name for thevariable

    Visual Basic associates that name with alocation in the computer's RAM

    The value currently associated with thevariable is stored in that memory location

    You simply use the name you chose when youneed to access the value

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    4/34

    Copy and store values entered by the user Perform arithmetic manipulation on values

    Test values to see if they meet a criteria Temporarily hold and manipulate the value of

    a control property Hold data/information so that it can be

    recalled for use at a later point in the code

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    5/34

    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

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    6/34

    Data type Prefix Size ValuesByte 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,647

    Long lng 8 byte integer from +/- 9,223,372,036,854,775,807Single sng 4 byte single-precision, floating-point numberDouble dbl 8 byte double-precision, floating-point numberDecimal 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 dtm 8 byte 8 character date: #dd/mm/yyyy#Object obj (4 byte) An address that refers to an object

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    7/34

    First character must be a letter or underscore Must contain only letters, numbers, and

    underscores (no spaces, periods, etc.)

    Can have up to 255 characters Cannot be a VB language keyword Naming Conventions Should be meaningful

    Follow 3 char prefix style - 1st 3 letters in lowercaseto indicate the data type

    After that, capitalize the first letter of each word

    Example: intTestScore

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    8/34

    A variable declaration is a statement thatcreates a variable in memory

    Syntax: Dim VariableNameAs 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

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    9/34

    A starting or initialization value may bespecified with the Dim statement

    Good practice to set an initial value unlessassigning a value prior to using the variable Syntax:

    Dim VariableNameAs DataType= Value Just append " = value to the Dim statement

    = 5assigning a beginning value to the variable

    Example: Dim intLength as Integer = 5

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    10/34

    Variable MUST be declared prior to the codewhere they are used

    Variable should be declared first in theprocedure (style convention)

    Declaring an initial value of the variable in thedeclaration statement is optional

    Refer to default values (next slide)

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    11/34

    Data type Default (Initial) value

    All numeric types Zero (0)

    Boolean FalseChar Binary 0

    String or Object Empty

    Date 12:00 a.m. on January 1, 0001

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    12/34

    Actual value/data/information Similar to a variable, but can NOT change

    during the execution of a program. Examples of Literals:

    Numeric: 5 ; 157 ; 195.38256

    String: Paul ; Hello!!! ; Jackson, AL 36545

    Char: a ; 1 ; ? ; @

    Boolean: True ; False

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    13/34

    Programs often need to use given values

    For example: decTotal *= 1.06

    Adds 6% sales tax to an order total

    Two problems with using literals for these typesof values

    The reason for multiplying decTotal by 1.06 isnt

    always obvious

    If sales tax rate changes, must find and change every

    occurrence of .06 or 1.06

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    14/34

    Use of named constantsresolves both these issues Can declare a variable whose value is set at

    declaration and cannot be changed later: Syntax: Const CONST_NAMEAs DataType= Value

    Looks like a normal declaration except:

    Const used instead of Dim

    An initialization value is required

    By convention, entire name capitalized with underscore

    characters to separate words

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    15/34

    The objective of our code is now clearer

    Const sngSALES_TAX_RATE As Single = 1.06

    decTotal *= sngSALES_TAX_RATE Can change all occurrences in the code simply

    by changing the initial value set in thedeclaration

    If tax rate changes from 6% to 7%

    Const sngSALES_TAX_RATE As Single = 1.07

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    16/34

    What Indicates the part of the program where thevariable can be used

    When From the variable declaration until the end ofthe 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 tostatements 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 samename (same name ok if different scope)

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    17/34

    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 untilthe end of that code block

    When the code block begins the space is created to holdthe 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

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    18/34

    Syntax: variablename = expression Assigns the value of the expression to the

    variable. (The variable must be on the left andthe expression on the right.)

    Example: intNumber1 = 4

    intNumber2 = 3 * (2 + 2) intNumber3 = intNumber1

    IntNumber1 = intNumber1 + 6

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    19/34

    A value of one data type can be assigned to a variable

    of a different type

    An implicit type conversion is an attempt to automatically

    convert to the receiving variables data type A widening conversion suffers no loss of data

    Converting an integer to a single

    Dim sngNumber as Single = 5

    A narrowing conversion may lose data Converting a decimal to an integer

    Dim intCount = 12.2 intCount becomes 12

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    20/34

    VB provides a set of functions that perform data type

    conversions These functions will accept a literal, variable name, or

    arithmetic expression The following narrowing conversions require an

    explicit type conversion

    Double to Single

    Single to Integer Long to Integer

    Boolean, Date, Object, String, and numeric types

    represent different sorts of values and require

    conversion functions as well

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    21/34

    The Val functionis a more forgiving means ofperforming string to numeric conversions

    Uses the form Val(string) If the initial characters form a numeric value,

    the Val function will return that Otherwise, it will return a value of zero

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    22/34

    Val Function Value Returned

    Val("34.90) 34.9

    Val("86abc) 86

    Val("$24.95) 0

    Val("3,789) 3

    Val(") 0

    Val("x29) 0 Val("47%) 47

    Val("Geraldine) 0

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    23/34

    Returns a string representation of the value inthe variable calling the method

    Every VB data type has a ToStringmethod Uses the form VariableName.ToString For example

    Dim number as Integer = 123

    lblNumber.text = number.ToString

    Assigns the string 123 to the text property of thelblNumber control

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    24/34

    Arithmetic Operators

    ^ Exponential

    * Multiplication/ Floating Point Division

    \ Integer Division

    MOD Modulus (remainder from division)

    + Addition

    Subtraction

    & String Concatenation (putting them together)

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    25/34

    Examples of use: decTotal = decPrice + decTax

    decNetPrice = decPrice - decDiscount

    dblArea = dblLength * dblWidth

    sngAverage = sngTotal / intItems

    dblCube = dblSide ^ 3

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    26/34

    The backslash (\) is used as an integer divisionoperator

    The result is always an integer, created bydiscarding any remainder from the division

    Example intResult = 7 \ 2 result is 3

    shrHundreds = 157 \ 100 result is 1 shrTens = (157 - 157 \ 100 * 100) \ 10

    result is ?

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    27/34

    This operator can be used in place of thebackslash operator to give the remainder of a

    division operationintRemainder = 17 MOD 3 result is 2

    dblRemainder = 17.5 MOD 3 result is 2.5

    Any attempt to use of the \ or MOD operatorto perform integer division by zero causes aDivideByZeroException runtime error

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    28/34

    Concatenate: connect strings together Concatenation operator: the ampersand (&) Include a space before and after the & operator

    Numbers after & operator are converted to strings

    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

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    29/34

    Often need to change the value in a variable andassign the result back to that variable

    For example: var = var 5 Subtracts 5 from the value stored in var

    Operator Usage Equivalent to Effect+= x += 2 x = x + 2 Add to

    -= x -= 5 x = x

    5 Subtract 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

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    30/34

    Operatorprecedencetells us the order in whichoperations are performed

    From highest to lowest precedence:

    Exponentiation (^) Multiplicative (* and /)

    Integer Division (\)

    Modulus (MOD)

    Additive (+ and -) Parentheses override the order of precedence Where precedence is the same, operations

    occur from left to right

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    31/34

    Parenthesis Exponential

    Multiplication / Division Integer Division MOD Addition / Subtraction String Concatenation Relational Operators (< , > , >= ,

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    32/34

    6 * 2 ^ 3 + 4 / 2 = 50

    7 * 4 / 2 6 = 8

    5 * (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

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    33/34

    Redo the Calculate Gross Pay example fromLecture 4 using variables.

    Redo the Calculator from HW2 usingvariables.

  • 8/10/2019 CIS 115 Lecture05 VB-Variables

    34/34

    Homework 3

    Visual Basic - Variables

    See handout for details and due date Questions?