Variables, Constants, and Calculations

Slides:



Advertisements
Similar presentations
Lecture Set 4 Data Types and Variables Part B – Variables, Constants, Expressions Conversion Rules Options Strict, Option Explicit Scope of Definition.
Advertisements

Chapter 3 Variables, Constants, and Calculations Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Variables, Constants, and Calculations. Data — Variables and Constants (1 of 2) Variable  Memory locations that hold data that can be changed during.
1.
Chapter 3 Variables, Constants, and Calculations
Data types and variables
Chapter 2 Data Types, Declarations, and Displays
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Copyright © 2001 by Wiley. All rights reserved. Chapter 3: Variables, Assignment Statements, and Arithmetic Variables Assignment Statements Arithmetic.
Chapter 3 Variables, Constants, and Calculations Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
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.
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.
Chapter 3 Variables, Constants, and Calculations Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Variables and Constants
McGraw-Hill © 2009 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 3 Variables, Constants, and Calculations.
McGraw-Hill © 2009 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 3 Variables, Constants, and Calculations.
06/10/ Working with Data. 206/10/2015 Learning Objectives Explain the circumstances when the following might be useful: Disabling buttons and.
Chapter 3 Part 11 Variables, Constants, and Calculations Chapter 3 Section 3.3 Chapter 3 Section 3.4.
3-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Arithmetic operations and operators, converting data types and formatting programs for output. Year 11 Information Technology.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 2 Input,
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.
Chapter 2: Using Data.
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.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Chapter 3 P. 1 Data - Variables and Constants Definition A variable is a value which can change during program execution. A constant is a value which can.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Chapter 3 Variables, Constants and Calculations Programming In Visual Basic.NET.
Variables & Function Calls. Overview u Variables  Programmer Defined & Intrinsic  Data Types  Calculation issues u Using Functions  The val() function.
Chapter 2 Variables.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Three Memory Locations and Calculations.
Chapter 3 w Variables, constants, and calculations DIM statements - declaration temporary memory locations identifier, data type, scope data types - values.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
Variables and Constants Variable Memory locations that hold data that can be changed during project execution Example: a customer’s name Constant Memory.
Data Tonga Institute of Higher Education. Variables Programs need to remember values.  Example: A program that keeps track of sales needs to remember.
1 Chapter 3 – Examples The examples from chapter 3, combining the data types, variables, expressions, assignments, functions and methods with Windows controls.
3-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Programming with Microsoft Visual Basic th Edition
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
110 E-1 Variables, Constants and Calculations(2) Chapter 3: Operations on variables, scope of a variable, formatting data Doing Arithmetic.
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.
Making Interactive Programs with Visual Basic .NET
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.
Instructors: Sidra Ehsan Budoor Bawazeer CpCS 206.
© 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.
Microsoft Visual Basic 2010 CHAPTER FOUR Variables and Arithmetic Operations.
A variable is a name for a value stored in memory.
Chapter 2 Variables.
Arithmetic operations and operators, converting data types and formatting programs for output. Year 11 Information Technology.
BASIC ELEMENTS OF A COMPUTER PROGRAM
Variables and Arithmetic Operations
Variables, Expressions, and IO
Variables and Arithmetic Operations
CIS16 Application Development Programming with Visual Basic
Chapter 2 Variables.
Brief description on how to navigate within this presentation (ppt)
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 1/15/2019.
Chapter 2 Variables.
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 7/9/2019.
Brief description on how to navigate within this presentation (ppt)
Presentation transcript:

Variables, Constants, and Calculations Chapter 3 Variables, Constants, and Calculations McGraw-Hill Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.

Variables If you were told: X = 5 and Y = 10 and answer = x + y What would answer equal? Answer = 15

Variables Constant – this number cannot change while the pgm runs If you were told: r=10 and areaCircle = 3.14 * r ^2 What would areaCircle equal? Variable – the value can vary. Answer = 314

Circle Area in VB code Const PI as Double = 3.1415R ‘declare constants before variables ‘the R means the number is a double Dim dblR as Double Dim dblCircleArea as Double dblR = 10 dlbCircleArea = PI * dblR ^ 2

Declaring Variables Declared inside a procedure using a Dim statement Declared outside a procedure using Private Always declare the variable’s data type. Inside a procedure you must use the Dim statement. Declaration Statements—General Form: Public|Private|Dim Identifier [As Datatype]

Declaration Statement Examples Dim strCustomerName As String Private intTotalSold As Integer Dim sglTemperature As Single Dim decPrice As Decimal Private decPrice VB’s IntelliSense feature helps you enter Private, Public, and Dim statements—after you type the space that follows VariableName As, a list pops up and displays the possible entries for data type to complete the statement. If you begin to complete the statement the list automatically scrolls to the correct section; when the correct entry is highlighted press Enter, Tab, or the spacebar to select the entry, or double-click if using the mouse. The reserve word Dim is really short for dimension, which means size. When declaring a variable, the amount of memory reserved depends on its data type.

Data Types Common ones will be circled Data Type Use For Storage Size in bytes Boolean True or False value 2 Byte 0 to 255, binary data 1 Clear Single Unicode character Date 1/1/0001 through 12/31/9999 8 Decimal Decimal fractions, such as dollars/cents 16 Single Single precision floating-point numbers with six digits of accuracy 4 Double Double precision floating-point numbers with 14 digits of accuracy Short Small integer in the range -32,768 to 32,767 Integer Whole numbers in the range -2,147,483,648 to +2,147,483,647 Long Larger whole numbers String Alphanumeric data: letters, digits, and other characters Varies Object Any type of data The data type of a variable or constant indicates what type of information will be stored in the allocated memory space. The data type charts displays the kind of data each type of data types hold, and the amount of memory allocated. The most common types of variables and constants are String, Integer, and Decimal.

Naming Variables and Constants Use camelCase & prefixes for variables (intQuantity) and UPPERCASE for constants (GST, PI) Cannot use reserved words or keywords to which Basic has assigned a meaning, such as print, name, and value Meaningful names consisting of letters, digits, and underscores; must begin with a letter and no spaces or periods. Include class (data type) of variable (variable: countInteger constant: QUOTA_Integer) A programmer has to name (identify) the variables and named constants that will be used in a project.

Type casting Dim intHeight as integer intHeight = 6.7 intHeight will now equal 7. It cannot hold a decimal value since it was declared type integer It will automatically be cast (rounded) to a whole number

Constants Named User assigned name, data type, and value Use CONST keyword to declare. Intrinsic System defined within Visual Studio (Color.Red) Const COMPANY_ADDRESS As String = "101 S. Main Street" Const SALES_TAX_RATE As Doublel = .08R Constants provide a way to use words to describe a value that doesn’t change. Constants are declared using the keyword and are given a name, a data type, and a value. Once a value is declared as a constant, its value can’t be changed during the execution of the project. Data type declared and data type of the value must match. Many sets of intrinsic constants (key term) are declared in system class libraries and are available for use in VB programs.

Assigning Values to Constants Declare the data type of numeric constants by appending a type- declaration character. Decimal D Decimal – 850.50D Double R Double – 52875.8R Integer I Integer – 12345678I Long L Long – 134257987L Short S Single F Single – 101.25F If a type-declaration character is not appended, any whole number is assumed to be Integer and any fractional value is assumed to be Double. Use two quotes with a string literal to avoid confusion.

Scope and Lifetime of Variables (1 of 2) Visibility of a variable is its scope. Scope may be Namespace Module level Local Block level Lifetime of a variable is the period of time the variable exists. A variable may exist and be visible for an entire project, for only one form, or for only one procedure. Visibility really means “this variable can be used or ‘seen’ in this location.” Namespace — Available to all procedures of project Module — Available to all procedures within that module (often a form) Use Public or Private keywords Local — Available only to the procedure in which it is declared Block — Available only in block of code inside a procedure where declared Previous versions of VB and some other programming languages refer to namespace variables as global variables.

Module Level Variable Declaration Example Code module-level declarations in the Declaration section at the top of the code. To enter module-level declarations, you must be in the Editor window at the top of your code. Place the Private and Const statements after the Class declaration but before your first procedure.

Calculations Calculations can be performed with variables, constants, properties of certain objects, and numeric literals. Do not use strings in calculations. Values from Text property of Text Boxes Are strings, even if they contain numeric data Must be converted to a numeric data type before performing a calculation

Getting Input from a text box intHeight = txtHeight.Text The above line works fine assuming that the user will not input anything except an integer. If they do, the program will crash.

Text changed procedures If a calculation is performed and results outputted due to a textbox value, then if the value in that textbox is changed, the result label should be cleared, along with anything else on the interface that corresponds to the now non-existing textbox text property. Me.lblResult.Text=““

Got Focus When a text box receives the focus, the text inside the box should become selected, awaiting the user’s new input. txtNumber.SelStart =0 txtNumber.SelLength=Len(txtNumber)

Mod and div There is a video in Moodle explaining these two types of INTEGER division. When you divide 2 integers (not real numbers), you get a remainder (mod) and a dividend (div  \). Examples: 11 / 4 = 2 remainder 3 therefore: 11 mod 4 = 3 11 \ 4 = 2

debugging Now that you are performing calculations, you will need to learn how to debug your programs when the results are not what you expected them to be. There will be a video on moodle for an explanation on how to add breakpoints and step through your code.

Debugging with breakpoints There will be times when you program is not producing the desired output. These logic errors can be tracked down using breakpoints. Add the breakpoints by clicking at the left of the line of code where you want to start debugging, and a red dot will appear. When the program halts on this line, right click on the variable in question to add a watch Click step into and continue stepping through your program, watching the values as your program runs. Clicking the dot will remove the breakpoint

Unexpected input from user If you ask the user for a number, and they input something that isn’t a number, your program will crash (halt execution). Use the val function to convert non-numeric characters to a zero to keep the program from crashing. IintHeight=val(Me.txtHeight.Text) The val function will convert the retrieved string to a 0 if it begins with anything except an integer

Arithmetic Operations Operator Operation + Addition – Subtraction * Multiplication / Division \ Integer Division Mod Modulus – Remainder of division ^ Exponentiation The arithmetic operations you can perform in VB include addition, subtraction, multiplication, division, integer division, modulus, and exponentiation. The first four operations are self explanatory, but you may not be familiar with Integer Division, Modulus, and/or exponentiation. Integer division — use to divide one integer by another giving an integer result, truncating (dropping) any remainder Modulus — returns the remainder of a division problem Exponentiation — raises a number to the power specified and returns (produces) a result of the Double data type.

Order of Operations (BEDMAS) Hierarchy of operations, or order of precedence, in arithmetic expressions from highest to lowest 1. Any operation inside parentheses 2. Exponentiation 3. Multiplication and division 4. Integer division 5. Modulus 6. Addition and subtraction To change the order of evaluation, use parentheses.

Using Calculations in Code Perform calculations in assignment statements. What appears on right side of assignment operator is assigned to item on left side. Assignment operators — allows shorter versions of code =, +=, -=, *=, /=, \=, &= ‘Accumulate a total. TotalSalesDecimal += salesDecimal The assignment operators that you will use most often are += and – =.

Rounding Numbers Round decimal fractions Decimal.Round method returns a decimal result rounded to a specified number of decimal positions. Decimal.Round and Convert methods use technique called “rounding toward even.” Decimal Value to Round Number of Decimal Positions Results 1.455 2 1.46 1.445 1.44 1.5 2.5 See the Appendices for additional mathematical, financial, and string functions Example: ' Round to two decimal positions. ResultDecimal = Decimal.Round(AmountDecimal, 2)

Formatting Data for Display To display numeric data in a label or text box, first convert value to string. Use ToString method Format the data using formatting codes. Specifies use of dollar sign, percent sign, and commas Specifies number of digits that appear to right of decimal point DisplayTextBox.Text = NumberInteger.ToString() When wanting to display numeric data in the Text property of a label or text box, the value must first be converted to string—the data can be formatted, which controls the way the output will look.

Using Format Specifier Codes "C" code Currency — String formatted with dollar sign, commas separating each group of 3 digits and 2 digits to the right of decimal point "N" code Number — String formatted with commas separating each group of 3 digits and 2 digits to the right of decimal point Can specify number of decimal positions Example: "C0" zero digits The format specifier codes format the display of output and are predefined. The default format of each of the formatting codes is based on the computer’s regional setting. Format specifier codes are displayed on the next slide (Slide 30) and examples are shown on the following slide (Slide 31).

Format Specifier Codes Name C or c Currency F or f Fixed-point N or n Number D or d Digits P or p Percent

Format Specifier Code Examples Variable Value Code Output totalDecimal 1125.6744 "C" $1,125.67 "N0" 1,126 pinInteger 123 "D6" 000123 rateDecimal 0.075 "P" 7.50% "P3" 7.500% "P0" 8% valueInteger -10 ($10.00)

Date Specifier Code Format DateTime values using format codes and ToString method. You can use methods of the DateTime structure for formatting dates:ToLongDateString, ToShortDateString, ToLongTimeString, ToShortTimeString. See Appendix B or MSDN for additional information.

Counting and Accumulating Sums Declare module-level variables, since local level variables reset to 0 each time the procedure is called. Summing Numbers Counting Calculating an Average dblTotal += dblItemPrice Private intCounter As Integer intCounter += 1 Programs often need to calculate the sum of numbers. The technique for summing is to declare a module-level variable for the total. If you want to count something, you need another module-level variable. To calculate an average, divide the sum of the items by the count of the items. dblAverage = dblTotal / intCounter

App deployment When your wonderful program is ready for the world, you can deploy it by publishing it to an URL, FTP location, or a space on your file server. There is a wizard to guide you

Assignments and practice Case Study, LVP Book Hands on Programming Example, Ch 3, Bradley Pizza Cost, LVP Change, LVP DigitsofaNumber International Lennies Bail Bonds, 3.2 Bradley Recording Studio, 3.4 Bradley Car Rental, 3.7 Bradley Video Bonanza 3