Chapter 3 Data Types, Variables, and Expressions

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

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.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
JavaScript, Third Edition
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.
Chapter 3 - VB 2008 by Schneider1 Chapter 3 – Variables, Input, and Output 3.1 Numbers 3.2 Strings 3.3 Input and Output.
Chapter 31 Fundamentals of Programming in Visual Basic (Continue VI) String Properties and Methods: "Visual".Length is 6. "Visual".ToUpper is VISUAL. "123.
1 Chapter 3 – Variables, Input, and Output 3.1 Numbers 3.2 Strings 3.3 Input and Output.
Created By Mayson Al-Duwais1. Using Exit to Terminate Repetition Statements To terminate different types of repetition statements you can use a special.
Variables and Constants
CS0004: Introduction to Programming Variables – Numbers.
CS0004: Introduction to Programming Input and Output.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
CS0004: Introduction to Programming Variables – Strings.
1 Chapter 3 – Variables, Input, and Output 3.1 Numbers 3.2 Strings 3.3 Input and Output.
1 Chapter 3 – Variables, Input, and Output 3.1 Numbers 3.2 Strings 3.3 Input and Output.
Chapter 3 - VB 2008 by Schneider1 Chapter 3 – Variables, Input, and Output 3.1 Numbers 3.2 Strings 3.3 Input and Output.
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
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.
Introduction to Programming with RAPTOR
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.
Numbers continued The Integer Data Type Multiple Declarations Parentheses Three Types of Errors.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
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.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
1 Chapter 3 – Examples The examples from chapter 3, combining the data types, variables, expressions, assignments, functions and methods with Windows controls.
110 E-1 Variables, Constants and Calculations(2) Chapter 3: Operations on variables, scope of a variable, formatting data Doing Arithmetic.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
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.
Chapter 3 - VB 2008 by Schneider1 Chapter 3 – Variables, Input, and Output 3.1 Numbers 3.2 Strings 3.3 Input and Output.
Microsoft Visual Basic 2010 CHAPTER FOUR Variables and Arithmetic Operations.
A variable is a name for a value stored in memory.
Topics Designing a Program Input, Processing, and Output
Chapter 3 – Variables, Input, and Output
Expressions.
An Application Uses Variables to Hold Information So It May Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use.
BASIC ELEMENTS OF A COMPUTER PROGRAM
Variables and Arithmetic Operations
Variables, Expressions, and IO
Chapter 3 – Variables, Input, and Output
Java Programming: From Problem Analysis to Program Design, 4e
Lecture Set 4 Data Types and Variables
Variables and Arithmetic Operations
Number and String Operations
Chapter 3 – Variables, Input, and Output
Numbers.
CIS16 Application Development Programming with Visual Basic
Section 3.3 Numbers Arithmetic Operations Variables
Computing in COBOL: The Arithmetic Verbs and Intrinsic Functions
elementary programming
Core Objects, Variables, Input, and Output
Chapter 2: Introduction to C++.
Data Types and Expressions
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Data Types and Expressions
Data Types and Expressions
Presentation transcript:

Chapter 3 Data Types, Variables, and Expressions

Chapter 3 Data Types, Variables, and Expressions

Terminology Data Type – a category of data. A description of how the computer will treat bits found in memory. Variable – a named location in memory, treated as a particular data type, whose contents can be changed. Constant – a named location in memory, treated as a particular type, whose contents cannot be changed. Declaration – the act of creating a variable or constant and specifying its type. Literal – a hard-coded piece of data, part of the statement and not based on a variable or constant declaration. Operator – a symbol that describe how to manipulate data and variables in memory Expression – a combination of operators, variables, constants and/or literals that produces a resulting piece of data Assignment – copying the results of an expression into a variable. Statement – a program instruction telling the CPU what to do. Date Type: Just telling the program it is a number or a string Operator: + , - , / , *

Numbers Arithmetic Operations : Numeric Data Types: Integer, Double +, -, /, *, \ (integer division), Mod (modulus, remainder), ^ (exponentiation) Numeric Data Types: Integer, Double Numeric Literals: (e.g. 10, 12.2, 0.395) Numeric Variables Declaration, Assignment, Use in expressions Numeric Expressions Some Built-In Arithmetic Functions: Math.Sqrt, Int, Math.Round

Arithmetic Operations Arithmetic operations in Visual Basic + addition - subtraction * multiplication / division ^ exponentiation \ integer division (remainder is discarded) Mod modulus (remainder of an integer division) Modulus: What’s left over when you do the division. So 10 / 6 = 4. 6 goes into 10 one time. 4 is left over. So the left over or Modulus is 4.

Operator Precedence in Numeric Expressions Exponentiation (^) Unary identity and negation (+, –) Multiplication and floating-point division (*, /) Integer division (\) Modulus arithmetic (Mod) Addition and subtraction (+, –) first last Same-precedence operations occur in left-to-right order Parenthesis give the operation priority. Parentheses can be used to override normal precedence (inner parentheses happen before outer parentheses)

Numeric Expressions 2 + 3 3 * (4 + 5) 2 ^ 3 13.2 + 4.5 / 3 All of these expressions involve numeric literals and arithmetic operators 14.7 Question: what will be the result of each of these expressions?

Two Integer-Valued Operators Integer division (denoted by \) is similar to ordinary long division except that the remainder is discarded. The Mod operator returns only the integer remainder. 23 \ 7 = 3 23 Mod 7 = 2 8 \ 2 = 4 8 Mod 2 = 0

Numeric Variable A numeric variable is a named location in memory that will contain a number and can be modified throughout the program’s execution. Example variable names: intSpeed intDistance dblInterestRate dblBalance

Numeric Variable Declaration Variable declaration (a statement beginning with Dim): Dim dblSpeed As Double variable name data type This creates a location in memory for containing a Double value. The Double data type refers to a number that can include a fractional part (i.e. places to the right of the decimal place.

Numeric Variable Declaration You can declare multiple variables in the same Dim statement Dim dblA, dblB As Double This creates two Double variables Dim dblA As Double, intB As Integer This creates one Double variable and one Integer variable The Integer data type refers to a whole number (no fractional part included)

Numeric Variable Assignment In an assignment statement, the expression to the right of the = operator is fully evaluated first, then the resulting value is placed in the variable to the left of the = operator. Assignment: intSpeed = 50 dblBal = dblBal + dblBal* dblInterestRate variable name Numeric expression What is dblBal after stmt is run if dblBal = 100 and dblInterestRate = 5% Note: the = symbol is an assignment operator in this case. Sometimes it is used as a test for equality (a relational operator), for example if used in a test of an If-statement

Initialization Numeric variables are automatically initialized to 0: Dim varName As Double To specify a nonzero initial value Dim varName As Double = 50  Initialization is a variable declaration combined with an assignment

Example 3.1.2 This is a ListBox called lstResults

Variable declarations Example 3.1.2 Variable declarations Variable intA is uninitialized so starts with a value of 0. Variable intB is initialized to 3.

Calling methods of the ListBox object’s Items property Example 3.1.2 Calling methods of the ListBox object’s Items property The Clear method empties the Listbox. The Add method adds a row to the ListBox.

Anatomy of a Method Call When calling the Add method, you pass it the data as an argument. The ListBox lstResults.Items.Add(intA) The Items property contains the collection of data that are displayed in the ListBox The Items property’s Add method is a subroutine that places an item into the collection

Example 3.1.2 Assigning value into the a variable

Example 3.1.2 Adding a third item to the list

Method Call passing a complex expression as an argument lstResults.Items.Add(intA * (2 + intB)) An argument can be a complex expression. The expression will be fully evaluated before the resulting data is sent. In this case, the following steps take place in this order: 2 + intB innermost parentheses  5 Multiply intA times the results of (1)  25 Pass the result of (2) to the Add method  Order of operations from innermost to outermost based on parentheses

Incrementing To add 1 to the numeric variable var Or as a shortcut var = var + 1 Or as a shortcut var += 1 Or as a generalization var += numeric expression  Other shortcuts: -=, *=, /=, etc.

Some Built-in Arithmetic Functions Functions return a value Square root: Math.Sqrt(9) returns 3 Convert number to integer: Int(9.7) returns 9 Rounding: Math.Round(2.7) returns 3 NOTE: integer variables round the number but Int function truncates

Example 3.1.4 This is a ListBox called lstResults

Variable declarations Example 3.1.4 Variable declarations

Example 3.1.4 Variable assignments

Empty the list box items Example 3.1.4 Empty the list box items

Add three values to the list box Example 3.1.4 Add three values to the list box

Order of operations lstResults.Items.Add(Math.Sqrt(5 * dblB + 1)) 15 16 4 Add to list

Order of operations lstResults.Items.Add(Int(dblA ^ dblB + 0.8)) 8 8.8 Add to list The Int function truncates the number…it will not round up, but rather just chops off the fractional part.

Order of operations lstResults.Items.Add(Math.Round(dblA / dblB, 3)) 0.6666666666… 0.667 Add to list The Math.Round method rounds the number either up or down, depending on which rounded value is nearer. It can take two arguments: The number to be rounded The total number of decimal places for the rounded number If the second argument is not provided, 0 is assumed. There will be no decimal places, so the result will be a whole number. Multiple arguments to methods are separated by commas.

This example converts 41 inches into 3 feet, 5 inches

Variable declarations…three in one statement Example 3.1.5 Variable declarations…three in one statement

Example 3.1.5 Backslash is for integer division. Truncates the fractional part. So, feet = 3

Example 3.1.5 Mod gives the remainder of an integer division. So, inches = 5. 41 divided by 12 is 3, with a remainder of 5

Widening Widening: assigning an Integer value to a Double variable Widening always works. No conversion function needed.

Narrowing Narrowing: assigning a Double value to an Integer variable Narrowing might not work. Narrowing requires the Cint function.

String Literal A string literal is a sequence of characters surrounded by quotation marks. Examples: "hello" "123-45-6789" "#ab cde?"

String Variable Examples: A string variable is a name to which a string value can be assigned. Examples: strCountry strSsn strWord strFirstName

String Variable (continued) Declaration: Dim strFirstName As String variable name data type Assignment: strFirstName = "Fred" Remember – in general an assignment statement has a variable name to the left of = and an expression to the right. The data type of the expression should be consistent with the data type of the variable. For example, you should not assign a String expression into a Double variable.

Initial Value of a String Variable By default the initial value is the keyword Nothing Strings can be given a different initial value as follows: Dim strName As String = "Fred“ The string "", which has no characters, is called the empty string or the zero-length string.

Example 3.2.1 This is a string literal, which will be displayed literally. This is a string variable, so its contents will be displayed

Concatenation Combining two strings to make a new string strQuote1 = "We'll always " strQuote2 = "have Paris." strQuote3 = strQuote1 & strQuote2 & " - Humphrey Bogart" The variable called strQuote3 will contain: We'll always have Paris. - Humphrey Bogart Concatenation can be done using either the ampersand symbol (&) or the plus symbol (+)

Appending To append str to the string variable var Or as a shortcut var = var & str Or as a shortcut var &= str

What are the results of each? Appending Example Dim str1 As String = "Good" Dim str2 As String = "bye“ Dim str3 As String = "Good“ Dim str4 As String = "-bye" str1 + str2 str1 & str2 str1 &= str2 str3 += str4 What are the results of each?

Example 3.2.3

Declaring three String variables Example 3.2.3 Declaring three String variables

Assigning String literals into String variables. Example 3.2.3 Assigning String literals into String variables.

Example 3.2.3 Concatenating the contents of two String variables and assigning them into another String variable Note: remember that the right side of an assignment statement is an expression. In this example, the expressions are String expressions.

Example 3.2.3 The final result placed in the Text property of txtOutput is the result of another concatenation

Strings String Properties and Methods: Length ToUpper Trim ToLower IndexOf Substring

String Properties and Methods "Visual".Length is 6. "Visual".ToUpper is VISUAL. "123 Hike".Length is 8. "123 Hike".ToLower is 123 hike. "a" & " bcd ".Trim & "efg" is abcdefg. Properties are data items associated with a class of objects. Methods are functions or subroutines associated with a class of objects. These will be discussed in detail in future lectures.

Positions in a String Positions of characters in a string are numbered 0, 1, 2, …. Consider the string “Visual Basic”. Position 0: V Position 1: i Position 7: B Substring “al” begins at position 4

Substring Method Let str be a string. str.Substring(m, n) is the substring of length n, beginning at position m in str. “Visual Basic”.Substring(2, 3) is “sua” “Visual Basic”.Substring(0, 1) is “V”

IndexOf Method Let str1 and str2 be strings. str1.IndexOf(str2) is the position of the first occurrence of str2 in str1. (Note: Has value -1 if str2 is not a substring of str1.) "Visual Basic".IndexOf("is") is 1. "Visual Basic".IndexOf("si") is 9. "Visual Basic".IndexOf("ab") is -1.

Example 3.2.5 This example illustrates the use of some String methods and properties.

Example 3.2.5 The Substring method takes two arguments: The beginning position of the substring (first position of the string is 0) The length of the substring (number of characters to return) Note: if no ending character position listed, returns to end of string

Example 3.2.5 This IndexOf method returns the first position of a substring within a string.

Example 3.2.5 This ToUpper method converts the characters of a string to upper case. There is also a ToLower method In this case, the string expression is a concatenation. Note that (str1 & str2) is a concatenation of two strings. Because this is in parentheses, the concatenation occurs BEFORE the conversion to upper case. What would happen if you did not have the parentheses around str1 & str2?

Example 3.2.5 The Trim method removes beginning and end spaces from a string. Here, the trim takes place for str1, and the result is concatenated with str2

Example 3.2.5 The Length property of a string gives the total number of characters in the string. As you can see, str2 contains “a wink”, which has a total of six characters In this case, the Substring method is only taking ONE argument (str2.Length – 4)  2. If a second argument is not provided Substring returns the remainder of the string, starting at the specified beginning position So, at the end of the assignment statement, str3 contains the string “wink”.

Example 3.2.5 Note: These methods (SubString, IndexOf, Trim, ToUpper) return a string expression that can be used for display or assignment. But they do NOT change the original contents of the variables str1 and str2. Only an assignment changes them. So, at the end of this program, the contents of str1 and str2 are still “Quick as ” and “a wink”.

Option Strict & Option Explicit Visual Basic allows numeric variables to be assigned strings and vice versa, a poor programming practice. To prevent such assignments, set Option Strict & Option Explicit to On in the Options dialog box. Option Strict – requires explicit conversion of variable type Option Explicit – requires all variables to be declared

Option Strict & Explicit (continued) Select Options from the Tools menu In left pane, expand Projects and Solution Select VB Defaults Set Option Strict to On Set Option Explicit to On

Option Strict (continued)

Auto Correction

With Option Strict On Not Valid: Replace with: Dim dblVar As Double, intVar As Integer Dim strVar As String Not Valid: Replace with: intVar = dblVar intVar = CInt(dblVar) dblVar = strVar dblVar = CDbl(strVar) strVar = intVar strVar = CStr(intVar)

converts a String to a Double converts a number to a string Data Conversion Because the contents of a text box is always a string, sometimes you must convert the input or output. dblVar = CDbl(txtBox.Text) txtBox.Text = CStr(numVar) converts a String to a Double converts a number to a string

Example 3.2.2 This example adds the values in two textboxes and places them in a third

Example 3.2.2 The CDbl function takes a string value and attempts to convert it into a Double value. Note: the string must consist of digits (and perhaps one dot for a decimal point). Otherwise an exception (run-time error) would occur.

Example 3.2.2 The CStr function takes a numeric value and converts it to a string. This is necessary because a TextBox’s Text property requires a string value.

Named Constants Declared with Value cannot be changed. Examples: Const CONSTANT_NAME As DataType = value Value cannot be changed. Examples: Const MIN_VOTING_AGE As Integer = 18 Const INTEREST_RATE As Double = 0.035 Const TITLE As String = "Visual Basic"

Dates Date literal: #7/4/1776# Declarations: Dim datDay As Date Dim datD As Date = CDate(txtBox.Text) Dim datDay As Date = #7/4/1776# Date literals are enclosed in pound signs #. The CDate function converts a string to a date.

Example 3.3.1 Working with dates In this case, we have declared a variable as a Date.

Here we guarantee that only numbers are entered separated by slashes Example 3.3.1 Note that we have set a mask in the mtbDayOfBirth MaskedTextBox control. The MaskedTextBox’s Mask property helps guide the user and prevent invalid input. Here we guarantee that only numbers are entered separated by slashes

Masked Text Box Control Click on the Tasks button to reveal the Set Mask property. Click Set Mask to invoke the Input Mask dialog box.

Input Mask Dialog Box

Mask A Mask setting is a sequence of characters, with 0, L, and & having special meanings. 0 Placeholder for a digit. L Placeholder for a letter. & Placeholder for a character

Sample Masks State abbreviation: LL Phone number: 000-0000 Social Security Number: 000-00-0000 License plate: &&&&&& Date: 00/00/0000

The CDate function converts a String to a Date Example 3.3.1 The CDate function converts a String to a Date

Example 3.3.1 The FormatDatetime takes a date and formats it four output. Options are LongDate, ShortDate, GeneralDate, Longtime, and ShortTime

Example 3.3.1 The DateDiff function gives the time gap between two dates. You can specify which intervals you want: days, months, etc.

Example 3.3.1 FormatNumber allows you to display a number in a wide variety of formats. In this case we are specifying to display only the whole number part of the difference. As always, use parentheses to determine the order of operations that take place…inner to outer.

Formatting Numbers Lots of approaches: FormatNumber is good for getting the correct number of places to the right of the decimal, and has other options for how to display negative numbers, etc. FormatCurrency is a great way to show dollars and cents. For example, try this: FormatCurrency(varName) Where varName is the name of a numeric variable

Three Types of Errors Syntax error Runtime error Logic error

Some Types of Syntax Errors Misspellings lstBox.Itms.Add(3) Omissions lstBox.Items.Add(2 + ) Incorrect punctuation Dim intM; intN As Integer

Syntax Error List Window Dim intM; intN As Double lstResults.Items.Add(5 lstResults.Items.Add(a)

A Type of Runtime Error Overflow error – this is an Exception, and will cause the program to abort unless caught. Dim intVar As Integer = 10,000,000,000 intVar = intVar * intVar This is because a variable of Integer data type can only be assigned whole number values between about -2 billion and 2 billion. If you want larger numbers, you can use the Long data type.

A Logical Error Value of dblAverage will be 10. Should be 7.5. Dim dblAverage As Double Dim intM As Double = 5 Dim intN As Double = 10 dblAverage = intM + intN / 2 Value of dblAverage will be 10. Should be 7.5. This is because division takes place before addition. Using parentheses to override normal operator precedence will make this correct: dblAverage = (intM + intN) / 2

Code comments Commented code begins with ‘ and is green ‘determine if user has more input Required in all remaining programs: 'Program name: 'Student name: 'My submission of this program indicates that I ‘have neither received nor given substantial ‘assistance in writing this program.

Example 3.2.7 It is good programming practice (and required in this class) to include comments in your code in order to explain what is being done.

Example 3.2.8 In previous examples, the variables were declared INSIDE the procedure. Here, it is declared OUTSIDE any subroutines. Two things to note about class-level variables: Their data remain in existence throughout the entire time that the Form is running Their data is accessible by ALL subroutines and functions of the form

Example 3.2.8 Compare previous to what would happen if numTimes were declared INSIDE the procedure. In this case, numTimes would only exist as long as the subroutine was running, and would disappear when it ended. So, EVERY TIME you run the routine, it will reinitialize to zero. Wouldn’t be able to keep a count of how many times the button was pushed!

3 Program Modes Design mode Run mode Debug or Break mode

Stepping through program Execute one line of code at a time (Stepping into) Execute one procedure (Stepping over) Execute remaining lines of code (Stepping out) Execution will stop a pre-specified line of code (Break point) Hoover to see value of particular variable or object

Stepping through program Each line is highlighted before execution Hover to see values dblNum1 & both Textboxes dblNum2 is 0 – Why?

Break points Set a break point & run Program stops Hover to see values

Book errors / Good programming techniques Use 3 letter prefix for all objects and variables All controls and variables names must be descriptive Any control that should not be editable should be set as such if not by default Descriptive comments (do not repeat code) NOTE: book does not follow these but they are required in this class