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

Similar documents
Data and Operations. Outline

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

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

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

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

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

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

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

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

Language Fundamentals

VB.NET MOCK TEST VB.NET MOCK TEST I

BASIC ELEMENTS OF A COMPUTER PROGRAM

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

Full file at

Chapter 2: Introduction to C++

! 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

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

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.

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

Chapter 2: Using Data

Basics of Java Programming

Microsoft Visual Basic 2015: Reloaded

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

Reserved Words and Identifiers

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Bits, Words, and Integers

DEPARTMENT OF MATHS, MJ COLLEGE

Declaration and Memory

Full file at

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

Java Notes. 10th ICSE. Saravanan Ganesh

The C++ Language. Arizona State University 1

Department of Computer and Mathematical Sciences. Lab 7: Selection

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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

Microsoft Visual Basic 2005: Reloaded

Java Programming Fundamentals. Visit for more.

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

VB FUNCTIONS AND OPERATORS

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

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

Objectives. In this chapter, you will:

Lecture 2 Tao Wang 1

Programming and Data Structures

JAVA Programming Fundamentals

Computer System and programming in C

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

Fundamental of Programming (C)

Information Science 1

Information Science 1

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

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

Introduction to Computer Use II

Fundamentals of Programming

LECTURE 3 C++ Basics Part 2

Operators. Lecture 3 COP 3014 Spring January 16, 2018

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

The PCAT Programming Language Reference Manual

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Object Oriented Programming with Visual Basic.Net

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

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

LECTURE 02 INTRODUCTION TO C++

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

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

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

Lecture 1. Types, Expressions, & Variables

Programming in C++ 5. Integral data types

The SPL Programming Language Reference Manual

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

Programming in C++ 6. Floating point data types

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

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

Getting started with Java

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

Basic Operations jgrasp debugger Writing Programs & Checkstyle

CIS 3260 Intro to Programming with C#

Work relative to other classes

CHAPTER 3 Expressions, Functions, Output

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards

Transcription:

Data and Operations Outline Data Types Arithmetic Operations Strings Variables Declaration Statements Named Constant Assignment Statements Intrinsic (Built-in) Functions Data and Operations 1 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 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 3 Data and Operations 4 1

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 Naming Prefix Description Byte byt Unsigned integer from to 255 Short shrt Signed integer from -32,768 to 32,767 Integer Long int Signed integer from -2,147,483,648 to 2,147,483,647 lng Signed integer from - 9,223,372,36,854,775,88 to 9,223,372,36,854,775,87 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 Naming Prefix Description Single sng As large as 1 38 plus or minus, 7 decimal positions Double dbl As large as 1 38 plus or minus,15 decimal positions Decima l dec As large as 1 29 plus or minus, 29 decimal positions Data and Operations 5 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., +9.2, 35.25,.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. 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, 7E2 It is similar to scientific notation. Decimal Notation Exponential Notation Scientific Notation 1234 1.234E3 1.234 1 3 123456 1.23456E5 1.23456 1 5.1234 1.234E 2 1.234 1 2.1234 1.234E 4 1.234 1 4 Data and Operations 7 Data and Operations 8 2

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 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 9 Data and Operations 1 ASCII Code Boolean J o e 111 111111 1111 A 11 N 1111 B 11 O 11111 C 111 P 11 D 11 Q 111 E 111 R 111 F 111 S 1111 G 1111 T 111 H 11 U 1111 I 111 V 1111 J 111 W 11111 K 1111 X 111 L 111 Y 1111 M 1111 Z 1111 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 11 Data and Operations 12 3

Date Data Type Date data type variables can hold the date and time A date literal is enclosed within # symbols #1/2/25 6:3: AM# or #12/1/25# or #21:15:2# Or can use a function to convert a string to a date System.Convert.ToDateTime("12/3/22") System.Convert.ToDateTime function is used to store a date from a text box in a date variable System.Convert.ToDateTime(txtDate.text) Fundamental VB.NET Data Types Type Size in Bytes Description Byte 1 8-bit unsigned integer - 255 Range of Values Integer 4 32-bit signed integer 2147483648-2147483647 Long 8 64-bit signed integer 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 92233723685477588-92233723685477587 3.4E38-3.4E+38 (7 significant digits) 1.7E38-1.7E+38 (15 significant digits) - 65,535 Boolean 1 Non-Numeric Type False or True Date 8 Non-Numeric Type :: on January 1, 1 11:59:59 on December 31, 9999 Object 4 Non-Numeric Type Reference to an object Data and Operations 13 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. Arithmetic Operations + Unary Plus Unary Negation + Addition Subtraction * Multiplication / Division \ Integer Division ^ Mod Exponentiation Modulus -- return remainder Data and Operations 15 Data and Operations 16 4

Precedence of Arithmetic Operations Operator Operation ^ Exponentiation Negation * / Multiplication and Division \ Integer Division Mod Modulus -- return remainder + Addition and Subtraction Operator Precedence Examples 6 * 2^3 + 4 / 2 6 / 2 * 2^3 + 4 6 * 8 + 4 / 2 6 / 2 * 8 + 4 48 + 4 / 2 3 * 8 + 4 48 + 2 24 + 4 5 28 Data and Operations 17 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. 2 * 4 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. (1 + 2) (3) is invalid. 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 19 Data and Operations 2 5

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 Arithmetic Expression Expression Result Type 11 + 4-27 Integer 11 / 4.6 *.879 Floating Point 11 / (4.6 *.879) Floating Point 11.36 + 4.6 *.879 Floating Point Data and Operations 21 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.2 2 11.36\4 11\4 = 2.75 2 11.36\4.6 11\5 = 2.2 2 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 2 Mod 4 2 4 = 5 r 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 23 Data and Operations 24 6

Lab 5 Task 3 Statement of the Problem: Create a VB.NET application called Arithmetic Operations that a user can type in two numbers. When a user clicks on an operation button, the application will display the result of that operation operates on the two entered numbers. The design/gui of application should look similar to the following figure: Control Objects and Their Properties Control Name Text ForeColor Font Size Others Form1 Default Arithmetic Operations Default None Size: 47, 315 Textbox1 NumberBox1 None (blank) Default 12 Size: Width: 1 Textbox2 NumberBox2 None (blank) Default 12 Size: Width: 1 Size: 1, 3, Label1 DisplayLabel None (blank) Red 12 BackColor: Pale Yellow Label2 Defualt = Default 1 Size: 2, 2 Button1 AddButton + Blue 1 Size: 5, 2 Button2 SubButton Blue 1 Size: 5, 2 Button3 MulButton * Blue 1 Size: 5, 2 Button4 DivButton / Blue 1 Size: 5, 2 Button5 IDivButton \ Blue 1 Size: 5, 2 Button6 PowerButton ^ Blue 1 Size: 5, 2 Button7 ModButton Mod Blue 1 Size: 5, 2 Button8 ExitButton Exit Default 12 Size: 1, 3 Data and Operations 25 Data and Operations 26 Form Design How Many Events Are in This Project? 1. Addition (+) button click event: This event will retrieve the two numbers, perform addition, and display the result. 2. Subtraction ( ) button click event: This event will retrieve the two numbers, perform addition, and display the result. 3. Multiplication (*) button click event: This event will retrieve the two numbers, perform addition, and display the result. 4. Division (/) button click event: This event will retrieve the two numbers, perform addition, and display the result. 5. Integer division (\) button click event: This event will retrieve the two numbers, perform addition, and display the result. 6. Power (^) button click event: This event will retrieve the two numbers, perform addition, and display the result. 7. Mod button click event: This event will retrieve the two numbers, perform addition, and display the result. 8. Exit button click event: This event will retrieve the two numbers, perform addition, and display the result. 4. Division (/) button click event: 8. Exit button click event: Data and Operations 27 Data and Operations 28 7

Chart of Functions for Each Control Code for Each Event Procedure 1. AddButton Click Event Procedure: retrieve two numbers, perform addition, display result DisplayLabel.Text = Val(NumberBox1.Text) + Val(NumberBox2.Text) 2. AddButton Click Event Procedure: retrieve two numbers, perform addition, display result DisplayLabel.Text = Val(NumberBox1.Text) + Val(NumberBox2.Text) 3. AddButton Click Event Procedure: retrieve two numbers, perform addition, display result DisplayLabel.Text = Val(NumberBox1.Text) + Val(NumberBox2.Text) 4. AddButton Click Event Procedure: retrieve two numbers, perform addition, display result DisplayLabel.Text = Val(NumberBox1.Text) + Val(NumberBox2.Text) 5. AddButton Click Event Procedure: retrieve two numbers, perform addition, display result DisplayLabel.Text = Val(NumberBox1.Text) + Val(NumberBox2.Text) 6. AddButton Click Event Procedure: retrieve two numbers, perform addition, display result DisplayLabel.Text = Val(NumberBox1.Text) + Val(NumberBox2.Text) 7. AddButton Click Event Procedure: retrieve two numbers, perform addition, display result DisplayLabel.Text = Val(NumberBox1.Text) + Val(NumberBox2.Text) 8. ExitButton Click Event Close application/window Close() Data and Operations 29 Data and Operations 3 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. 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 31 Data and Operations 32 8

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 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 33 Data and Operations 34 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 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 35 Data and Operations 36 9

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 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 37 Data and Operations 38 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 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:: AM January 1,1 Data and Operations 39 Data and Operations 4 1

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. 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 41 Data and Operations 42 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 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 43 Data and Operations 44 11

Named Constants Programs often need to use given values For example: dectotal *= dectotal* 1.6 Adds 6% sales tax to an order total Two problems with this approach The reason for multiplying dectotal by 1.6 isn t always obvious If sales tax rate changes, must find and change every occurrence of.6 or 1.6 Use of named constants resolves both these issues 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 45 Data and Operations 46 Named Constants Can declare a variable whose value is set at declaration and cannot be changed later: Const sngsales_tax_rate As Single = 1.6 The objective of our code is now clearer Const sngsales_tax_rate As Single = 1.6 dectotal *= sngsales_tax_rate Examples Const bythourlyrate As Byte = 15 Const bytweekly As Byte = 4 Const sngpi As Single = 3.141 Const dblsalestax As Double =.825 Data and Operations 47 Data and Operations 48 12

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. Examples Count = Count = Count + 1 Sum = Sum + Data Area = Height * Width AverageScore = TotalSum / NemberOfScores Solution = Math.Sqrt(B^2 2*A*C) Data and Operations 49 Data and Operations 5 Assignment Statements Assignment Variations Data1 65 1 location: 12345 Data2 49 location: 6789 1 1 1 1 Consider following actions that a computer will perform: put 65 in location 12345 put 49 in location 6789 Add the content of location 12345 to the content of location 6789 store the sum in location 76543 The programming version is as follows: Data1 = 65 Data2 = 49 Sum = Data1 + Data2 Sum 114 1 location: 76543 1 1 1 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 51 Data and Operations 52 13

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 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 53 Data and Operations 54 Lab 6 Task 2 Const SalesTaxRate As Single =.825 Lab 6 Task 2 Const SalesTaxRate As Single =.825 SalesTaxRate.825 Dim TotalAmount, SalesTaxAmount, InputAmount As Double 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) 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 55 Data and Operations 56 14

Lab 6 Task 2 Lab 6 Task 2 Const SalesTaxRate As Single =.825 SalesTaxRate.825 Const SalesTaxRate As Single =.825 SalesTaxRate.825 Dim TotalAmount, SalesTaxAmount, InputAmount As Double TotalAmount. SalesTaxAmount. Dim TotalAmount, SalesTaxAmount, InputAmount As Double TotalAmount. SalesTaxAmount. 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) InputAmount. 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) InputAmount 1. Data and Operations 57 Data and Operations 58 Lab 6 Task 2 Lab 6 Task 2 Const SalesTaxRate As Single =.825 SalesTaxRate.825 Const SalesTaxRate As Single =.825 SalesTaxRate.825 Dim TotalAmount, SalesTaxAmount, InputAmount As Double TotalAmount. SalesTaxAmount 8.25 Dim TotalAmount, SalesTaxAmount, InputAmount As Double TotalAmount 18.25 SalesTaxAmount 8.25 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) InputAmount 1. 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) InputAmount 1. Data and Operations 59 Data and Operations 6 15

Lab 6 Task 2 Lab 6 Task 2 Const SalesTaxRate As Single =.825 SalesTaxRate.825 Const SalesTaxRate As Single =.825 SalesTaxRate.825 Dim TotalAmount, SalesTaxAmount, InputAmount As Double TotalAmount 18.25 SalesTaxAmount 8.25 Dim TotalAmount, SalesTaxAmount, InputAmount As Double TotalAmount 18.25 SalesTaxAmount 8.25 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) InputAmount 1. 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) InputAmount 1. Data and Operations 61 Data and Operations 62 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 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 63 Data and Operations 64 16

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 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 65 Data and Operations 66 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 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,5 ) CDate converts a string to a date Dim dathired as Date = CDate( 5/1/25 ) Data and Operations 67 Data and Operations 68 17

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 ) Invalid Conversions Conversion functions can fail Dim dblsalary As Double = CDbl( xyz ) Dim dathired As Date = CDate( 5/35/25 ) 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 69 Data and Operations 7 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 The Val Function Val Function Value Returned Val("34.9 ) 34.9 Val("86abc ) 86 Val("$24.95 ) Val("3,789 ) 3 Val(" ) Val("x29 ) Val("47% ) 47 Val("Geraldine ) Data and Operations 71 Data and Operations 72 18

Examples Function Name and Arguments Asc(string) Chr(val) CBool(expression) 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. Expression Dim intaverage As Integer Average = 98 / 1 Assigned Value intaverage = 1 CByte(expression) CChar(expression) CDate(expression) CDbl(expression) CDec(expression) CInt(expression) 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. Dim intnumberstring As Integer NumberString = 1 intnumberstring = 1 CLng(expression) CObj(expression) CShort(expression) 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. Dim sngnumber As Single Number = 1 sngnumber = 1. CSng(expression) CStr(expression) CType(expression, type) Convert a numeric value or sting expression to a Single. Convert an expression to a String. Convert an expression to a specified type. Val(string) Return the first numeric value of the string. Data and Operations 73 Data and Operations 74 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. 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 75 Data and Operations 76 19

Examples Function Name Description Returned Value Val( 1 ) Convert string to value 1 CStr(1) Convert value to string 1 Int(99.8) Round to nearest integer less than or equal to the number 99 CInt(99.8) Round to nearest integer 1 Ceiling(99.8) Floor(99.8) Returns the smallest integer greater than the number Returns the integer largest less than the number 1 99 Data and Operations 77 2