Data and Operations. Outline

Similar documents
Data Types. Strings Variables Declaration Statements Named Constant Assignment Statements Intrinsic (Built-in) Functions

Outline. Data and Operations. Data Types. Integral Types

3.1. Chapter. CSC 252 (MIS 385) Chapter 3 Input, Variables, Exceptions, and Calculations. Introduction. Page 1

Programming Language 2 (PL2)

Copyright 2014 Pearson Education, Inc. Chapter 3. Variables and Calculations. Copyright 2014 Pearson Education, Inc.

Chapter 3. Variables and Calculations Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of

Unit 4. Lesson 4.1. Managing Data. Data types. Introduction. Data type. Visual Basic 2008 Data types

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Introduction to Data Entry and Data Types

Agenda & Reading. VB.NET Programming. Data Types. COMPSCI 280 S1 Applications Programming. Programming Fundamentals

UNIT- 3 Introduction to C++

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Murach s Visual Basic 2012, C4 2013, Mike Murach & Associates, Inc. Slide 1. The built-in value types (continued)

VARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals

Visual C# Instructor s Manual Table of Contents

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Language Fundamentals

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

C++ Programming: From Problem Analysis to Program Design, Third Edition

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

VB.NET MOCK TEST VB.NET MOCK TEST I

BASIC ELEMENTS OF A COMPUTER PROGRAM

Microsoft Visual Basic 2015: Reloaded

Basics of Java Programming

COMP Primitive and Class Types. Yi Hong May 14, 2015

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

Full file at

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Full file at

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Expressions and Casting

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Java Notes. 10th ICSE. Saravanan Ganesh

Bits, Words, and Integers

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Chapter 2: Using Data

The C++ Language. Arizona State University 1

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Reserved Words and Identifiers

DEPARTMENT OF MATHS, MJ COLLEGE

Declaration and Memory

VB FUNCTIONS AND OPERATORS

Java Programming Fundamentals. Visit for more.

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

Introduction to Computer Use II

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

JAVA Programming Fundamentals

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

Ex: If you use a program to record sales, you will want to remember data:

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Microsoft Visual Basic 2005: Reloaded

Lesson 02 Working with Data Types MIT 31043, Visual Programming By: S. Sabraz Nawaz

4. Inputting data or messages to a function is called passing data to the function.

Chapter 2: Basic Elements of C++

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

ECE 122 Engineering Problem Solving with Java

Lecture 2 Tao Wang 1

Objectives. In this chapter, you will:

Programming and Data Structures

Computer System and programming in C

Information Science 1

Information Science 1

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Programming in C++ 5. Integral data types

2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a) and (b) D. stands for Graphic Use Interaction

Fundamentals of Programming

Lesson 02 Working with Data Types. MIT 31043: VISUAL PROGRAMMING By: S. Sabraz Nawaz Senior Lecturer in MIT

LECTURE 3 C++ Basics Part 2

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Getting started with Java

CIS 3260 Intro to Programming with C#

Object Oriented Programming with Visual Basic.Net

Fundamental of Programming (C)

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

LECTURE 02 INTRODUCTION TO C++

CMPT 125: Lecture 3 Data and Expressions

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

Chapter 2 Working with Data Types and Operators

CHAPTER 3 BASIC INSTRUCTION OF C++

Lecture 1. Types, Expressions, & Variables

The PCAT Programming Language Reference Manual

Programming in C++ 6. Floating point data types

Primitive Data Types: Intro

Chapter 17. Fundamental Concepts Expressed in JavaScript

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

Basic Operations jgrasp debugger Writing Programs & Checkstyle

BITG 1233: Introduction to C++

CHAPTER 3 Expressions, Functions, Output

Work relative to other classes

Transcription:

Data and Operations Data and Operations 1 Outline Data Types Arithmetic Operations Strings Variables Declaration Statements Named Constant Assignment Statements Intrinsic (Built-in) Functions Data and Operations 2

Data Types In computers data such as integers, real numbers, character, strings, and Boolean are represented and stored in memory differently. In order to represent data efficiently based on memory space and calculations accuracy, the size memory space is preset for each data type to be stored. Computer languages provide appropriate different data types according to the size of storage. There are four fundamental data types: Integral types Floating-point numbers Characters String Boolean values Data and Operations 3 Integral Data Types An integer type has a value as a whole number either negative or positive, e.g., 123, +123, 123, 22333 Visual Basic.NET has different integral types depends on the size of the storage. For examples, Byte -- 1 byte Short -- 2 bytes Integer -- 4 bytes Long -- 8 bytes Data and Operations 4

Integer Data Types For values that will always be a whole number Usually name a variable starting with a 3 or 4 letter prefix indicating the variable s type Data Type Namin g Prefix Description Byte byt Unsigned integer from 0 to 255 Short shrt Signed integer from -32,768 to 32,767 Intege r Long int Signed integer from -2,147,483,648 to 2,147,483,647 lng Signed integer from - 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Data and Operations 5 Floating-Point Data Types For values that may have fractional parts Single used most frequently Double sometimes used in scientific calculations Decimal often used in financial calculations Data Type Namin g Prefix Description Single sng As large as 10 38 plus or minus, 7 decimal positions Double dbl As large as 10 308 plus or minus,15 decimal positions Decima l dec As large as 10 29 plus or minus, 29 decimal positions Data and Operations 6

Floating-Point Data Types A floating number or a real number is any signed or unsigned number having an integer part and a fractional part, with a decimal point in between e.g., 18.0, +9.2, 35.25, 0.57, 138.2, 4.,.8 Visual Basic supports two different categories of floating point numbers: Single -- Numbers which are stored using the single data type are called single precision numbers. Double -- Numbers that are stored using the double data type are called double precision numbers. A double precision number uses twice the amount of storage as that used by a single precision number. Data and Operations 7 Exponential Notation Exponential notation is commonly used to express both very large and very small floating point numbers in a compact form, e.g., 1.74536E 12, 3.652442E4, 7E20 It is similar to scientific notation. Decimal Notation Exponential Notation Scientific Notation 1234 1.234E3 1.234 10 3 123456 1.23456E5 1.23456 10 5.01234 1.234E 2 1.234 10 2.0001234 1.234E 4 1.234 10 4 Data and Operations 8

Other Common Data Types Boolean variable naming prefix is bln Holds 2 possible values, True or False Char variable naming prefix is chr Holds a single character Allows for characters from other languages String variable naming prefix is str Holds a sequence of up to 2 billion characters Date variable naming prefix is dat Can hold date and/or time information Data and Operations 9 Strings A string consists of one or more characters that are enclosed within double quotes. The number of characters within a string determines the length of the string. For examples, apple, S, 45, Joe Nobody and HELLO. String concatenation means the joining of two or more strings into a single string. Visual Basic provides two symbols, the ampersand (&) and the plus sign (+), for performing string concatenation. Joe & & Nobody Joe Nobody Numeric values and/or strings can be displayed using either a call to the MessageBox.Show() method or a text box. Data and Operations 10

ASCII Code A 01000001 N 01001110 B 01000010 O 01001111 C 01000011 P 01010000 D 01000100 Q 01010001 E 01000101 R 01010010 F 01000110 S 01010011 G 01000111 T 01010100 H 01001000 U 01010101 I 01001001 V 01010110 J 01001010 W 01010111 J o e 00000000 01001010 00000000 01101111 00000000 01100101 K 01001011 X 01011000 L 01001100 Y 01011001 M 01001101 Z 01011010 Data and Operations 11 Boolean There are only two Boolean data values in Visual Basic. These values are the constants: True and False. The Boolean constants are used in decision-making statements. Data and Operations 12

Date Data Type Date data type variables can hold the date and time A date literal is enclosed within # symbols #10/20/2005 6:30:00 AM# or #12/10/2005# or #21:15:02# Or can use a function to convert a string to a date System.Convert.ToDateTime("12/3/2002") System.Convert.ToDateTime function is used to store a date from a text box in a date variable System.Convert.ToDateTime(txtDate.text) Data and Operations 13 Fundamental VB.NET Data Types Type Size in Bytes Description Range of Values Byte 1 8-bit unsigned integer 0-255 Integer 4 32-bit signed integer 2147483648-2147483647 Long 8 64-bit signed integer 9223372036854775808-9223372036854775807 Short 2 16-bit signed integer 32,768-32,767 Single 4 Double 8 Decimal 16 Char 2 32-bit floating point variable 64-bit floating point variable 128-bit floating point variables 16-bit Unicode characters String Varies Non-Numeric Type 3.4E38-3.4E+38 (7 significant digits) 1.7E308-1.7E+308 (15 significant digits) 0-65,535 Boolean 1 Non-Numeric Type False or True Date 8 Non-Numeric Type 00:00:00 on January 1, 0001 11:59:59 on December 31, 9999 Object 4 Non-Numeric Type Reference to an object Data and Operations 14

Arithmetic Operations Visual Basic provides a number of numeric operators, which can be used to perform operations such as additions, subtractions, multiplications, etc. A simple numeric expression is an expression that has a numeric operator connecting two arithmetic operands. This type of expression has the syntax: operand operator operand A binary operator is an operator that requires two operands. A unary operator is an operator that requires only one operand. Data and Operations 15 Arithmetic Operations + Unary Plus Unary Negation + Addition Subtraction * Multiplication / Division \ Integer Division ^ Mod Exponentiation Modulus -- return remainder Data and Operations 16

Precedence of Arithmetic Operations Operator ^ Exponentiation Negation Operation * / Multiplication and Division \ Integer Division Mod Modulus -- return remainder + Addition and Subtraction Data and Operations 17 Operator Precedence Examples 6 * 2^3 + 4 / 2 6 * 8 + 4 / 2 48 + 4 / 2 48 + 2 50 6 / 2 * 2^3 + 4 6 / 2 * 8 + 4 3 * 8 + 4 24 + 4 28 Data and Operations 18

Rules of Forming Expressions The followings are rules when writing expressions in Visual Basic: Two binary operators must never be placed adjacent to one another. 20 * 40 is invalid. Parentheses may be used to form groupings, and all expressions enclosed within parentheses are evaluated first. Parentheses cannot be used to indicate multiplication. (10 + 20) (30) is invalid. Data and Operations 19 Expression Types Integer expression -- is an arithmetic expression containing only integers. Floating point expression -- is an arithmetic expression containing only floating point numbers. Mixed-mode expression -- is an arithmetic expression containing both integers and floating point numbers. Data and Operations 20

Types of Arithmetic Expressions combining floating point numbers with either integers or floating point numbers floating point combining integers or floating point numbers with \ integer combining integers with either +,, *,\, Mod integer Data and Operations 21 Arithmetic Expression Expression Result Type 11 + 4-27 Integer 11 / 4.6 * 0.879 Floating Point 11 / (4.6 * 0.879) Floating Point 11.36 + 4.6 * 0.879 Floating Point Data and Operations 22

Integer Division Operator VB.NET uses back slash (\) as integer division operator. Expression Actual Value Result 11\4 11\4 = 2.75 2 11\4.6 11\5 = 2.20 2 11.36\4 11\4 = 2.75 2 11.36\4.6 11\5 = 2.20 2 Data and Operations 23 Mod Operator The modulus operator Mod yields the remainder of the result of dividing its first operand by its second. Expression Actual Value Result 11 Mod 4 11 4 = 2 r 3 3 20 Mod 4 20 4 = 5 r 0 0 11 Mod 4.6 11 4.6 = 2 r 1.8 1.8 11.36 Mod 4.6 11.36 4.6 = 2 r 2.16 2.16 Data and Operations 24

Variables A variable is a storage location in the computer s memory, used for holding information while the program is running. The information that is stored in a variable may change, hence the name variable. Data and Operations 25 What Can You Do With Variables? Copy and store values entered by the user, so they may be manipulated Perform arithmetic on values Test values to determine that they meet some criterion Temporarily hold and manipulate the value of a control property Remember information for later use in the program Data and Operations 26

How to Think About Variables You the programmer make up a name for the variable Visual Basic associates that name with a location in the computer's RAM The value currently associated with the variable is stored in that memory location Data and Operations 27 Variable Naming Rules The first character of a variable name must be a letter or an underscore Subsequent characters may be a letter, underscore, or digit Thus variable names cannot contain spaces or periods (or many other kinds of characters) Visual Basic keywords cannot be used as variable names Data and Operations 28

Variable Naming Conventions Naming conventions are a guideline to help improve readability but not required syntax A variable name should be chosen to indicate what it represents Each data type has a recommended prefix, in lower case, that begins the variable name The 1 st letter of each subsequent word in the variable name should be capitalized inthoursworked - an integer variable strlastname - a string (or text) variable Data and Operations 29 Declaring Variables with IntelliSense As you enter your program, VB often aids you by offering a list of choices that could be used at that point After typing As in a variable declaration, VB will offer an alphabetical list of all possible data types Type the first few letters of the data type name Intellisense box will highlight the matching type Press the Tab key to select highlighted choice Or just complete typing the entire data type name Data and Operations 30

Variable Declaration Statements A variable declaration is a statement that create a variable in memory as well as specifying the data type that can be stored in it. Declaration statements placed within a procedure and have the general syntax: Dim VariableName As DataType Dim (short for Dimension) is a keyword ariablename is the programmer designated name As is a keyword DataType is one of many possible keywords for the type of value the variable will contain Data and Operations 31 Examples Dim intnumber As Integer Dim sngwages As Single Dim strlast_name As String Dim chrmiddleintial As Char Dim blnempty As Boolean Data and Operations 32

Single-line line Declarations Visual Basic allows combining multiple declarations into one statement, using the syntax: Dim var1 As DataType, var2 As DataType,...,,...,varn As DataType Examples: Dim strfirstname As String, strlastname As data-type, strmiddleinit As Char, inttest1 As Integer, inttest2 As Integer, sngaverage As Single Dim inttest1, inttest2, inttest3, intfianlexam As Integer, sngaverage As Single Data and Operations 33 Default Values When a variable is first created in memory, it is assigned a default value numeric types are given a value of zero Boolean types are given a value of False strings are given a value of Nothing dates default to 12:00:00 AM January 1,1 Data and Operations 34

Initialization An initialization is the process of storing a value in a variable for the first time. Declaration statements perform both a software and a hardware function. From a software perspective, declaration statements provide a convenient, up-front list of all variables and their data types. The hardware function that declaration statements perform is that they inform Visual Basic of the physical memory storage that must be reserved for each variable. Programmers use variable names to reference their contents. Data and Operations 35 Initialization Can provide a starting or initialization value for any type of variable in a Dim statement Usually want to set an initial value unless assigning a value prior to using the variable Just append = value to the Dim statement where value is the literal to be assigned to the variable Dim intmonthsperyear As Integer = 12 Good practice to initialize string variables Dim strname As String = String.Empty String with value Nothing causes error if used Data and Operations 36

Scope and Local Variables Scope refers to the part of the program where: A variable is visible and May be accessed by program code Variables declared within a procedure are called local variables and observe these characteristics Scope begins where variable is declared Extends to end of procedure where declared Variable is not visible outside the procedure A variable cannot be declared twice in the same procedure Data and Operations 37 Class-Level and Global Scope A variable declared inside a class but outside any procedure is a class-level variable Scope is throughout all procedures of the class A variable declared outside any class or procedure is a global variable Scope is throughout all forms, classes, and procedures of the project Class-level and global scope will be discussed further in future chapters Values in a variable are destroyed when it goes out of scope Data and Operations 38

Named Constants Programs often need to use given values For example: dectotal *= dectotal* 1.06 Adds 6% sales tax to an order total Two problems with this approach The reason for multiplying dectotal by 1.06 isn t always obvious If sales tax rate changes, must find and change every occurrence of.06 or 1.06 Use of named constants resolves both these issues Data and Operations 39 Named Constants Constants are numbers that have a special meaning in the context of a particular application. Const statement is used to assign symbolic names to constants. The syntax for this statement within a form s procedure is: Const named-constant As DataType = expression A named constant is a symbolic name assigned to a constant. A named constant cannot be altered after it is defined. All Const statements must be placed in the Declarations section of the form or within a procedure, but for clarity they are usually placed immediately after the procedure s declaration Data and Operations 40

Named Constants Can declare a variable whose value is set at declaration and cannot be changed later: Const sngsales_tax_rate As Single = 1.06 The objective of our code is now clearer Const sngsales_tax_rate As Single = 1.06 dectotal *= sngsales_tax_rate Data and Operations 41 Examples Const bythourlyrate As Byte = 15 Const bytweekly As Byte = 40 Const sngpi As Single = 3.141 Const dblsalestax As Double =.0825 Data and Operations 42

Assignment Statements Assignment statements are statements that tell the computer to store a value into a variable. An assignment statement can be used to both assign a value to a variable and to perform calculations. The assignment statement has the following syntax: variable = expression An expression is any combination of constants, variables, and operators that can be evaluated to yield a value. Assignment statements always have an equal (=) sign and exactly one variable name immediately to the left of the equal sign. The value on the right of the equal sign is assigned to the variable on the left of the equal sign. Data and Operations 43 Examples Count = 0 Count = Count + 1 Sum = Sum + Data Area = Height * Width AverageScore = TotalSum / NemberOfScores Solution = Math.Sqrt(B^2 2*A*C) Data and Operations 44

Assignment Statements Data1 65 1 location: 12345 0 Data2 49 0 location: 67890 1 0 0 0 0 0 1 0 1 0 0 0 1 Consider following actions that a computer will perform: put 65 in location 12345 put 49 in location 67890 Add the content of location 12345 to the content of location 67890 store the sum in location 76543 The programming version is as follows: Data1 = 65 Data2 = 49 Sum = Data1 + Data2 0 Sum 114 1 location: 76543 1 1 0 0 1 0 Data and Operations 45 Assignment Variations An assignment variation statement is an assignment statement in which the variable on the left of the equal sign is also used on the right of the equal sign. For example : Total = Total + 34.7 Sum = Sum + Number Data and Operations 46

Accumulating To accumulate subtotals when data is entered one number at a time, assignment statements such as Total = Total + 34.7 are used. These statements have the syntax: variable = variable + new value Example: SumScore = SumScore + Score Data and Operations 47 Counting The counting statement is a variation of the accumulating assignment statement. It has the following form: Variable = Variable + fixed number After a counting statement is executed, the value of the variable is increased by a fixed amount. Example: Count = Count + 1 Count += 1 Data and Operations 48

Lab 6 Task 2 Const SalesTaxRate As Single = 0.0825 Dim TotalAmount, SalesTaxAmount, InputAmount As Double REM Retrieve input amount from InputAmountTextBox and REM Compute the sales tax, then the total amount InputAmount = InputTextBox.Text SalesTaxAmount = InputAmount * SalesTaxRate TotalAmount = InputAmount + SalesTaxAmount REM Display sales tax and total amount SalesTaxLabel.Text = FormatCurrency(SalesTaxAmount) TotalAmountLabel.Text = FormatCurrency(TotalAmount) Data and Operations 49 Lab 6 Task 2 Const SalesTaxRate As Single = 0.0825 SalesTaxRate 0.0825 Dim TotalAmount, SalesTaxAmount, InputAmount As Double REM Retrieve input amount from InputAmountTextBox and REM Compute the sales tax, then the total amount InputAmount = InputTextBox.Text SalesTaxAmount = InputAmount * SalesTaxRate TotalAmount = InputAmount + SalesTaxAmount REM Display sales tax and total amount SalesTaxLabel.Text = FormatCurrency(SalesTaxAmount) TotalAmountLabel.Text = FormatCurrency(TotalAmount) Data and Operations 50

Lab 6 Task 2 Const SalesTaxRate As Single = 0.0825 Dim TotalAmount, SalesTaxAmount, InputAmount As Double REM Retrieve input amount from InputAmountTextBox and REM Compute the sales tax, then the total amount InputAmount = InputTextBox.Text SalesTaxAmount = InputAmount * SalesTaxRate TotalAmount = InputAmount + SalesTaxAmount REM Display sales tax and total amount SalesTaxLabel.Text = FormatCurrency(SalesTaxAmount) TotalAmountLabel.Text = FormatCurrency(TotalAmount) SalesTaxRate 0.0825 TotalAmount 0. SalesTaxAmount 0. InputAmount 0. Data and Operations 51 Lab 6 Task 2 Const SalesTaxRate As Single = 0.0825 Dim TotalAmount, SalesTaxAmount, InputAmount As Double REM Retrieve input amount from InputAmountTextBox and REM Compute the sales tax, then the total amount InputAmount = InputTextBox.Text SalesTaxAmount = InputAmount * SalesTaxRate TotalAmount = InputAmount + SalesTaxAmount REM Display sales tax and total amount SalesTaxLabel.Text = FormatCurrency(SalesTaxAmount) TotalAmountLabel.Text = FormatCurrency(TotalAmount) SalesTaxRate 0.0825 TotalAmount 0. SalesTaxAmount 0. InputAmount 100. Data and Operations 52

Lab 6 Task 2 Const SalesTaxRate As Single = 0.0825 Dim TotalAmount, SalesTaxAmount, InputAmount As Double REM Retrieve input amount from InputAmountTextBox and REM Compute the sales tax, then the total amount InputAmount = InputTextBox.Text SalesTaxAmount = InputAmount * SalesTaxRate TotalAmount = InputAmount + SalesTaxAmount REM Display sales tax and total amount SalesTaxLabel.Text = FormatCurrency(SalesTaxAmount) TotalAmountLabel.Text = FormatCurrency(TotalAmount) SalesTaxRate 0.0825 TotalAmount 0. SalesTaxAmount 8.25 InputAmount 100. Data and Operations 53 Lab 6 Task 2 Const SalesTaxRate As Single = 0.0825 Dim TotalAmount, SalesTaxAmount, InputAmount As Double REM Retrieve input amount from InputAmountTextBox and REM Compute the sales tax, then the total amount InputAmount = InputTextBox.Text SalesTaxAmount = InputAmount * SalesTaxRate TotalAmount = InputAmount + SalesTaxAmount REM Display sales tax and total amount SalesTaxLabel.Text = FormatCurrency(SalesTaxAmount) TotalAmountLabel.Text = FormatCurrency(TotalAmount) SalesTaxRate 0.0825 TotalAmount 108.25 SalesTaxAmount 8.25 InputAmount 100. Data and Operations 54

Lab 6 Task 2 Const SalesTaxRate As Single = 0.0825 Dim TotalAmount, SalesTaxAmount, InputAmount As Double REM Retrieve input amount from InputAmountTextBox and REM Compute the sales tax, then the total amount InputAmount = InputTextBox.Text SalesTaxAmount = InputAmount * SalesTaxRate TotalAmount = InputAmount + SalesTaxAmount REM Display sales tax and total amount SalesTaxLabel.Text = FormatCurrency(SalesTaxAmount) TotalAmountLabel.Text = FormatCurrency(TotalAmount) SalesTaxRate 0.0825 TotalAmount 108.25 SalesTaxAmount 8.25 InputAmount 100. Data and Operations 55 Lab 6 Task 2 Const SalesTaxRate As Single = 0.0825 Dim TotalAmount, SalesTaxAmount, InputAmount As Double REM Retrieve input amount from InputAmountTextBox and REM Compute the sales tax, then the total amount InputAmount = InputTextBox.Text SalesTaxAmount = InputAmount * SalesTaxRate TotalAmount = InputAmount + SalesTaxAmount REM Display sales tax and total amount SalesTaxLabel.Text = FormatCurrency(SalesTaxAmount) TotalAmountLabel.Text = FormatCurrency(TotalAmount) SalesTaxRate 0.0825 TotalAmount 108.25 SalesTaxAmount 8.25 InputAmount 100. Data and Operations 56

Implicit Type Conversions A value of one data type can be assigned to a variable of a different type An implicit type conversion is an attempt to convert to the receiving variable s 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 Data and Operations 57 Option Strict Option Strict is a VB configuration setting Only widening conversions are allowed when Option Strict is set to On An integer can be assigned to a decimal A decimal cannot be assigned to an integer A single can be assigned to a double A double cannot be assigned to a single Option Strict On is recommended to help catch errors Data and Operations 58

Type Conversion Runtime Errors Consider the statement Dim intcount As Integer = abc123 This is a narrowing conversion With Option Strict On, statement will not compile With Option Strict Off, statement compiles but String abc123 will not convert to an integer A runtime error called a type mismatch occurs when this statement is executed Data and Operations 59 Explicit Type Conversions A function performs some predetermined operation and provides a single output Input(s) Function Output VB provides a set of functions that permit narrowing conversions with Option Strict On These functions will accept a constant, variable name, or arithmetic expression The function returns the converted value Data and Operations 60

Explicit Type Conversions 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 Data and Operations 61 Explicit Type Conversion Examples Rounding can be done with the CInt function intcount = CInt(12.4) intcount value is 12 intcount = CInt(12.5) intcount value is 12 CStr converts an integer value to a string Dim strtext as String = CStr(26) CDec converts a string to a decimal value Dim decpay as Decimal = CDec( $1,500 ) CDate converts a string to a date Dim dathired as Date = CDate( 05/10/2005 ) Data and Operations 62

A Full List of Conversion Functions There are conversion functions for each data type CBool ( expr ) CByte ( expr ) CChar ( expr ) CDate ( expr ) CDbl ( expr ) CDec ( expr ) CInt ( expr ) CLng ( expr ) CObj ( expr ) CShort ( expr ) CSng ( expr ) CStr ( expr ) Data and Operations 63 Invalid Conversions Conversion functions can fail Dim dblsalary As Double = CDbl( xyz ) Dim dathired As Date = CDate( 05/35/2005 ) String xyz can t be converted to a number There s no day 35 in the month of May These failed conversions cause a runtime error called an invalid cast exception Data and Operations 64

The Val Function The Val function is a more forgiving means of performing string to numeric conversions Uses the form Val(string) as shown here intnumber = 45 Return value is the number 45 Argument contains the string 45 Val(InputTextBox.text) If the initial characters form a numeric value, the Val function will return that Otherwise, it will return a value of zero Data and Operations 65 The Val Function 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 Data and Operations 66

Examples Expression Dim intaverage As Integer Average = 98 / 10 Dim intnumberstring As Integer NumberString = 100 Dim sngnumber As Single Number = 100 Assigned Value intaverage = 10 intnumberstring = 100 sngnumber = 100.0 Data and Operations 67 Asc(string) Chr(val) Function Name and Arguments CBool(expression) CByte(expression) CChar(expression) CDate(expression) CDbl(expression) CDec(expression) CInt(expression) CLng(expression) CObj(expression) CShort(expression) CSng(expression) CStr(expression) CType(expression, type) Val(string) with VB.NET Description and Returned Value Convert the first character in the string to an ACII value Returns string associated with the specified ASCII value. Convert an expression to a Boolean value. Convert an expression to a Byte with rounding if necessary. Convert the first character of a string expression to a Char Convert an expression to a date. Convert a numeric value or string expression to a Double. Convert a numeric value or string expression to a Decimal. Convert a numeric value or string expression to a Integer. Convert a numeric value or string expression to a Long. Convert an expression to an Object. Convert a numeric value or sting expression to a Short. Convert a numeric value or sting expression to a Single. Convert an expression to a String. Convert an expression to a specified type. Return the first numeric value of the string. Data and Operations 68

Intrinsic (Built-in) in) Functions Intrinsic functions are preprogrammed routines provided by Visual Basic.NET that can be used in a procedure. These include mathematical functions, functions to carry out conversion between data types, formatting functions, and string manipulation functions. A number of mathematical functions are found in the System.Math class of Visual Basic.NET. Functions operate in a manner similar to sub procedures, except for the fact that a function always directly returns a single value. Data and Operations 69 Examples Function Name Description Returned Value Math.Sqrt(9) Square root 3 Math.Abs(-42) Absolute value 42 Math.Round(4.779, 2) Round 4.78 Math.Log(24.212) Log 3.186... Data and Operations 70

Examples Function Name Description Returned Value Val( 100 ) Convert string to value 100 CStr(100) Convert value to string 100 Int(99.8) Round to nearest integer less than or equal to the number 99 CInt(99.8) Round to nearest integer 100 Ceiling(99.8) Floor(99.8) Returns the smallest integer greater than the number Returns the integer largest less than the number 100 99 Data and Operations 71 Problem Create a project that can be used by a business persons on their laptop computer to determine exchange rates for China, Japan, England, and France. A form for this project is shown on the right. For this project, assume that one dollar has 8.3 yuans 120 yen 0.6 pounds 5 francs Data and Operations 72

Objects and Their Properties Control Name Text ForeColo r Font Size Others Form1 Default Currency Conversion Default None Size: 470, 315 Textbox1 InputTextBox None (blank) Default 12 Size: Width: 100 Label1 DisplayLabel None (blank) Red 12 Label2 Defualt Enter the dollar amount in text1 and click on the appropriate button. Default 12 Size: 100, 30, BackColor: Pale Yellow Size: 400, 40 Label3 Defualt Enter The Dollar Amount: Default 12 Size: 200, 30 Label4 CurrencyLabe l Currency: Default 12 Size: 80, 30, Button1 YenButton Yen Blue 12 Size: 100, 30; Bold: True Button2 YuanButton Yuans Blue 12 Size: 100, 30; Bold: True Button3 PoundButton Pounds Blue 12 Size: 100, 30; Bold: True Button4 FrancButton Francs Blue 12 Size: 100, 30; Bold: True Button5 QuitButton Quit Red 12 Size: 100, 30; Bold: True Data and Operations 73 Form Design Data and Operations 74

How Many Events Are in This Project? 1. YenButton Click Event Convert dollars to Yen Display currency as Yen 2. YuanButton Click Event Convert dollars to Yuans Display currency as Yuans 3. PoundButton Click Event Convert dollars to Pounds Display currency as Pounds 4. FrancButton Click Event Convert dollars to Francs Display currency as Francs 5. QuitButton Click Event Close application/window Data and Operations 75 Chart of Functions for Each Control Currency Conversion Application Yen Button Click Event: Convert dollars to Yen Display currency as Yen Yuan Button Click Event: Convert dollars to Yuans Display currency as Yuans Pound Button Click Event: Convert dollars to Pounds Display currency as Pounds Franc Button Click Event: Convert dollars to Francs Display currency as Franc Quit Button Click Event: Close application/window Data and Operations 76

Code for Each Event Procedure 1. YenButton Click Event Procedure: Dim Amount As Double Amount = Val(InputTextbox.Text) Convert dollars to Yen DisplayLabel.Text = Amount * 120.0 Display currency as Yen CurrencyLabel.Text = "Yen" 2. YuanButton Click Event Convert dollars to Yuans DisplayLabel.Text = Val(InputTextbox.Text) * 8.3 Display currency as Yuans CurrencyLabel.Text = "Yuans" 3. PoundButton Click Event Convert dollars to Pounds DisplayLabel.Text = Val(InputTextbox.Text) * 8.3 Display currency as Pounds CurrencyLabel.Text = "Yuans" 4. FrancButton Click Event Convert dollars to Francs DisplayLabel.Text = Val(InputTextbox.Text) * 8.3 Display currency as Francs CurrencyLabel.Text = "Yuans" 5. QuitButton Click Event Close application/window Close() Data and Operations 77 Data and Operations 78