Lecture 5: Variables, Constants, and Data Types (2



In this lecture, we will discuss:  Comments and Whitespace  Storing Data

Bits and Bytes Integer Single and Double Boolean Char and String

More about data types…
   

Variable Scope  Formatting Data for output And with VB Studio, we will:

Apply formatting to our Price Calculator

Comments and Whitespace

When writing code, you want to keep things clear…
 

To improve re-usability of the code. Two useful tools for good coding:

Comments and White-space i.e., not executed. Describing what is going on ‘in-line’ (in the code). Example:
‘ define Integer n and initialize it to 27… Dim n As Integer = 27  whitespace ‘ add 1 to the value of n… n += 1

A comment is a line of code which is ignored by the compiler…

Useful for program documentation:

Comments are declared using a single quotation mark.

Whitespace (blank lines) is also used to define ‘blocks’ of code. A block will execute a single step in our algorithm. Blocks are then separated by whitespace.

Each comment then precedes a single block…
 

Storing Data: Bits and Bytes

Computers store data as bits:
 

Here, ‘bit’ is short for binary digit. A bit can take only two values: 0 or 1. Where each bit represents a power of 2 (base-2).

A number may be expressed as a string of bits…

This is referred to as binary representation.




Note that there are 8 bits in the binary representation above…

A byte (= 8 bits) is a common unit for measuring computer memory. Other common units:
 

A kilobyte (KB) = 1024 bytes = 210 bytes A megabyte (MB ) = 1024 KB = 220 bytes

Data Types: Overview

Integer Data Types

Last lecture, we mentioned two useful data types:
 

Integer and Double Note: most recent computers are 32 bit.

This means that they are optimized for 32-bit integer values.

An Integer is stored as a string of 32 bits = 4 bytes of memory.
  

The first bit is used to indicate sign. The remaining 31 bits indicate the number value…

Thus, an Integer is in the range: -2,147,483,648 ~ 2,147,483,648

Note: all 32 bits will be used, regardless of value! This is stored as 64 bits = 8 bytes. Longs are in the range: -263 ~ 263

For larger integers, the Long type is also available:
 

Where 263 = 9,223,372,036,854,775,808

The Short and Byte types are also available for small integers:
 

A Short is 2 bytes in length (-32,768 ~ 32,768) A Byte only 1 byte in length…but is unsigned:

Bytes are in the range: 0 ~ 255.

Floating Point Data Types

Floating-point numbers (or ‘floats’) refer to real numbers:
 

Numbers with a decimal point.

Examples: 32.0186925, 1.0, 3.14, etc

A real number will have the form: r = +/- M x10E
 

Where E is the ‘Exponent’ (signed integer) Where M is the ‘Mantissa’ (normalized in binary to be b/w 1 and 2)  For instance, the binary numeral for 21/16 is 1.0101 = 1 + ¼ + 1/16

The Single data type is available for ‘low-precision’ floats.
 

Stored as a string of 32 bits = 4 bytes.

So-called ‘single-precision’.

According to IEEE standards, a Single is a 32 bit approximation: S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM
  

Bit S encodes the sign (0 means positive) Bits E encode the exponent (8 bits; a signed integer) Bits M encode the Mantissa (23 bits).

 

For negative values: -3.4028235E+38 ~ -1.401298E-45 For positive values: 1.401298E-45 ~ 3.4028235E+38

Floating Point Data Types (cont.)

The Double data type is available for high-precision floats…
 

So-called ‘Double precision’. The real number is approximated using 64 bits.

Again, we have the basic form (IEEE): S E…E M…M

But now:  1 sign bit, S  11 exponent bits, E  52 significand bits, M

Range of Values:

-1.79769313486231570E+308 ~1.79769313486231570E+308

The Decimal data type is also available for floats:

The float is stored as a signed 16 byte Integer (128 bits)…

The Integer is then scaled by a power of 10 to produce the float:

This specifies the number of digits to the right of the decimal point.

The scale is from 0 decimal places to 28 decimal places.

Useful for fixed point calculations…like currency (money).


Boolean variables can take only two values:
 

True or False Although simple, such Boolean variables become very important when making decisions...

Such as conditional statements.

More on this, later…

Dim isReady As Boolean = False

Declares a boolean value ‘isReady’, and initializes it to False.

 

A character refers to a single symbol.

Examples: a,  虹 , M, 3, =, ひ as a two byte, unsigned integer (16 bits).

In VB, a character is stored via the Char data type…

Range: 0 – 65,535 uniquely identifies the represented character; is called the Unicode representation.

For a given character, this integer:
 

Conversely, a variable of type Char may take 65,536 distinct values.

Each of which is the unique character.

Char variables are useful in processing Strings (next).

A character variable is declared as follows: Dim char_name As Char = “a”

Note that when assigning a value to a Char…

The assigned character is enclosed by double quotes (“”).

Example: oneCharacter = “A”

 

A String is a collection of characters, enclosed by “ ” marks.

Example: “This is a string.”

A String is declared in the normal way:
Dim string_name As String = “initial value”

As usual, initialization is shown, but not required. Example:
 

As expected, we may assign a value to a declared String:

Dim c As String c = “Hello, World!” For instance, to a Button, as its text.

Such a String is often passed for graphics use…

Working with Strings: Catenation
 

Various operations are defined on Strings…

Catenation, etc… the catenation operator, &. Example: Given the statements… Dim s1, s2, s3 As String s1 = “Hello” s2 = “, World!”

The joining of two strings is accomplished by:
 

The catenation operation…
s3 = s1 & s2

…adds s1 and s2, and sets s3 equal to: “Hello, World!”

Thus, catenation may be thought of as ‘addition for Strings.’

String Literals

Not all strings have to be explicitly declared as a variable:

A String literal is an undeclared string constant…

Which is implicitly declared using quotation marks (“ ”). For instance, by displaying text on a label.

We have frequently used string literals for output!

String literals are often combined with other data types…

Via the catenation operator, &…

to form a new string, which is then used for output.

Consider the VB code:
Dim subtotal As Integer = 150 label1.text = “Subtotal = ” & subtotal &” dollars”

The result is that the catenated string,
“Subtotal = 150 dollars”

Is passed to a label1, for display.

More String Operations

Returning a String’s length:

A String’s length is the number of characters in the string.

This is a ‘property’ of all objects of type String:

All strings have an Integer length.

So, the length of a string, s is given by referencing its length property…

Using the ‘dot operator’ (s.length)

Working with substrings:

A substring of s is a sub-set of the string.

Kind of like taking a ‘bite’ out of the string.

The statement:
s.substring( start n, length l )

Takes string s, and creates a substring of length l, starting from char n. Let String s = “Hello, World!”. Then
 


s.substring(0, 5) = “Hello”, and s.substring(7, 6) = “World!

Using Dates

A variable of the Date data type holds a ‘date’ value:

A time/date pair, stored as a 64 bit (8 byte) integer…

Each increment represents 100 ns (10-7 sec) of elapsed time. Date: AD Jan 01 0001 ~ AD Dec 31 9999. Time: 00:00:00 (midnight) – 23:59:59

Range of Values:
 

Variables of type Date are declared in the normal way  For example: Dim theDate As Date = #5/31/2007 3:00:00 AM#

However, when assigning a value to a Date, it must be:
 

enclosed in ‘#’ signs, and in the format shown above ( mm/dd/yyyy h:mm:ss tt);

When converting a Date to a String…

for instance, for display or printing,

The ‘date’ and ‘time’ portions are rendered according to the local settings on your computer.

Extracting Date Properties

A variable of type Date will have a number of properties.

You can call these to learn more about the date…

Using the dot-operator ( . )

For instance, for a Date variable called ‘theDate’:

You can get theDate’s date-values:
  

theDate.Month theDate.Day theDate.Year theDate.Hour theDate.Minute theDate.Second

And theDate’s time-values:
  

Type Conversions

In VB .NET, data can be converted in two ways:

Implicitly – this means the conversion is automatic.
 

VB will often do the conversion for you, if you don’t… However, keep in mind that some conversions are narrowing.

For instance, converting 5.234 to an Integer yields 5 (losing information!).

Explicitly – this means you must do the conversion.
 

An explicit conversion is also called a ‘cast’. In VB .NET, many casts are done using defined functions:  CInt(x) converts x to an Integer (rounds).  CDbl(x) converts x to a Double  CDate(x) converts x to a Date  CString(x) converts x to a String  Etc… The CType(x, y) function operates on two arguments:

(converts variable x to data type y; return the result). Example:

Dim d As Double Dim i As Integer i = CType(d, Integer) ‘conversion, followed by assignment.

Variable Scope

A variable’s scope refers to its range:

Where it is visible (i.e., available for use).

If a variable is used out of scope, an error message results.


outside of the While loop, the computer doesn’t “know about” B.

Formatting Data
 

After data analysis, it is usual to format the data for output:

To provide a convenient form for users. Using the Format() function. Earlier examples: Date and Time.

In VB .NET, numerical values may easily be formatted:
 

As we saw, the Format() function has syntax (= structure): Format(Object o, String s)

Format() takes two parameters:
 

An Object (e.g., Data) which is to be formatted; A String which specifies the desired format.

When formatting currency (money), the FormatCurrency() function may be used.

The simplest form takes only one parameter

FormatCurrency(Object o)

Data o is formatted using the operating system currency symbol…

set by the user, via Control Panel.

Setting up Numerical Data Format

Here are the format characters for setting up a custom format:

You may also insert symbols (characters), as we saw earlier.

Let’s look at some examples…

Data Formatting: Examples

Re-using our Program
 

Let’s use our Cash Register program as a base…

And rebuild it to create a new program. Basic Function will be the same as before:

Program Functionality:

Calculate the subtotal, consumption tax, and total Add a dollar sign. Format so that values are displayed to 2 decimal places. Format to include a comma after every 3 digits (to the left of the ‘.’)

New Functionality (formatting):
  

To accomplish this, we use the Format() function.

Re-using our Program (cont.)

Note: When we reuse code, I may just show the changed/added lines!

Now, I have some Tasks (assignments).

Task 1: The Body Mass Index

Task 2: Simple Interest

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.