[go: up one dir, main page]

0% found this document useful (0 votes)
14 views38 pages

Topic 3

This document covers the fundamentals of variables, constants, and arithmetic operations in programming. It explains the differences between variables and constants, outlines various data types and their naming conventions, and provides guidelines for declaring variables and formatting data for output. Additionally, it discusses arithmetic operations, operator precedence, and converting string values to numeric data types.

Uploaded by

2022605412
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views38 pages

Topic 3

This document covers the fundamentals of variables, constants, and arithmetic operations in programming. It explains the differences between variables and constants, outlines various data types and their naming conventions, and provides guidelines for declaring variables and formatting data for output. Additionally, it discusses arithmetic operations, operator precedence, and converting string values to numeric data types.

Uploaded by

2022605412
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

TOPIC 3

Variables, Constants and


Arithmetic Operations
Lesson Outcomes
 At
the end of this lesson, students should be
able to:
 Distinguish between variables and constants
 Explain, differentiate and use the various
data types
 Declare variables using the Dim statement
 Perform calculations using variable and
constant
 Format values for output using the formatting
functions
Variables & Constants
 Variables and constants are temporary
memory locations that have a name, a
data type and a scope.
 Variables – memory locations that hold
data that can be changed during project
execution
 Constants – memory locations that hold
data that cannot be change during project
execution Constants
Area of Circle =π × r2
Variables
Data Types
 The data type determines what type of value
may be stored in a variable or constant
 Default data type is variant (if not specify a
data type)
 Advantage: It’s easy – the variables or constants
change their appearance as needed for each
situation
 Disadvantage: Less efficient – require more
memory and operate less quickly than other data
types
 Most common types are String, Currency and
Integer
Data Types (cont.)
Type Value Range
Boolean True or False
Byte A single ASCII character
Decimal Dollars and cents (two decimal places)
Date Eight character date (mm/dd/yy)
Integer Small integers (+ or -32,767)
Long Larger integers (+ or -2 Billion)
Single 6-digit floating point numbers
Double 14-digit floating point numbers
String Character data
Variant Converts from one type to another
Naming Rules
 Names are from 1 to 255 characters long
 Names must begin with a letter
 Names may consist of letters, digits and
underscores
 Names must not contain blanks
 Names cannot be Visual Basic reserved
words
 Keywords to which VB has assigned some
meaning
 Examples: Print, Name and Value
Naming Conventions
 Identifiersmust be meaningful – clearly
indicates its purpose
 Precede each identifier with a lowercase
prefix that specifies the data type
 After the appropriate prefix, capitalize
each word of the name
 Used mixed case
 Examples: strLongNameHere

Specifies the data type


Data Types & Their Prefixes
Data Type Prefix
Decimal dec
Boolean bln
Double dbl
Date/Time dtm
Integer int
Long lng
Single sng
String str
Variant vnt
Example Identifiers
 Guidelines to choose suitable data type:
 If the data will be used in a calculation, then
it must be numeric – Integer or Decimal
 If it is not used in a calculation – String
 Use Decimal as the data type for any
decimal fractions in business application
 Single and Double data types are generally
used in scientific applications
Example Identifiers
Field of Data Data Type Possible Identifier
IC Number String Not used in a calculation
Eg.: strICNumber
Pay rate Decimal Used in a calculation, contains a
decimal point
Eg.:decPayRate
Hours worked Decimal Used in calculation, contains a decimal
point (Decimal can be used for any
decimal fraction, not just dollars)
Eg.: decHoursWorked
Quantity Integer Used in calculation, contains a whole
number
Eg.: intQuantity
Phone String Not used in a calculation
number Eg.: strPhoneNumber
Constants
 Two type of constants:
 Named constants: a programmer-defined constants
and are declared using the Const statement
 Intrinsic constants: predefined and built into VB; such
as Color.Red, Color.Blue and etc.
 Const statement – General form
 Const Identifier [As Datatype] = Value
 Example:
Const decSalesTaxRate As Decimal = .08
Const strCompanyName As String = “R n R”
Constants (cont.)
 Assigning values to constants
 String values must be enclosed in quotation
marks, “ ”
 May contain letters, digits and special
characters
 Also known as string literals
 Numeric values are not enclosed
 May contains only the digits (0-9), a decimal
point and a sign (+ or -) at the left side
 Cannot include comma, dollar sign, any other
special characters or sign at the right side
Declaring Variables
 Variablesare declared using the Dim statement
 Dim statement – General form
 Dim Identifier [As Datatype]
 Example:
 Dim strCustName As String
 Dim intTotalSold As Integer
 Dim decPrice As Decimal
 Dim vntStatus ‘defaults to variant type
Declaring Variables (cont.)
 The
reserved word Dim is really short for
dimension, which means “size”
 When you declare a variable, the amount of
memory reserved depends on its data type
Scope of Variables/Constants
 Scope is the visibility (can be used or ‘seen’
in this location) of a variable/constant
 Global: can always be used or seen across
the entire project (all procedures in a project)
 Module: accessible by all procedures in the
form
 Local: accessible only from single procedure
in which it is declared
Scope of Variables/Constants (cont.)

LOCAL
DECLARATION
Variable Lifetime
 Lifetime – the period of time the variable
exist
 Local variable exist each time the sub
procedure executed, and disappear when
the procedures finishes
 Module-level variable lifetime is the entire
time the form is loaded
Arithmetic Operations
 Standard operators: ^, *, /, +, -
 Operator precedence determines how an
equations is evaluated:
 Parentheses
 Exponentiation
 Multiplication or Division (from left to right)
 Addition or Subtraction (from left to right)
/ 15/2 7.5

\ 12\5 2

36\5 7
MOD

150/60
150 Mod 60 = 30 =2
=Bal 30
3+2x4-6 = 5

20-5+3 = 18

15-22+6 = 17

2+(3-1)+7 = 11
Converting Strings to a
Numeric Data Type
 Values of text boxes and labels are actually
strings od text characters.
 They should not be used directly in calculations,
just in case they are not numbers.
Identifiers=Integer .Parse(Object.Property)

intQuantity = Integer.Parse(txtQuantity.Text)

Identifiers=Decimal.Parse(Object.Property)
Parse Function (cont.)
 How does it works?
 When the Parse function converts an
argument to numeric, it begins at the
argument’s left most character
 If that character is a numeric digit, decimal
point or sign, Parse converts the character to
numeric and move to the next character. As
soon as a non-numeric character is found,
the operation stops.
Example – Values returned by
Parse()
Contents of Argument Numeric value returned by the
Parse()
(blank) 0
123.45 123.45
$100 0
1,000 1
A123 0
123A 123
4B5 4
-123 -123
+123 123
12.34.8 12.34
Formatting Data
 Formatting data: to format data for display (on
the printer or on the screen)
 To display output:
Object.Property = Value.ToString(Format Data)

txtExtendedPrice.text=decExtendedPrice.ToString(
“C”)

lblExtendedPrice.Text =
'Calculate the extended price,discount and discounted price
decExtendedPrice = intQuantity * decPrice
decDiscount = decDiscountRate * decExtendedPrice
decDiscountedPrice = decExtendedPrice ‐ decDiscount

'Display the output


txtExtendedPrice.Text = decExtendedPrice.ToString("C")

object Property Value Format


Format Currency Function (“C”)
 Returns a string of characters formatted as
dollars and cents
 By default, the currency value displays a dollar
sign, commas and two positions to right of the
decimal point.
 Simple form:
 .ToString(“C”)
 Example:
 lblBalance.text = decBalance.ToString(“C”)
 txtBalance.text = decBalance.ToString(“C”)

RM1,000.25
Format Number Function (“N”)
 Thevalue will displays with commas and
two digits to the right of the decimal point.
 Simple form:
 .ToString(“N”)
 .ToString(“N3”)

 Example:
 txtSum.text = decSum.ToString(”N”) 1,000.25
 txtSum.text = decSum.ToString(”N3”) 1,000.253
Format Fixed-point Function (“F”)
Format as a string of:
 numeric digits,
 No commas,
 2 decimal places, and
 A minus sign at the left for negative values.
Simple form:
 .ToString(“F”)
 .ToString(“F3”)
 Example:
1000.25
 txtSum.text = decSum.ToString(”F”)
 txtSum.text = decSum.ToString(”F3”) 1000.253
Format Digits Function (“D”)
 Use only for integer data types.
 Format with a left minus sign for negative values.
 Usually used to force a specified number of digits
to display.
Simple form:
 .ToString(“D”)
 .ToString(“D3”)
 Example: 25
 txtQuantity.text = intQuantity.ToString(”D”)
 txtQuantity.text = intQuantity.ToString(”D3”)
025
Format Percent Function
 To display numeric values as a percent
 This function multiplies the argument by 100, adds a
percent sign and rounds to two decimal places.
 Simple form:
 .ToString(“P”)
 .ToString(“P0”)
 .ToString(“P3”)

 Example: 50.50%
 lblInterestRate.text = decInterestRate.ToString(“P”)
 lblInterestRate.text = decInterestRate.ToString(“P0”)

50%
Format Date Time Function
 Format an expression as a date and/or time
 The expression may be a string that holds
A date or time values
 A date type variable, or
 A function that returns a date

 Simple form:
 ToLongDateString
 ToShortDateString
 ToLongTimeString
 ToShortTimeString
Named Format
Named Format Returns Example
ToLongDateString Days of week, Month, Day, Sunday, June 21,2020
Year
ToShortDateString MM/DD/YY 6/21/2020
ToLongTimeString HH:MM:SS AM/PM 01:02:26 PM
ToShortTimeString HH:MM (24 hours clock) 12:03 AM
Private Sub btnCost_Click(sender As Object, e As EventArgs) Handles btnCost.Click

Dim strNumberOfDays As String


Dim intNumberOfDays As Integer
Dim decTotalCost As Decimal

strNumberOfDays = txtNumberOfDays.Text
intNumberOfDays = Convert.ToInt32(strNumberOfDays)

decTotalCost = intNumberOfDays * _cdecPricePerDay

lblTotalCost.Text = decTotalCost.ToString("C")
End Sub

Private Sub btnCost_Click(sender As Object, e As EventArgs) Handles btnCost.Click

Dim intNumberOfDays As Integer


Dim decTotalCost As Decimal Input
intNumberofDays = Integer.Parse(txtNumberOfDays.Text)

decTotalCost = intNumberOfDays * _cdecPricePerDay Process


lblTotalCost.Text = decTotalCost.ToString("C")
End Sub Output

Identifiers=Integer .Parse(Object.Property)
End of Topic 3

You might also like