Presentation is loading. Please wait.

Presentation is loading. Please wait.

CIS16 Application Development Programming with Visual Basic

Similar presentations


Presentation on theme: "CIS16 Application Development Programming with Visual Basic"— Presentation transcript:

1 CIS16 Application Development Programming with Visual Basic
Chapter Three Variables and Constants

2 How a computer works

3 Question? Can you add 3 numbers and calculate the sum before you get them?

4 LOGIC

5 Pseudocode and Flowcharts
Many programmers use development planning tools such as pseudocode and flowcharts. Pseudocode uses short phrases to describe the steps a procedure must take to accomplish its goal. A flowchart, on the other hand, uses standardized symbols to illustrate a procedure’s steps. Programmers use the planning tool of their choice as a guide when coding the procedure.

6 Pseudocode and Flowcharts

7 Pseudocode and Flowcharts
The flowcharts contain three different symbols: an oval, a rectangle, and a parallelogram The oval symbol is called the start/stop symbol. The start and stop ovals indicate the beginning and end, respectively, of the flowchart. The rectangles are called process symbols. You use the process symbol to represent tasks such as ending the application and making calculations. The parallelogram in a flowchart is called the input/output symbol, and it is used to represent input tasks

8 Internal Memory Figure 3-1: Illustration of shoe boxes and memory locations Memory locations are reserved (declared as a variable) by a programmer for use in a program

9 Variables A variable is a computer memory location that a programmer uses to temporarily store data while an application is running

10 Variables Assigning the variable a data type indicates the type of data (for example a numeric or string) the memory location will store Reasons to use variables To hold information that is not stored in a control on the form To allow for more precise treatment of numeric data To enable code to run more efficiently

11 Byte Whole#’s from 0-255

12 Variables (cont’d.) Variables assigned the Integer, Long, or Short data type can store integers, which are positive or negative numbers that do not have any decimal places The differences among these three data types are in the range of integers each type can store and the amount of memory each type needs to store the integer Variables assigned the Decimal, Double, or Single data type, on the other hand, can store real numbers, which are numbers that contain a decimal place The Char data type can store one Unicode character, while the String data type can store from zero to approximately two billion Unicode characters

13 Using Variables to Store Information (cont.)
The Integer data type is used for all integers Either the Decimal or Double data type are used for numbers containing decimal places or numbers used in calculations The String data type for text or numbers not used in calculations The Boolean data type for Boolean values

14 Using Variables to Store Information (cont.)
Selecting a Name for a Variable Names must begin with a letter or underscore Names can contain only letters, numbers, or underscores No punctuation, special characters, or spaces are allowed The recommended length for a name variable is 32 characters Variable names cannot be reserved words (such as Sub or Double) Three-character IDs and examples

15 Using Variables to Store Information (cont.)
Valid names: intFeb_Income decSales2014 dblEastRegion strName Invalid Names: 4thQuarter The name must begin with a letter or underscore dblWest Region The name cannot contain a space strFirst.Name The name cannot contain punctuation decSales$East The name cannot contain a special character

16 Variables (cont’d.) Declaring a Variable in Code
The declaration statement tells the computer to set aside a small section of its internal memory, and it allows the programmer to refer to the section by the variable’s name The {Dim | Private | Static} portion of the syntax indicates that you can select only one of the keywords appearing within the braces

17 Using Variables to Store Information (cont.)
If no initial value is given to a variable when declaring it, the computer stores a default value Numeric variables are set to 0 Boolean variables are set to False Object and String variables are set to Nothing Date variables are set to 1/1/ :00:00AM

18 LITERALS AND CONSTANTS

19 Literals A value is called a literal when it literally is the value required by the assignment statement

20 Forced Literal Types Sometimes you might want a literal to be a specific data type than the Visual Basic default type

21 Constants A constant variable will contain one permanent value throughout the execution of the program The declaration of a constant begins with the letters Const, not the letters Dim You must assign the value to be contained in the constant on the same line as its definition You cannot attempt to change the value of the constant anywhere in the program. If you do, you will produce a compiler error The letter c often is placed before the constant name to identify it throughout the program as a variable that cannot be changed Other than the letter c, constant names are formed using the same rules and techniques as other variable names

22 Named Constants (cont.)
Figure 3-20 Syntax and examples of the Const statement

23 Assigning data to variables

24 Assigning Data to an Existing Variable
Assignment statement Assigns a value to a variable at run time Syntax: variablename = expression An expression may include literal constants, object properties, variables, keywords, and arithmetic operators Literal constant A data item whose value does not change while the application is running Example: The string “Mary” Literal type character Forces a literal constant to change its data type

25 Referencing a Variable
When a variable is declared, it will be underlined with a green squiggly line until it is referenced in a statement When using a variable in a program, it is mandatory that you define the variable before using the variable name in a statement

26 Assigning Data to an Existing Variable

27 Parsing, converting and formatting

28 Val( ) function Val temporarily converts a string to a number and returns the number Doesn’t change the string Syntax: Val(string) Microsoft Visual Basic 2012: Reloaded, Fifth Edition

29 TryParse() Using the TryParse Method
Each data type in Visual Basic is a class Most classes have one or more methods that perform a specific task for the class All of the Visual Basic numeric data types (such as Double, Decimal, or Integer) have a TryParse method whose task is to convert a string to that particular data type (i.e. convert a string to double, decimal, or integer)

30 TryParse( ) Converts a string to a number Arguments
You specify the data type to parse to Will not produce an error if the conversion fails Arguments dataType: A numeric data type, such as Integer String: A string to be converted Variable: A variable that receives the numeric value SYNTAX: datatype.TryParse(from, into) TryParse Is preferred over Val Allows the programmer to specify the data type Val only returns a Double number

31 TryParse( )

32 TryParse results for double, decimal and integer data types

33 Convert( ) At times, you may need to convert a number (rather than a string) from one data type to another Visual Basic includes several procedures that allow you to convert one data type to another data type Convert Methods include ToDecimal, ToDouble, ToInt32, and ToString

34 Convert( )

35

36 Conversion method review
Ex. Dim W as Double Dim X as String =“10” Dim Y as integer Dim Z as decimal Val temporarily converts a string to a number and returns the number (returns the numbers in a string) Doesn’t change the string (useful for getting numeric info from a textbox) No control over the resulting data type Y = Val(x) ‘ Y is now equal to 10 and can be used in a math equation Y = Val(" ") ' Y is now 2457 TryParse() converts a string to a number Returns 0 if it fails Useful for getting numeric info from a textbox, because it will always return a numeric value ex: Double.TryParse(X, Y) Convert() changes a number from one data type to another W = Convert.ToDouble(Z); Chapter 4: Variables and Arithmetic Operations

37 ToString ( ) Used for Formatting numbers into strings
Specifying decimal places and special characters to display Syntax: variablename.ToString(FormatSpecifier) variablename: The name of a numeric variable FormatSpecifier: The format you want to use

38 Format Specifiers for the ToString Function
Use the format specifier to identify the format for the numeric data to be returned by the ToString function

39 Precision Specifier The precision specifier is a number included within the quotation marks that identifies the number of positions that should be returned to the right of the decimal point

40 Arithmetic expressions

41 Arithmetic Operators

42 Arithmetic Expressions

43 Arithmetic Expressions (cont’d.)
The integer division operator is used to divide two integers and then return the result as an integer The modulus operator (sometimes referred to as the remainder operator) is also used to divide two numbers, but the numbers do not have to be integers After dividing the numbers, the modulus operator returns the remainder of the division

44 Arithmetic Expressions (cont’d.)
Arithmetic Assignment Operators Used to abbreviate an assignment statement that contains an arithmetic operator variableName = variableName arithmeticOperator value age = age is the same as age += 1 Both statements tell the computer to add the number 1 to the contents of the age variable and then store the result in the variable

45

46 Scope

47 The Scope and Lifetime of a Variable
Indicates where a variable can be used Lifetime How long a variable remains in memory Scope and lifetime are determined by where a variable is declared: either the General Declarations section or the form’s Declaration section Three types of scope: Class: The variable can be used by all procedures in a form Procedure: The variable can be used within a procedure Block: The variable can be used within a specific code block

48 Scope and Lifetime (cont’d.)
Variables with Class Scope A class-level variable has have class scope and is declared in the form’s Declarations section, which begins with the Public Class clause and ends with the End Class clause Class-level variables retain their values and remain in the computer’s internal memory until the application ends Declare a class-level variable using the Private keyword When a variable is referenced in two different event handling procedures, it must be defined at the class level instead of the procedure (event handler) level

49 Using a Procedure Two types of Procedures
A procedure that performs its task but does not return a value is called a Sub procedure A procedure that returns a value is called a Function procedure, or a function An argument identifies a value required by a procedure Every procedure is part of a Class Variables with Procedure Scope Can be used only by that procedure Declared at the beginning of the procedure using the Dim keyword Removed from memory when the procedure ends

50 Scope and Lifetime (Cont’d.)

51 Scope and Lifetime (Cont’d.)
Variables are declared using the Dim, Private, or Static keywords A static variable is a procedure-level variable that remains in memory, and also retains its value, even when the procedure in which it is declared ends Like a class-level variable, a static variable is not removed from the computer’s internal memory until the application ends Unlike a class-level variable, which can be used by all the procedures in a form, a static variable can be used only by the procedure in which it is declared

52 Scope and Lifetime (cont’d.)

53 Option statements

54 Option Statements Every variable must be declared Option Explicit
flags any undeclared variables Option Infer Prevents you from using undeclared variables Ensures that every variable is declared with a data type Option Strict - If the value’s data type does not match the memory location’s data type, implicit type conversion occurs to convert the value to fit the memory location Implicit type conversion - Converts the right-side value to the data type on the left side Promotion - Data is converted to a greater precision number (e.g., Integer to Decimal) Demotion = Data is truncated (e.g., Decimal to Integer) Data loss can occur when demotion occurs

55 Option Statements When a value is converted from one data type to another data type that can store either larger numbers or numbers with greater precision, the value is said to be promoted Changing a short (2 bytes) to a Long (8 bytes) Dim X as Short = 2 Dim Y as Long Y =X When a value is converted from one data type to another data type that can store only smaller numbers or numbers with less precision, the value is said to be demoted Changing a long to a short X=Y

56 TESTing and debugging

57 Testing and Debugging the Application
Applications must be tested to verify that the code works correctly A logic error can occur for a variety of reasons A run time error causes the application to end abruptly Your sample input data should include both valid and invalid data Valid data is data that the application is expecting the user to enter Invalid data is data that the application is not expecting the user to enter

58 Debugging Your Program
A Format Exception occurs when the user enters data that a statement within the program cannot process properly

59 Debugging Your Program
An Overflow Exception occurs when the user enters a value greater than the maximum value that the statement can process It is not possible to divide by zero, so if your program contains a division operation and the divisor is equal to zero, the Divide By Zero Exception will occur


Download ppt "CIS16 Application Development Programming with Visual Basic"

Similar presentations


Ads by Google