Chapter 3 Variables, Assignment Statements, and Arithmetic.

Slides:



Advertisements
Similar presentations
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Advertisements

Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
1.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
IMS1906 Programming in VB.NET Week 3 – Lecture 1 Application Development © Angela Carbone Monash University School of Information Management.
JavaScript, Third Edition
Copyright © 2001 by Wiley. All rights reserved. Chapter 1: Introduction to Programming and Visual Basic Computer Operations What is Programming? OOED Programming.
Copyright © 2001 by Wiley. All rights reserved. Chapter 3: Variables, Assignment Statements, and Arithmetic Variables Assignment Statements Arithmetic.
Variables & Math Operators CE 311 K - Introduction to Computer Methods Daene C. McKinney.
Variables, Constants, Methods, and Calculations Chapter 3 - Review.
Variables and Constants
Learning Objectives Data and Information Six Basic Operations Computer Operations Programs and Programming What is Programming? Types of Languages Levels.
Microsoft Excel Diane M. Coyle Spring 2009 CS 105.
3-1 Chapter 3 Variables, Assignment Statements, and Arithmetic.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
06/10/ Working with Data. 206/10/2015 Learning Objectives Explain the circumstances when the following might be useful: Disabling buttons and.
Chapter 4: The Selection Process in Visual Basic.
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?
Input, Output, and Processing
 Application – another name for a program.  Interface – is what appears on the screen when the application is running.  Program Code – is instructions.
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.
Variables & Function Calls. Overview u Variables  Programmer Defined & Intrinsic  Data Types  Calculation issues u Using Functions  The val() function.
Chapter One An Introduction to Programming and Visual Basic.
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.
1 Chapter 3 – Examples The examples from chapter 3, combining the data types, variables, expressions, assignments, functions and methods with Windows controls.
Pay Example (PFirst98) Please use speaker notes for additional information!
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
Lesson 4 Mathematical Operators! October 6, 2009.
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 4 Working with Variables, Constants, Data Types, and Expressions.
CECS 5020 Computers in Education Visual Basic Variables and Constants.
110 E-1 Variables, Constants and Calculations(2) Chapter 3: Operations on variables, scope of a variable, formatting data Doing Arithmetic.
Variables and Expressions Programming Right from the Start with Visual Basic.NET 1/e 7.
Controlling Program Flow with Decision Structures.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
Visual Basic.NET Programming for the Rest of Us Keith Mulbery Utah Valley State College.
Creation of Variables with Numeric, alphanumeric, date, picture, memo data types Constant - A quantity that does not change during the execution of a program.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
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.
© 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.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Microsoft Visual Basic 2010 CHAPTER FOUR Variables and Arithmetic Operations.
Egyptian Language School Computer Department
A variable is a name for a value stored in memory.
Topics Designing a Program Input, Processing, and Output
Arithmetic operations and operators, converting data types and formatting programs for output. Year 11 Information Technology.
An Application Uses Variables to Hold Information So It May Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use.
Variables and Arithmetic Operations
Variables and Arithmetic Operations
Introduction to C++ Programming
Visual Basic Programming Chapter Four Notes Working with Variables, Constants, Data Types, and Expressions GROUPBOX CONTROL The _____________________________________.
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 1/15/2019.
Chapter One: An Introduction to Programming and Visual Basic
CHAPTER FOUR VARIABLES AND CONSTANTS
Topics Designing a Program Input, Processing, and Output
Introduction to Programming
Topics Designing a Program Input, Processing, and Output
Visual Basic Numbers Chapter 3.3 Prepared By: Deborah 7/9/2019.
Introduction to Computer Programming IT-104
Presentation transcript:

Chapter 3 Variables, Assignment Statements, and Arithmetic

Learning Objectives Declare and use different types of variables in your project. Use text boxes for event-driven input and output. Use a four-step process to write code for event procedures Write Visual Basic instructions to carry out arithmetic operations. Describe the hierarchy of operations for arithmetic. Understand how to store the result of arithmetic operations in variables using assignment statements. Use comments to explain the purpose of program statements. Discuss using Visual Basic functions to carry out commonly used operations. Use command buttons to clear text boxes, print a form with the PrintForm method, and exit the project. Describe the types of errors that commonly occur in a Visual Basic project and their causes.

Variables Variables are named locations in memory (memory cells) in which we store data that will change at run time Variable names in VB:**** –Must begin with letter and can use 0-9 in name –Can’t include period, but can contain an underscore –Can’t be over 255 characters –Not case-sensitive, but suggest using upper and lower case Example mnemonic variable names –sngProfit_Margin for Profit margin**** –curTaxes for taxes on this price –curAmountDue for sum of price and taxes –curYTDEarnings for year to date earnings

Data Types Two primary types of data: numeric and string Numeric data can be used in arithmetic operations – are all numeric constants String data should not be used in arithmetic – “Dogs” “ ” “Dr. Brown” are all string constants Numeric data types can be subdivided into specific types: –currency $55,567.78integer 255 –single long (integer) 35,455 –double Boolean True or False**

Data Types (cont) String - stores ASCII symbols (text) and numbers that are not used in mathematical operations, but rather to provide for the input, output, and manipulation of sets of characters Integers - whole numbers (-32,768 to 32,767) Long Integers - whole numbers (-2,147,483,648 to 2,147,483,647 Single - fractional numbers to seven significant digits Double - fractional numbers to 15 significant digits

Data Types (cont) Currency - use with monetary amounts and up to four digits to the right of the decimal Date - use with dates Boolean - use only when the value of a variable is True or False Variant - variable is assigned this type automatically if you don’t declare the variable as a specific data type, but takes up more memory

Variable Prefixes Variable TypePrefix Stringstr Integerint Long Integerlng Singlesng Doubledbl Currencycur Datedtm Booleanbln

Advantages of Coding Prefixes Standard allows anyone who reads the code to immediately determine data type of variable Words that are normally reserved words can be used, i.e. strPrint Different objects can practically same name, i.e lblAge (label), or txtAge (text box)

Declaring Variables Declare ALL variables with the DIM statement **** General form: –Dim Variable1 as type1, variable2 as type2, etc. For example, –Dim strHerName as String, sngMyValue as Single –Dim curMyIncome as Currency, curPrice as Currency –Dim curAmountDue as Currency Two or more variables can be declared with same Dim statement but you must include the variable type If you fail to declare a variable after the Option Explicit statement has been entered, an error occurs at Run time Use variables rather than objects in processing since all textboxes are strings

The Option Explicit Statement Begin ALL Forms with the Option Explicit command in the declarations procedure of the general object. This forces all variables to be declared**** You may have to correct variable statements in your test! To automatically include Option Explicit, go to the Tools|Options|Editor menu selection and check the box for “Require variable declaration”

Event-driven Input In VB, we often use event-driven input where data is transferred from text boxes to variables by an event **** The user, not the program controls the sequence of events Use an assignment statement to do this:. : An assignment statement gives a variable a value by setting it equal either to an existing quantity or to a value that can be computed by the program Control property or variable = value, variable, or property Only variables or controls can be on left of the = sign statement while the value, variable or property is on the right of the = sign

Comments To explain the purpose of a statement, a comment statement is added Any statement beginning with an apostrophe or REM is a comment Comments can be added before statements or at the end of statements by using an apostrophe

VB Code Box 3-1 Code to Input Two Numbers Private Sub cmdSum_Click ’ Declare variables Dim intFirst as Integer, intSecond as Integer Dim intSum as Integer ’ Assign values to variables intFirst = txtFirstNum.Text intSecond = txtSecondNum.Text End Sub

Functions Function - an built -in operation that takes one or more more arguments and returns a a single value A Common form of a function is variable=functionname(argument1, argument2 ….) Not all functions require arguments such as the Date function The VAL() function is very common and is used to convert the Text property from a string to a number, which is assigned to Numeric variable

Using Functions (cont) You can’t use text boxes to do computations because the default property, Text, is a string and therefore must be converted to a numeric value before a calculation is performed. It is necessary to convert the results of the computation that will appear in another text box to a string value, using the Str() function, otherwise you would be assigning an integer value to it Example functions for converting data: –Val to convert a string to a number –Str to convert a number to a string

Commonly Used Conversion Functions Conversion Function Purpose CBoolConvert argument to Boolean CCurConvert argument to Currency CDateConvert argument to Date CIntConvert argument to Integer CSngConvert argument to Single CDblConvert argument toDouble

Assignment Statements Must convert strings in text boxes to numeric with Val function, eg, –curPrice = Val(txtPrice) Convert numeric variables to strings before assigning to text box, eg, –txtAmountDue = str(curAmountDue) Carry out calculations with assignment statements, eg, –curTaxes = 0.07*Price –curAmountDue = curPrice + curTaxes

VB Code Box 3-2 Use Val() Function in Inputting Numbers Private Sub cmdSum_Click() ’ Declare variables Dim intFirst as Integer,intSecond as Integer Dim intSum as Integer ’ Assign values to variables as number intFirst = Val(txtFirstNum.Text) intSecond = Val(txtSecondNum.Text) End Sub

VB Code Box 3-3 Code for cmdSum Command Button Private Sub cmdSum_Click() ’Declare variables Dim intFirst as Integer, intSecond as Integer Dim intSum as Integer ’Assign values to variables as a number intFirst = Val(txtFirstNum.Text) intSecond = Val(txtSecondNum.Text) intSum = intFirst + intSecond ’Calculate sum txtSum.Text = Str(intSum) ’display sum in sum text box End Sub

Properties Versus Methods The dot notation method is the way properties are set at run time. Syntax: object. property= value E.g. txtSum.Text=Str(intSum) The same notation is used to invoke a method for a control. Methods define the actions a control can carry out. Syntax: object.method E.g. txtFirstNum.SetFocus The SetFocus method shifts the cursor to the named text box Methods can’t be used in assignment statements

VB Code Box 3-4 Code for cmdClear Command Button Private Sub cmdClear_Click() ’Clear text boxes with empty string txtFirstNum.Text = "" txtSecondNum.Text = "" txtSum.Text = "" txtFirstNum.Setfocus ’Set focus back to first text box End Sub

Using Assignment Statements for Calculations An expression is a combination of one or more variables and/or constants with operators A constant is a quantity that does not change Operators are symbols used for carrying out processing

Arithmetic Operators **** () for grouping + for addition ^ for exponentiation - for subtraction - for negation * for multiplication / for division \ for integer division (divisor and dividend are rounded to 0) Example \1.95= 7\2 =3 mod for modulus Example \1.95= 7\2 =3 with 1 remainder

Hierarchy of Operations **** Operations within parentheses ( ) Exponentiation (^) Negation (-)' Multiplication and division (*,/) Integer division (\) Modulo arithmetic (Mod) Addition and subtraction (+,-) String concatenation (&) ****Make sure you know this!!!

Arithmetic Example 3 * (Salary - Taxes)^2 + Bonus/Months (order) Order 1Subtract Taxes from Salary 2Square the result 3Multiply this result by 3 4Divide Bonus by Months 5Subtract result from first expression ****You will see something like this again!

String Operators For String Variables the only valid operation is that of combining two strings into one**** Use + or & to combine them Example: strBigday = “Christmas” + “ Day” strBigday = “Christmas” & “ Day” Result of above is Christmas Day

Symbolic Constants We can assign a name to a constant with the Const statement Syntax: Const constant name as variable type = value Examples Const sngIntRate as Single = 0.07 Const intNumYears as Integer=12 Const sngIntRate as Single=0.07,intNumYears as Integer=12

Formatting Data To display information in a pleasing form, we can use the Format function: variable or control = Format(variable, “format expression”) Where the format expressions are in quotes and include; –Currency –Fixed –Standard –Percent –Scientific Example: txtTaxes.Text = Format(curTaxes, “currency”)

Variations of the Format Command FunctionDescription FormatCurrencyExpression formatted as currency along with currency symbol FormatDateTimeExpression formatted as a date or time FormatNumberExpression formatted as a number FormatPercentExpression formatted as a percentage with a trailing % character RoundRounds a number a specified number of decimal places

Print Form, Clearing Entries and Setting Focus Create a command button called cmdPrint To print the form, use the PrintForm command in the cmdPrint click event _________________________________ Create a command button called cmdClear To clear a text boxes, set them equal to the null string “” To set the focus to a text box, use the Setfocus method For example, txtCustName.SetFocus sets focus to this textbox

Coding the Exit Button and Giving User Ability to Use Control Keys Create Exit button called cmdExit In the click event enter this line of code END User can also activate the click event from the keyboard by using the CTRL Key and underlined letter if the caption has an “&” before the applicable letter Example E&xit for the Exit command button

Pseudocode to Compute and Output Taxes and Amount Due Begin Procedure Calculate Input customer name Input video name Input video price Taxes = video price times tax rate Amount due = video price + taxes Output taxes Output amount due End procedure

VB Code Box 3-5 Code for Calculate Button Private Sub cmdCalc_Click() ’Declare constant and variables Const sngTaxRate as Single = 0.07 ’Use local tax rate Dim curPrice As Currency, curAmountDue As Currency Dim curTaxes As Currency Price = CCur(TxtVideoPrice.Text) Taxes = Price * TaxRate ’calculate taxes AmountDue = Price + Taxes ’calculate amount due ’Display taxes and amount due in text boxes as strings txtTaxes.Text = Str(Taxes) txtAmountdue.Text = Str(AmountDue) End Sub

VB Code Box 3-6 Code to Compute and Display Taxes and Amount Due Private Sub cmdCalc_Click() Const sngTaxRate as Single = 0.07 'Use local tax rate Dim curPrice As Currency, curAmountDue As Currency Dim curTaxes As Currency Price = CCur(txtVideoPrice.Text) Taxes = curPrice * sngTaxRate 'Compute taxes curAmountDue = curPrice + curTaxes 'Compute amount due 'Format text boxes as currency txtTaxes.Text = Format(curTaxes, "Currency") txtAmountDue.Text = Format(curAmountDue, "Currency") txtVideoPrice.Text = Format(curPrice, "Currency") End Sub

VB Code Box 3-7 Code to Clear Entries in cmdClear Command Button Private Sub cmdClear_Click() ‘Clear all text boxes txtCustName.Text = "" txtVideoName.Text = "" txtVideoPrice.Text = "" txtTaxes.Text = "" txtAmountDue.Text = "" txtCustName.SetFocus ‘set focus to this text box End Sub

Using Other Arithmetic Functions Other useful functions include –Abs for absolute valueSqr for square root –FV for future valuePV for present value –IRR for internal rate of returnPmt for payment –UCase/LCase to convert to upper/lower case –Len for length of a string –Date for the system date –DateValue for the date corresponding to string argument We will use Pmt to compute the monthly payment –MonPay = Pmt(rate, Nper,-LoanAmt ) –Pmt(.08/12,60,-10000) = $256.03

Creating a Monthly Payment Calculator Assume you wanted to determine the monthly payment necessary to pay off a loan at a given interest rate in some number of months Use PMT function PMT(rate, nper, pv) where –rate = monthly interest rate –nper = number of months –pv = negative value of loan amount

The Monthly Payment Form

VB Code Box 3-8 Code to Compute Monthly Payment Private Sub cmdCompute_Click() ‘Declare variables Dim curAmount As Currency, intMonths As Integer Dim sngRate As Single Dim curPayment As Currency ‘Convert variables in text boxes curAmount = CCur(txtAmount.Text) intMonths = CInt(txtMonths.Text) ‘Calculate monthly interest rate sngRate = (CSng(txtRate.Text) / 100) / 12 ‘Calculate payment curPayment = Pmt(sngRate, intMonths, -curAmount) txtPayment.Text = Format(curPayment, "Currency") txtAmount.Text = Format(curAmount, "Currency") End Sub

Visual Basic Errors **** Most mistakes that happen while using VB are a result of human error - not hardware error **** VB will NOT automatically detect and alert you to all errors!! Syntax errors: caused by incorrect grammar, vocabulary, or spelling. Also caused by using a keyword. Usually caught as you enter the statement. These are pointed out by VB and are usually easy to find and correct.

Visual Basic Errors (con’t) Run time errors: errors not caught at entry but which involve an incorrect statement or bad data, eg, dividing by zero. The presence of an error is detected by VB when you run the program, but you still have to find the source of the error. More difficult to correct than syntax errors Logic errors: those that are VB does not catch as being “wrong”, but which involve erroneous logic, say, only having a program include 11 months of data instead of 12. These are the hardest to find! Debugging is the process of finding and correcting program errors. ****