Variables in VB
What is a variable? ► A named memory location that stores a value
Why use variables? ► Makes code easier to read ► Used to transfer information from one part of a program to another
Types of Variables TYPEPREFIX Singlesgl Doubledbl Integerint Longlng Currencycur Stringstr Booleanbln
Single ► Positive or negative real (might contain a decimal) numbers ► Can store smaller numbers
Double ► Same as single, but can store larger numbers
Integer ► Positive or negative integers (no decimals) ► Smaller integers ► Good for counting (e.g. number of students in a class) ► NOTE: if a decimal number is assigned to an integer, then the value is rounded ► E.g. 6.7 would become 7
Long ► Same as integer, but can store larger numbers
Currency ► Real numbers that are money values ► Up to four decimal places
String ► Set of characters (e.g. letters or any character that can be typed) ► String assignments require quotation marks “” ► E.g. strword = “hello”
Boolean ► True or false ► Used for on/off and yes/no values
Using Variables Step 1 – Declare Step 2 – Initialize (Assign a value) Step 3 – Use
Declaring Variables E.g. Dim intage As Integer ► Dim - stands for dimension (a variable has been assigned a space in memory somewhere) ► intage – identifier (name of variable) ► Integer – data type
Declaring Variables When a variable has been declared, you have saved a space in memory to hold whatever value is assigned: intage
Initializing Variables (assigning a value) E.g. intage = 15 OR intage = txtage.text This will assign whatever the user types into the textbox to intage.
Initializing Variables ► The space in memory now holds a value 15intage
Using the Variable E.g. intagedoubled = intage * 2 This will calculate the person’s age multiplied by 2 and then will store it in the variable called: intagedoubled. You can then output the variable intagedoubled to a textbox. txtagedoubled.text = intagedoubled
Questions 1 – Write a variable declaration statement for: a)A variable called intgrade of integer type b)A variable called strword of string type
Questions 2 – Indicate the value of the following variables: a) Dim dblnumber As Double dblnumber = 6 – 3 dblnumber dblnumber
Questions 2 – b) Dim intnum1 As Integer Dim intnum2 As Integer Dim intnum2 As Integer Dim intnum3 As Integer Dim intnum3 As Integer intnum1 = 3 intnum2 = 4 intnum3 = intnum1 * intnum2 intnum1 intnum2 intnum3