Chapter 4 Introduction to Numeric Data Types and Variables.

Slides:



Advertisements
Similar presentations
Operators & Identifiers The Data Elements. Arithmetic Operators exponentiation multiplication division ( real ) division ( integer quotient ) division.
Advertisements

Chapter 3: Using Variables and Constants Programming with Microsoft Visual Basic 2005, Third Edition.
Lecture Set 4 Data Types and Variables Part B – Variables, Constants, Expressions Conversion Rules Options Strict, Option Explicit Scope of Definition.
Data Types and Expressions
VBA Modules, Functions, Variables, and Constants
Chapter 3.3 Numeric Data Types and Variables. Slide 2 Objectives Create variables to store information while a solution runs Perform computations with.
An Introduction to Programming with C++ Fifth Edition Chapter 4 Chapter 4: Variables, Constants, and Arithmetic Operators.
Data types and variables
An Introduction to Programming with C++ Fifth Edition Chapter 4 Chapter 4: Variables, Constants, and Arithmetic Operators.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Chapter 2 Data Types, Declarations, and Displays
Chapter 3: Introducing the Microsoft.NET Framework and Visual Basic.NET Visual Basic.NET Programming: From Problem Analysis to Program Design.
Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic th Edition.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Variables, Constants, Methods, and Calculations Chapter 3 - Review.
Objectives You should be able to describe: Data Types
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 6 Enhancing the Inventory Application Introducing Variables, Memory Concepts and.
Variables and Constants
Chapter 3: Using Variables and Constants
Programming with Microsoft Visual Basic th Edition CHAPTER THREE USING VARIABLES AND CONSTANTS.
Chapter 6 Understanding the Structure of an Application: Procedures, Modules, and Classes.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Lecture Set 4 Data Types and Variables Part A – Introduction Numeric Data Types.
Arithmetic operations and operators, converting data types and formatting programs for output. Year 11 Information Technology.
Basic Notions Review what is a variable? value? address? memory location? what is an identifier? variable name? keyword? what is a legal identifier? what.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Input, Output, and Processing
Chapter 2: Using Data.
Computer Programming TCP1224 Chapter 4 Variables, Constants, and Arithmetic Operators.
Microsoft Visual Basic 2005 CHAPTER 4 Variables and Arithmetic Operations.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
Operators & Identifiers The Data Elements. Arithmetic Operators exponentiation multiplication division ( real ) division ( integer quotient ) division.
Operators & Identifiers The Data Elements. Arithmetic Operators exponentiation multiplication division ( real ) division ( integer quotient ) division.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Three Memory Locations and Calculations.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Three Using Variables and Constants.
Operators & Identifiers The Data Elements. Arithmetic Operators exponentiation multiplication division ( real ) division ( integer quotient ) division.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
Hungarian Notation A must in this course Every object used MUST be renamed including the form(s) using the following rules Form  frmFormName E.g. frmTemperature.
Programming with Microsoft Visual Basic th Edition
Part:2.  Keywords are words with special meaning in JavaScript  Keyword var ◦ Used to declare the names of variables ◦ A variable is a location in the.
Module B - Computation1/61 Module-B-Computation Variables Basic Memory Operations Expressions.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
CHAPTER THREE Representing Data: Constants and Variables.
Variables and Expressions Programming Right from the Start with Visual Basic.NET 1/e 7.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
Chapter 3: Introducing the Microsoft.NET Framework and Visual Basic.NET Visual Basic.NET Programming: From Problem Analysis to Program Design.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
Chapter 4 Chapter 4: Variables, Constants, and Arithmetic Operators.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are used in programs so that values can be represented with.
Programming with Microsoft Visual Basic 2012 Chapter 3: Using Variables and Constants.
© 2006 Lawrenceville Press Slide 1 Chapter 4 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration statement. For example: Dim.
1Object-Oriented Program Development Using C++ Built-in Data Types Data type –Range of values –Set of operations on those values Literal: refers to acceptable.
Microsoft Visual Basic 2010 CHAPTER FOUR Variables and Arithmetic Operations.
IS 350 Numeric Data Types.
A variable is a name for a value stored in memory.
Arithmetic operations and operators, converting data types and formatting programs for output. Year 11 Information Technology.
Variables and Arithmetic Operations
Lecture Set 4 Data Types and Variables
Data Types and Variables Part D – Common Methods (ToString and Parse)
Variables and Arithmetic Operations
Introduction to Tools, Numeric Data Types and Variables
CIS16 Application Development Programming with Visual Basic
Data Types and Expressions
Presentation transcript:

Chapter 4 Introduction to Numeric Data Types and Variables

Class 4: Numeric Data Types Process numeric data Declare and use variables Create user-defined constants and use expressions Work with numeric data types and convert data between numeric and string data types Define the order in which control instances get input focus

Integral Data Types Integral data types store data that does not have a decimal point Some integral data types can store 0 or positive values Other integral data types can store both positive and negative values –Negative values are indicated by a sign bit –Unsigned data types were new to Visual Studio 2005

Table 4-1: Integral Data Types

Understanding Integral Data Types All integral values are stored as binary numbers The SByte data type stores its data in 8 bits –7 bits store the data –1 bit stores the value's sign The largest possible value is 2^7-1 or 127 The value has the binary pattern

Understanding Integral Data Types (continued) Negative integral values appear in two ’ s compliment format Rules to represent a two ’ s compliment value: –Start with the binary representation of a positive number –Flip each bit 0 values become 1 1 values become 0 –Add one to the number produced in the previous step

Creating a Negative Two ’ s Compliment Value Start with the positive representation of a value Flip each bit Add one to the value from the previous step

Introduction to Floating-point Data Types Floating-point numbers store values with a decimal point –Floating-point numbers are stored in a form of scientific notation One bit is the sign bit A 23-bit mantissa stores the fractional part of a number The exponent is stored in 8 bits

Table 4-3: Floating-point Data Types

Figure 4-4: Representation of a 32- bit Single Precision Value

Rounding Error (Introduction) Floating-point numbers are an approximation of an actual value –1/3 or 2/3 must be rounded, for example Rounding introduces an error called rounding error The greater the precision of the data type, the smaller the rounding error –The Decimal data type has the smallest rounding error and the greatest precision

Performance of Numeric Data Types Performance is a key characteristic of any application Different data types have different performance characteristics –Arithmetic operations using integral data types are faster than operations on floating-point data types –The Decimal data type is very slow

Introduction to the String Data Type Data is often represented as a string of characters –Textual data is represented as a string –Data entered by end users is textual –Strings are used to display output Strings are represented differently than numbers (numeric data types)

Storage of the String Data Type Strings are stored as Unicode characters in two bytes as an unsigned short ( UShort ) The first 127 values store letters, digits, and special characters The values 128 to 255 are for special characters such as keyboard arrows The values 256 to 65,535 are for international characters and diacritical marks

Figure 4-7: Representation of a Unicode string

Introduction to Value Types and Reference Types A data type can be characterized as a value type or a reference type –Value types store data in the memory allocated to the variable –Reference types store a 32-bit memory address

Value Types All value types derive from the System.ValueType class Integral and floating-point data types are value types

Figure 4-8: Storage of value types

Reference Types All reference type variables are 32 bits in size The value stored in a reference type variable is a memory address This memory address points to the memory allocated to the actual data –Thus, the term pointer is often used to describe a reference type

Figure 4-9: Storage of reference types

Introduction to Variables A variable stores data while an application runs –The process of creating a variable is called declaring a variable –A variable has a name (identifier) The naming rules for variables and procedures are the same –A variable has a data type

Variable Characteristics All variables have three characteristics –A variable has a lifetime –A variable has a scope –A variable has accessibility

Variable Lifetime Variable lifetime refers to the period of time that a variable exists –A variable with local lifetime exists only while a procedure executes –A variable with a module-level lifetime exists while a class instance exists or a module is loaded

Variable Scope and Accessibility Variable scope refers to the statements that can use a variable Variables declared inside a procedure with the Dim statement have local scope Variables declared outside a procedure with the Private statement have module-level scope

Declaring a Local Variable [Dim | Static] varname As type [=initexpr] –The Dim keyword declares a local variable The variable and its value are destroyed when the procedure ends –The Static keyword declares a local variable The variable and its value persist from one procedure invocation to the next –varname contains the name (identifier) of the variable –type defines the variable ’ s data type –initexpr is used to initialize the variable ’ s value

Initializing Variables Variables can be declared and initialized in the same statement Example to declare a variable named CurrentYear and initialize its value to 2006: Dim CurrentYear As Integer = 2006

Common Initialization Errors Numeric initialization values cannot contain formatting characters The following statements are illegal: Dim Value1 As Double = 100, Dim Value2 As Double = $100,000.52

Declaring Multiple Variables in One Statement Multiple variables can be declared in the same statement Separate each declaration with a comma as follows: Dim IntegerValue As Integer, _ DoubleValue As Double If variables have the same data type, the following shorthand notation can be used: Dim IntegerValue1, IntegerValue2 As Integer

Naming Conventions (Description) Hungarian notation –Use a prefix to denote the data type followed by a descriptive name Pascal case –Use whole words –Capitalize the first letter of each word Camel case –Use whole words –Use lower case for the first letter of the first word –Capitalize the first letter of each remaining word

User-defined Constants Constants are similar to variables The value of a constant does not change while an application runs –Trying to assign a value to a constant will cause an error Use the Const statement to declare a constant Constants are typically declared at the module-level

User-defined Constant (Example) Declare a constant to store the value of PI Private Const PI_VALUE As Single _ = Declare a constant to store the value of PI multiplied by 2 Private Const PI_VALUE As Single _ = PI_VALUE * 2

Introduction to Expressions Variables can be used in assignment statements along with object properties Examples: Dim Result As Integer Dim Example As Integer = 4 Result = 3 Result = txtExample.Height Result = Example

Common Expression Errors Values on the right and left sides of an assignment statement must have the same data type The Font and Integer data types are not compatible so the following statements will cause an error: Dim SomeInteger As Integer SomeInteger = txtExample.Font

Parts of an Expression Operators –Arithmetic operators such as (+, -, *, /, ^, \) –Comparison and logical operators Operands –Literal values –Object properties –Constants –Variables

Operator Precedence Operators have an evaluation order called precedence –The Visual Basic precedence rules are the same as the algebraic precedence rules –Use parentheses to override the default precedence rules –Use parentheses to clarify evaluation order Extra parentheses do no harm

Table 4-5: Operators and Precedence

Arithmetic Operators (Example) Divide 10 by 5 and multiply the intermediate result by 100 The value 200 is stored in Result Dim Numerator As Double = 10 Dim Denominator As Double = 5 Dim Result As Double Result = Numerator / Denominator * 100

Integer Division The result of an integer division operation is an integral value The result is truncated rather than rounded Examples: Result = 4 \ 3 ' 1 Result = 5 \ 2 ' 2 Result = 10 \ 6 ' 1

The Mod Operator The Mod operator calculates the Integer remainder of a division operation –The operation is the same as the remainder resulting from a long division operation Examples: Result = 5 Mod 2 ' 1 Result = 4 Mod 2 ' 0

Operator Precedence Arithmetic operators are applied in a default order known as precedence –Exponentiation, multiplication and division, addition and subtraction Use parentheses to change the default precedence order

Figure 4-11: Evaluation Order with and without Parenthesis

Numeric Data Types and Type Conversion Type conversion is used to convert data from one data type to another How type conversion is performed depends on whether strict type checking is enabled or disabled –If strict type checking is enabled, less restrictive types will not be implicitly converted to more restrictive types –Strings will not be implicitly converted to numeric data types

Strict Type Checking Rules Widening type coercion allows more restrictive types to be implicitly converted to less restrictive types –Integral data types will be converted to floating-point types –Integer to Single is legal, for example –Single to Double is legal –Double to Integer is not legal

Enabling Strict Type Checking The Option Strict statement enables or disables strict type checking The Option Strict statement must appear at the beginning of a module Enable strict type checking to prevent hard to find type conversion errors Example: Option Strict On Option Strict Off

Enforcing Explicit Variable Declaration Explicit variable declaration requires variables to be declared before they are used –Explicit variable declaration is enabled, by default Use the Option Explicit statement to enforce explicit variable declaration Example: Option Explicit On Option Explicit Off

Performing Explicit Type Conversion The members of the System.Convert class explicitly convert data from one type to another Methods exist for each primary data type Example: Dim DoubleValue1 As Double = Dim IntegerResult As Integer IntegerResult = _ System.Convert.ToInt32(DoubleValue1)

Explicit Type Conversion Methods ToInt16, ToInt32, and ToInt64 convert the argument to an integral value ToDecimal converts the argument to the Decimal data type ToDouble and ToSingle convert the argument to floating-point data types ToString converts the argument to a string

Formatting Output Strings The ToString method accepts an argument used to format numeric data –Visual Studio supports named formats to supply common formatting Currency, for example –Predefined formats can be created with format specifiers –Custom formats can be created with placeholder characters

Table 4-6: Format Specifiers

Table 4-7: Placeholder Characters

Table 4-8: Format Strings

The Imports Statement Use the Imports statement to eliminate the need for fully qualified references to method names The Imports statement appears after the Option Explicit and Option Strict statements It ’ s possible to import any number of namespaces or classes The order in which Imports statements appear is not significant Types can also be imported using the Project Properties dialog box

Imports Statement (Example) Import the System.Convert class Option Explicit On Option Strict On Imports System.Convert Public Class frmMain ' statements End Class

Figure 4-14: Project Properties Dialog Box

The FV Function The FV function calculates the future value of an investment The first argument contains the interest rate The second argument contains the number of periods The third argument contains the amount of the periodic payment The optional fourth argument contains the present (initial) value of the investment The optional fifth argument defines whether payments are made at the beginning or end of the period

The FV Function (Example) Calculate the future value of $1, for 12 periods at 1% per period Dim MonthRate As Integer = 0.01 Dim MonthTerm As Integer = 12 Dim InitialValue As Single = Dim FutureValue As Double FutureValue = FV(0.01, 12, 0, 1000) FutureValue = FV (MonthRate, MonthTerm, 0, _ InitialValue)

The TextBox Control (Introduction) The TextBox control gets input and displays output –The control derives from the TextBoxBase class –Other textual controsl include the MaskedTextBox and RichTextBox controls

The TextBox Control (Properties) The BorderStyle property defines the style of the border The ForeColor and BackColor properties define text and background colors The Enabled property defines whether the control instance can get input focus The ReadOnly property controls whether the text in the control instance can be copied to the clipboard The MultiLine property defines whether text will appear on multiple lines The maximum number of characters is defined in the MaxLength property

The TextBox Control (Properties, continued) The ScrollBars property defines whether scroll bars appear –Scroll bars only appear when the MultiLine property is True The Text property stores the visible text The TextAlign property defines how the text is aligned in the control instance The size and position is defined by the X, Y, Height, and Width properties

The TextBox Control (Methods and Events) The Focus method is used to set input focus to a text box The Enter event fires when the control instance gets focus The Leave event fires when the control instance loses focus

Introduction to Tab Order Every form has exactly one active control instance at run time –This is the control instance having input focus The order in which control instances get focus is called the tab order –The tab order is set using the TabIndex property –The tab order can also be set using a visual designer

Figure 4-14: Setting the tab order