320 likes | 385 Views
Chapter 2. Variables and Constants. Variables. Variable – a named memory location that stores a value. A variable can be thought of as a named box (memory location) containing a value. Variables are used in a program so that values can be represented with meaningful names.
E N D
Chapter 2 Variables and Constants
Variables • Variable – a named memory location that stores a value. • A variable can be thought of as a named box (memory location) containing a value. • Variables are used in a program so that values can be represented with meaningful names.
Declaration of a Variable • A variable must be declared before it is used. • Declaration Statement: Dimvariable_nameAs type • Ex. DimintNumberAs Integer
Dim Statement • Dimvariable_name As type • Dim – stands for dimension. A declared variable has a “dimension” because it has been assigned space in memory. • Variable – prefix of the variable • Name – descriptive name of the variable • Type – Data Type
Initialization of Variable • A numeric variable is automatically initialized to 0 in Visual Basic • A declaration statement can also include a specific value for initialization. • Example: DimsngRadiusAs Single = 9.5 • Initializes a variable named sngRadius with the value of 9.5
Multiple Declaration of Variables • Multiple variables with the same data type can be declared in a single statement. • Example: DimsngRadius, sngDiameterAs Single • Grouping variables together in a single declaration is good programming style when the variables represent related items.
Variable Assignment • The value stored in a variable can be changed at runtime through assignment. • A variable assignment must be written so that the variable name is on the left side of the equal sign and the value is on the right. • Example: Dim sngRadiusAs Single = 10 sngRadius = 12.3
Variable Assignment cont… • One common error is to reverse the variable name and the value in an assignment statement. • 12.3 = sngRadius ‘Error
Initialization of Variable to a Numeric Expression • A numeric expression can also be used on the right side of an assignment statement. • sngCircleArea = 3.14 * sngRadius ^ 2 • A variable can be used wherever a value can be used.
IMPORTANT • A variable can store only one value at any given time. Dim sngRadiusAs Single = 10 sngRadius = 5 sngRadius = 12.5 • The final statement is what sngRadius with be assigned to. sngRadius = 12.5
Obtaining a Value from the User • A TextBox object is one way to allow users to enter values. • A label is often placed near a text box to describe its contents or purpose. This label is also called the prompt.
TextBox • Name = prefix = txt • Text = what is displayed in the text box. • TextAlign = sets the alignment of text relative to the text box. • At run time, the TextBox Text property stores whatever characters are currently in the text box. • sngRadius = Me.txtRadius.Text
TextBox cont… • If the text box does not contain data that matches the variable type, a run-time error occurs and the program is halted. • To prevent this, the Val() function should be used when assigning data from a text box to a numeric variable. • Function = a procedure that performs a task and returns a value.
Value Function • Val() takes a string and returns a number corresponding to the numeric characters in the string. • If the first character of the sting is not a number, Val() returns a 0.
Value cont… • Dim sngHeight As Single • sngHeight = Val(“62.5 inches”) = 62.5 sngHeight = Val(“Twenty inches”) = 0 sngHeight = Val(“Six ft. 2 inches”) = 0
Named Constants • A constant is a named memory location which stores a value that cannot be changed from its initial assignment. • Const sngPI As Single = 3.14 • A value of a constant is typed only in the declaration, eliminating the possibility of typing the wrong value elsewhere in a program.
Constants cont… • This also means that if the program is modified later, the constant value need only be changed in one place. • Const sngPI As Single = 3.14159265 • As a matter of good programming style, constants should be in all uppercase except for the prefix that indicates the data type.
Constants cont… • Const sngPI As Single = 3.14 sngPI = 22/7 ‘Error
Choosing Identifiers • There are several identifiers that Visual Basic.net reserves for use as keywords. • Keyword – has special meaning, and therefore cannot be used for a variable or named constant identifier. • For example, Single, End, and Sub are keywords. Keywords appear in different font.
Built-In Data Types • A variable or constant declaration includes a data type that corresponds to the data stored. • Visual Basic includes several data types:
Built-in Data Types Type Prefix Used to represent Short srt Integers from -32,768 to 32,767 Integerint Integers from -2,147,483,648 to 2,147,483,647 Long lng large integers (no decimals) Single sng numbers possibly containing a decimal Double dbl large numbers possibly containing a decimal Date dtm a date in m/d/yyyy format Decimal dec numbers that may have many significant digits Char chr a single character String str a set of characters Boolean bln True or False
Variable Initialization • Visual Basic automatically initializes variables to a default value when they are declared. • Variables of numeric type, such as Short, Integer, Long, Single, Double, and Decimal are initialized to 0. • Date variables are initialized to 12:00:00 AM.
Variable Initialization cont… • Boolean variables are initialized to False. • Char and String variables are initialized to nothing, which is equal to the keyword Nothing. • This keyword can be used in place of an empty string (“”) for clearing labels, and so on.
Automatic Type Conversion • In an assignment statement, Visual Basic automatically converts data to match the type of the variable it is being assigned to. • Dim intX = 6.7 ‘intX is assigned to the value of 7
Automatic Type Conversion cont… • Visual Basic will try to convert from one data type to another as long as the data is valid for the receiving data type. • For example, assigning 12.3 to an Integer variable intX is valid because the number can be converted to 12. However, an error will be generated when abc is assigned to an Integer variable.
Scope • Scope of a Variable – is the set of statements that can use the variable. • Local Declaration – a declaration at the beginning of a procedure where the variable can only be used “locally” • Global Declaration – a declaration placed at the beginning of the program that can be used in any procedure throughout the program.
Special Division OperatorsInteger Division • Integer Division ( \ ) – truncates the decimal portion of the quotient, which results in an integer. • Dim intX As Integer intX = 20 \ 7 ‘IntX is assigned 2 • Only returns the whole portion of the quotient
Modulus Division • Modulus Division ( Mod ) – returns the remainder resulting from division. • Dim intX as Integer intX = 20 Mod 7 ‘intX is assigned 6 • Only returns the remainder of the quotient. • Modulus division is used in applications where the separate digits of a number are needed, for finding the number of minutes left over after hours have been accounted for, and for other integer related tasks.
Programming Errors • Syntax Error – a statement that violates the rules of Visual Basic • Logic Error – are caused by statements that are syntactically correct, but produce undesired or unexpected results. • Run-Time Error – Syntax and logic errors that go undetected may generate a run-time error when the program is run. A run-time error halts the program at the statement that cannot be executed.
Debugging an Application • Debugging – the process of getting an application to work correctly. One technique uses breakpoints. • Breakpoint – a statement that has been marked as a stopping point. • Watch Window – used to examine values in break mode.