28
65 Using Data in Programs HUS FAR IN THE VISUAL BASIC PROJECTS, we have used objects, modified the properties and exercised some methods. We have used events to provide action in the projects. However, we have not used T data except for text strings, and have not made any mathematical calcu- lations. That is about to change. We are now going to enter numeric data in the project, and perform some calculations. This will give us much more capability to do something useful than we have done so far. Varia aria aria aria ariables and Constants les and Constants les and Constants les and Constants les and Constants Broadly speaking, data can be divided into two basic categories: (1) data that is changeable (or will likely change), and (2) data that will not change. In computer-eze, data that either can change or will likely change is called a variable, while data that does not change is called a constant. Most of the data you will deal with will be variables, but constants are also around us. Visual Basic treats them the same in some respects but has important differences.

Using Data in Programs - Solano Community Collegebcs.solano.edu/workarea/ewylie/CIS 1/CIS1 Data Files/CIS001 - A... · Using Data in Programs ... data except for text strings,

Embed Size (px)

Citation preview

65

Using Datain Programs

HUS FAR IN THE VISUAL BASIC PROJECTS, we have used objects,modified the properties and exercised some methods. We have usedevents to provide action in the projects. However, we have not used

Tdata except for text strings, and have not made any mathematical calcu-lations. That is about to change. We are now going to enter numeric datain the project, and perform some calculations. This will give us muchmore capability to do something useful than we have done so far.

VVVVVariaariaariaariaariabbbbbles and Constantsles and Constantsles and Constantsles and Constantsles and ConstantsBroadly speaking, data can be divided into two basic categories:

(1) data that is changeable (or will likely change), and (2) data that willnot change. In computer-eze, data that either can change or will likelychange is called a variable, while data that does not change is called aconstant. Most of the data you will deal with will be variables, butconstants are also around us. Visual Basic treats them the same in somerespects but has important differences.

66

Constants are values that have been given a specific definition, andnothing you can do will change it. For example, there are 7 days in a week,24 hours in a day, 60 seconds in a minute, 12 months in a year, 12 inches ina foot, 5,280 feet in a mile, and so forth. Nobody can change them, andthey are “constant” in their definition.

A variable is data that will or could change. Examples are thenumber of work hours in a work week, rate of pay, scores on exams, priceof a movie ticket, number of people attending an event, and so forth.

VVVVVariaariaariaariaariabbbbble and Constant Namesle and Constant Namesle and Constant Namesle and Constant Namesle and Constant Names

To make our lives easier, we use words to represent both variablesand constants to describe the values they represent. If we say “day” we allknow it is the same thing as 24 hours, or 1440 minutes. Or, a “mile” is thesame thing as 5,280 feet or 1760 yards. Both day and mile are names forconstants, and we all learned long ago what the actual values are. On theother hand, if I say “pay-rate” we don’t know what value that representsunless we define it. After it has been defined (or described), we can thenuse pay-rate the same way we use day or mile to describe a numericamount. In computer-eze, we use pay-rate, day, or mile as a placeholderfor a numeric value. We call that placeholder a variable or constant name.

Likewise, in math and Algebra we learned that you can use aboutany letter to represent any value as long as it is defined someplace. Forexample, we can say that “A = 15” and then we can use the letter “A” torepresent the value 15. In this case, “A” is a variable name for the value15. Visual Basic uses variable names in the same way as Algebra, or asEnglish does for common, fixed values.

Visual Basic uses variable names to represent memory locationsinside the computer. Those memory locations are containers that hold data.We are normally not concerned where the exact location is in memory, butwe need to know what the location is called. We refer to these memorylocations as Identifiers.

To help you conceptualize a memory identifier, think of an identiferas a container. We are used to using various types of containers to containdifferent items. For example, we have cardboard boxes, paper bags, metalor plastic buckets, glass bottles, fiber baskets, air-tight tanks, etc., and theyhold different items. They are all containers. You would not think of put-ting a liquid in a basket or paper bag, but could put solid items in a basket.We know a liquid needs a bottle, and sand needs a bucket. We must like-wise use an appropriate container to hold different types of data.

We mustuse an

appropriatecontainer

to holddifferenttypes of

data.

67

DaDaDaDaData ta ta ta ta TTTTTypesypesypesypesypesData includes both numeric data and alphabetic data. However, we

all learned long ago that these two types of data are not the same. We canadd and subtract with numbers, but not with alphabetic characters. Num-bers are not all the same either. Some numbers have decimal points andothers do not. Numbers with decimal points are called Decimals, andwhole numbers (numbers without decimals) are called Integers. Alphabeticcharacters are called Strings. To be successful in programming, you need tounderstand that the data types are different, and you need to know the typeof data you are using.

Visual Basic recognizes 12 different types of data, but normallyonly four are significantly different and important at this level. The fourdata types you need to understand for this class are Integer, Decimal,String, and Boolean. They are described below.

Data Type Description UseInteger Whole numbers Counting and computingDecimal Numbers with decimals ComputationsString Any character Text characters, punctua-

tion, and numbers notused in computations

Boolean On or off state True or False values

Even though all data is contained electronically in the computer, itsidentifiers are different sizes, and we need to assign the right type ofidentifier to the appropriate data. The different data types need differentamounts of memory space to be stored properly. For example, an Integerrequires 4 bytes of storage while a Decimal number requires 16 bytes ofstorage. A Boolean value only needs 2 bytes of storage while String dataneeds a varying amount of storage space.

The other data types recognized by VB include the following:

Data Type UseSingle Single-precision numbers with 6 digits of accuracyDouble Double-precision numbers with 14 digits of accuracyLong Very large whole numbersShort Small whole numbersDate Date values through Dec 31, 9999Char Single Unicode characters (including non-English

language characters)Byte Binary dataObject The default data type; could be used for any data

Table 4.1Common

Data Types inVisual Basic

Table 4.2Other

Data Types inVisual Basic

68

Each of the above data types has certain restrictions. For example,the Short data type is restricted to Integer values ranging from -32,768 to+32,767 while the Integer data type allows values to plus or minus 2.1billion. If your Integer value will be larger than 2.1 billion, you must usethe Long data type. Likewise, most decimal applications fit within theDecimal data type. However, if you need very high levels of decimalprecision, then use Single or Double. If you are planning a trip to Mars,then you probably should use Double to get the highest degree of precision.If you are counting grains of sand on the beach, you probably should useLong. Byte is used to transfer binary data between various programminglanguages, such as transferring from Visual Basic to C++ or C#. TheObject data type should only be used if the type of data is unknown, or islikely to change in data type frequently. It is the least efficient data typeavailable, and should only be used when nothing else works.

Technically, the Single data type is more efficient than the Decimaldata type. However, Single, Double, and Long are usually used in scientificapplications while business-use usually uses Integer and Decimal datatypes.

Refer to Appendix A for details on all data types.

DecDecDecDecDeclaring laring laring laring laring VVVVVariaariaariaariaariabbbbble Namesle Namesle Namesle Namesle Names

The most important thing about a variable name is that it must berepresentative of the data it contains. You cannot assume that you willremember what the value of the data actually is, so the name must identifyit for you. You might not even know what the value is. For those reasons,the variable name “X” is the worst name possible -- it doesn’t describeanything.

Visual Basic has some “Naming Rules” to keep in mind whennaming variables or constants:

Names can contain alphabetic characters, numbers, andthe underscore, but no other punctuation.

Names must begin with an alphabetic character. Names cannot contain a space or a period. Names cannot be a reserved word, but reserved words can be

contained inside a name, such as ClassFriend. (A reserved wordis a word that has a special meaning in Visual Basic, such asSub, Private, Dim, Close, etc. Refer to Appendix B for a partiallist of reserved words.)

Names are not case sensitive. Names such as Quantity, quantity,and QUANTITY are all considered the same variable name.

There is no real limit to the number of characters used.

69

Most experienced programmers like to use prefixes to identify thedata type in variable and constant names. Variable or constant name pre-fixes are similiar to prefixes used to identify controls. A suggested listingof prefixes for variables and constants are as follows:

Data Type Prefix ExampleInteger int intCountDecimal dec decNetAmountBoolean bln blnMaleString str strAcctNum

As with control prefixes, variable name prefixes should be lowercase with the main part of the name starting with a capital letter. Usingprefixes to designate the data types is highly encouraged to avoid “Type-Mismatch” errors, such as trying to compute a zip code. The importantthing is the spelling and capitalization used because it will appear that waythroughout the program.

It is also important to assign the right type of prefix as it is named.Consider the following when assigning a data type:

If a value could be used in calculations and does not have adecimal, use the Integer data type.

If a value could be used in calculations and does have adecimal, use the Decimal data type.

If a value will not be used in calculations, use the String datatype. This would include numbers such as Social Securitynumbers, phone numbers, account numbers, Zip Codes,addresses, etc.

If the variable contains alphabetic characters, use the Stringdata type.

TTTTThe Deche Deche Deche Deche Declarlarlarlarlaraaaaation Station Station Station Station Statementtementtementtementtement

Variable names are created using a Declaration statement. TheDeclaration statement establishes the name and assigns the data type tothat name. It also assigns the scope of the name (which will be discussed inthe next section). The Declaration statement is often called a “Dim” state-ment because it starts with the keyword Dim. (Dim is a shortened versionof “dimension.”)

The Variable name follows the word Dim, then the key word “As”,then the data type. Figure 4.1 shows some examples.

Table 4.3Variable and

Constant NamePrefixes

70

In Figure4.1, the first twostatements de-clared decPayRateand decMaxPointsas Decimalvariables, the nexttwo (intCount andintQuantity) asInteger variables,and the last two(strCity andstrZipCode) asString variables.

Note: it is the keywords As Decimal, As Integer, or As String thatassign the data type, not the prefix. If you list it as “Dim intValue as Deci-mal”, then it will be a decimal data type regardless of the prefix.

Normally a variable is created and the opening value is zero. How-ever, if you wish to initialize it with a value other than zero, you can do so,as shown with the variable decMaxPoints in Figure 4.1. SincedecMaxPoints is a variable, it can be changed later while the program isrunning.

DecDecDecDecDeclaring Constantslaring Constantslaring Constantslaring Constantslaring Constants

Declaring a constant is nearly the same as declaring a variable.However, constants use the keyword “Const” instead of “Dim,” and con-stants must be given a value at the time they are declared. Once they aredeclared and initialized to a value, they cannot be changed. Constants mustalso be given a data type when created. The data type and the value givenmust also match. Figure 4.2 shows a constant being declared and initial-ized.

Figure 4.2 shows four constants being declared and initialized. Acouple of things are different than with variables. Variables may be initial-

Figure 4.1The Dim

StatementdeclaringDecimal,

Integer, andString variables

Figure 4.2Declaring

Constants

71

ized when declared, but constants must be given a value when declared.Also notice that the bottom two constants have a different capitalizationthan the first two in that most of the constant name is capitalized (exceptfor the prefix). This is an optional arrangement, but is a very handy way ofshowing the difference between a variable and a constant to the program-mer on the code sheet.

Also notice that in Figure 4.2 the value is followed by a typedeclaration character. This will ensure that the data and the data typematch. The type declaration characters are D for Decimal, I for Integer, Rfor Double, L for Long, S for Short, and F for Single. No space is allowedbetween the value and the type declaration character. If the type declarationcharacter is missing, then a whole number is assumed to be an Integer anda decimal number is assumed to be a Decimal. It is an extra step to helpthe programmer not make a type-mismatch error later.

Scope ofScope ofScope ofScope ofScope of VVVVVariaariaariaariaariabbbbbles and Constantsles and Constantsles and Constantsles and Constantsles and ConstantsVariables are “born” when they are created, but they don’t live

forever. Like humans, variables don’t live forever; they will eventually“expire.” The lifetime between when a variable is created and when itexpires is called its scope. But, there is more to it than that. Scope alsorelates to its area of influence. A variable only exists within its lifetime andarea of influence. When variables expire, the memory locations are re-leased, the contents are erased, and the variable name is no longer valid.

Generally, there are three levels of scope: global, modular, andlocal. A local-level variable is only useable within the event procedurewhere it was created. When the flow of control enters the event procedure,it becomes alive, and when the flow of control leaves the procedure, it nolonger exists. A modular-level variable becomes alive when the module(or form) becomes active and when the form becomes inactive, the vari-able no longer exists. A global variable is alive and active whenever theproject is active.

(The code sheet for a form is called the “module sheet,” so gener-ally a form and module are the same. At advanced levels, there is a differ-ence, but it is not important now. The term “module” is preferred.)

If a project only has one form, then global- and modular-levelscope would be nearly the same. If the project is large and has more thanone form, then modular-level and global-level become different. Likewise,if a module only has one event procedure, then local-level and modular-level would be the same. However, it is very unlikely that a module willonly have one event procedure, so the difference between modular-leveland local-level scope is most likely to be relevant.

A variableonly existswithin itslifetime

and area ofinfluence.

72

DecDecDecDecDeclaring Local laring Local laring Local laring Local laring Local VVVVVariaariaariaariaariabbbbbleslesleslesles

Scope level of a variable is determined by where the variable isdeclared. Local-level scope is created using the Dim statement, and itnormally should be at the top of the event procedure above all other codelines. The variable will be alive and useful only within the event procedurein which it was declared, and will normally expire when the End Substatement is reached at the end of the procedure. Each time you re-enter anevent procedure, the variable is re-created. Always use local-level scope ifpossible.

DecDecDecDecDeclaring Module-Lelaring Module-Lelaring Module-Lelaring Module-Lelaring Module-Levvvvvel el el el el VVVVVariaariaariaariaariabbbbbleslesleslesles

A module-level variable is created using the keyword Private, andthe remainder of the declaration line is the same as the Dim statement usedto create a local variable. The declaration is placed above the first eventprocedure on the module sheet in the area called the “Declarations section”of the module sheet. Normally the module-level declarations are placedbelow the line reading “Public Class form-name” and above the first eventprocedure. Module-level variables are useful in all event procedures on theform or module.

Figure 4.3 shows both local and modular-level variables and theirdeclaration statements. The variable intCounter is declared as a modular-

Figure 4.3Declaring

Module-leveland Local-level

Variables

73

level Integer variable, and is located in the Declarations section of themodule sheet. It will be available in all event procedures on the modulesheet. The variable decScore is declared as a local variable and is onlyactive inside the btnComputeScore_Click event procedure. Likewise, thevariable decFinalGrade is a local variable and is only active inside thebtnComputeGrade_Click event procedure. The variable decScore is notknown to the btnComputeGrade_Click procedure, and the decFinalGradevariable is not known to the btnComputeScore_Click event procedure.

To further explain how scope works, let’s use a legal/politicalexample. Assume you have three independent cities (Fairfield, Vallejo, andVacaville), all located inside one county (Solano) which is also locatedinside one state (California). If the Fairfield City Council passes a law, ithas no effect inside the cities of Vallejo or Vacaville, but does have aneffect inside the City of Fairfield. That is an example of local scope. Alsoassume the County of Solano passes a law. It is in effect within the entirecounty, including the cities in the county, but has no effect in other coun-ties. That is an example of module-level scope. If the State of Californiapasses a law, it is in effect in each county, and each county within the state,but not other states. That would be an example of global scope.

The advantage of using local scope is that an unexpected result willnot have an impact in an event procedure because it was declared some-where else, and has wider impact than is needed or expected. You shouldalways use the lowest-possible scope for your variables.

Global ScopeGlobal ScopeGlobal ScopeGlobal ScopeGlobal Scope

Even though global scope (now called “Namespace scope” byMicrosoft) will probably not be used in this class, it needs to be coveredbriefly here. Global scope is intended for large applications that haveseveral forms and/or modules and those variables will be used throughoutthe entire application.

Global variables are declared using the keyword Public instead ofPrivate or Dim. Other than the Public keyword, the process is exactly thesame as declaring a module-level variable. The declaration statementshould occur on the first module sheet to be encountered or used in theproject. Once declared, a global variable can be used or changed anywherein the project.

Instead of using globally-declared variables, good programmingtechnique involves passing the value (or reference to the variable) directlyto the specific event procedure where it is needed. The process of passingvariables from one procedure to another is not difficult, but is beyond thelevel of knowledge needed in this class.

74

Scope of ConstantsScope of ConstantsScope of ConstantsScope of ConstantsScope of Constants

Constants are declared in the Declarations section of the modulesheet along with module-level variables. The reason for placing constantdeclarations with module-level variables is to make them easier to find ifneeded. A medium-sized application could have hundreds of event proce-dures, but only a few modules. Finding a constant declaration locatedinside an event procedure would be like searching for a needle in a hay-stack. Also, it is rare when a constant is given local scope.

An example of a global constant is shown in Figure 4.4. Note theinclusion of the keyword “Public.” Omitting this keyword would give itmodular-level scope. Compare this example with those in Figure 4.4 whichshow module-level constants.

PPPPPerferferferferforororororming ming ming ming ming Arithmetic CalculaArithmetic CalculaArithmetic CalculaArithmetic CalculaArithmetic CalculationstionstionstionstionsArithmetic operations in Visual Basic are fairly straightforward.

Addition, subtraction, multiplication, and division are very similar to theoperations of simple arithmetic. The operators used to perform thosecalculations include the +, -, *, and / symbols, respectfully. For example:

Addition: 10 + 3 results in 13Subtraction: 10 – 3 results in 7Multiplication: 10 * 3 results in 30, andDivision: 10 / 3 results in 3.333.

In addition, Visual Basic allows Integer division, Modulus division,and exponentiation (raising a number to its exponent power).

InteInteInteInteInteggggger dier dier dier dier divisionvisionvisionvisionvision is dividing one Integer by another and theresulting answer is likewise an Integer. The remainder, if any, is disre-garded. The symbol used for Integer division is the backslash (\). Forexample, if the Integer 10 is divided by the Integer 3, the Integer divisionanswer is the Integer 3. The remainder of 0.33 is disregarded. That wouldbe shown as 10 \ 3 with the answer being 3.

Figure 4.4Declaring Global

Constants

75

Modulus divisionModulus divisionModulus divisionModulus divisionModulus division returns only the remainder of the divisionoperation. The word Mod is used for the operator. For example, using theexample above, the Integer 10 modulus Integer 3 gives the answer of .333.The Integer portion of the answer is disregarded. That would be shown as10 Mod 3.

Integer and Modulus division is useful for stripping off or truncat-ing a portion of the answer.

ExponentiaExponentiaExponentiaExponentiaExponentiationtiontiontiontion is raising a number to the power specified,and uses the caret (^) symbol. The number before the symbol is the basenumber and the number after the symbol is the exponent (or power). Forexample, the base number of 10 raised to the power of 2 would be 10 ^ 2and the result would be 100.

The examples above involving only one arithmetic operator arereferred to as simple calculations because it only has one operator, andonly one possible result. However, the process can get more involved whentwo arithmetic operators are involved, such as 10 + 3 * 5. Which is per-formed first – the addition or the multiplication? If the addition is per-formed first, the result is 65. However, if the multiplication is performedfirst then the result is 25. They can’t both be considered correct.

Calculations involving more than one arithmetic operator are called“complex” calculations – regardless how simple or difficult the actualarithmetic is. To avoid confusion in complex calculations, an Order ofArithmetic Operations has been established.

Order of Arithmetic Operations for multiple operators:(Highest order to lowest order)

1. Any operation inside parentheses2. Exponentiation3. Multiplication and division4. Integer division5. Modulus division6. Addition and subtraction

Multiple operations on the same level are performed left to right. Ifmultiple sets of parentheses are involved, work from the inside out. If youwant to override the above order, insert parentheses.

In the above example of 10 + 3 * 5, the correct answer would be 25since multiplication would be performed before addition. If you want theaddition to occur first, then place that portion of the formula inside paren-theses, such as (10 + 3)* 5 which results in 65.

76

DaDaDaDaData Conta Conta Conta Conta ConvvvvvererererersionsionsionsionsionPerforming calculations in Visual Basic is fairly easy to do. The

wrinkle in the process, however, is getting the data ready for the calcula-tions.

Initializing DaInitializing DaInitializing DaInitializing DaInitializing Datatatatata

When a numeric variable has been created using the Dim or Privatestatements, its initial value is zero. String variables are equal to emptywhen created. To be useful, most numeric variables need to have a valueother than zero. This is called “initializing.” As explained previously,variables can be initialized to a value when they are declared. If this isn’tdone, then they can be initialized in a separate line, such as

Variablename = valueNormally, initialization statements would be grouped to follow the

declaration statements.

ConConConConConvvvvverererererting Dating Dating Dating Dating Datatatatata

One of the new concepts of Visual Basic .Net is the concept ofconverting data from one data type to another. Visual Basic is a strongly-typed programming language, which in laymen’s terms is that the data typeof a variable is very important – more important than most “beginners toprogramming” realize.

TTTTThe Phe Phe Phe Phe Parararararse Methodse Methodse Methodse Methodse Method

As previously mentioned, data found in the Text Property of aTextBox is Text (or String). You must convert string data into a numericdata type before it can be used in calculations. This processes calledParsing or Casting. Parsing is a method of a data type. It is simple to do,but must be done.

Assume you have a TextBox on your form called txtQuantity, andyou want to convert its Text Property into an Integer variable calledintQuantity. Use the Integer.Parse method and place the text string insideparentheses, as shown in Figure 4.5.

Each numeric data type has a Parse method. If you are convertingfrom String to a Decimal data type, use the Decimal.Parse(text-string)method. Likewise, you can use the Short.Parse, Long.Parse, andDouble.Parse methods in a similar way. The string you wish to convert canbe a property of a control (such as a TextBox), a String variable, or a String

77

constant. The String value being parsed is called the argument of the Parsemethod.

Val function. Older versions of Visual Basic used the Val functionto convert numeric strings to numeric data. If the string data contained adecimal point, it would assume the numeric value was a Double data type,but if it did not have a decimal it would assume it was an Integer data type.The problem with using the Val function was with a zero value – it wasunreliable, and that is never acceptable in good programming practice.Since the Parse method does a better job, the Val function should beavoided.

ConConConConConvvvvverererererting Numeric dating Numeric dating Numeric dating Numeric dating Numeric data to Stringsta to Stringsta to Stringsta to Stringsta to Strings

After you have completed your calculations using numeric vari-ables, you likely will need to output the results to a label. Again, the TextProperty of a label is also Text (or String). Numeric data must be convertedinto a String data type to display it in a label. This conversion is accom-plished using the ToString() method. (Note: the parentheses indicate that itis a method.) Nothing needs to be included inside the parentheses. Thegeneral form of the ToString() method is

lblLabel.Text = intVariablename.ToString()lblResult.Text = decVariablename.ToString()

Figure 4.6 below shows the variable intResult being converted to astring data type that can be displayed in the Text Property of a label namedlblResult.

Figure 4.5Initializing a

Variable Usingthe Parse

Method

Numericdata must

be convertedinto a stringdata type todisplay it in

a label.

78

FFFFFororororormamamamamatting Outputtting Outputtting Outputtting Outputtting Output

To make the output easier to read, it is customary to format numericvalues to fit the circumstance. That means that numbers larger than “999”are usually displayed with comma separators. For example, the value 12345would normally be displayed as “12,345.” If the output is meant to be acurrency value, the dollar sign is added. Normally currency values aredisplayed to either zero or two decimal places. Also, negative currencyvalues are enclosed in parentheses.

Formatting should only occur after the calculation is complete andas part of the output process. Formatting is accomplished using the ToStringmethod by placing a format string inside the parenthesis following theToString method. For example, ToString(“c”) would format the output tocurrency and append the dollar sign, insert comma separators as appropri-ate, and display two decimal places.

Other numeric formatting patterns are also available. To format forpercent, use a “p” for the format code. Percent format will automaticallymultiply the result by 100 and append a space followed by the percent sign.Negative numbers will show a leading minus sign. The Number format isfairly generic. It will insert comma separators and show negative valueswith a leading minus sign. Number format uses the “n” format string.Scientific notation uses the “e” (for exponent) format string, and willdisplay the value in exponential form.

The format string can be further customized by placing a value afterthe designated letter to indicate the number of decimal places to show. For

Figure 4.6The ToString

method ofconverting a

numeric variableto a string

variable

Declaringvariables

Parsing Textdata toNumeric data

ConvertingNumeric datato Text data

79

example, the string c0 (letter “c” and the zero) will show the currencyformat rounded to zero decimal places. Likewise, p1 will show percent toone decimal, and n3 will show the number format to three decimal places.For currency, you do not need to show “c2” because two decimal places isthe default for currency. Lost decimal places are rounded, not truncated,when formatted.

Table 4.4 shows the format string and examples in tabular form.

Format Unformatted FormattedDescription String Number Number

Currency (default) c 1234.567 $1,234.57Currency no decimals c0 1234.567 $1,235Percent (default) p 0.12345 12.35 %Percent 1 decimal p1 0.12345 12.4 %Number (default) n 1234.567 1,234.57Number no decimal n0 1234.567 1,235Number 3 decimals n3 1234.5 1,234.500Scientific (default) e 1234.567 1.234567e-003

Since output formatting is so easy to accomplish, there really is noexcuse for not formatting numbers properly.

AccumAccumAccumAccumAccumulaulaulaulaulating ting ting ting ting TTTTTotalsotalsotalsotalsotalsand Counterand Counterand Counterand Counterand Countersssss

Accumulators: A frequent programming technique is to keep arunning total of a variable. The variable that keeps the running total isusually called an accumulator. An accumulator can be used to keep track oftotal sales, total earnings to date, and a variety of other applications. Theconcept of accumulating a running total consists of adding the current valueto the previous running total. To perform this task, two variables are needed:a current value and a running total value, such as decSales anddecTotalSales. For this example, the variable decSales is the amount of onetransaction, and the variable decTotalSales is the accumulator. The actualcomputation line would be

decTotalSales = decTotalSales + decSales

This line would take the previous total (decTotalSales) and add thelatest transaction (decSales), and replace this sum in the variable on the leftside of the equal sign.

Anaccumulatorincreases a

running totalby a varyingamount, but

a counterincreases a

running totalby a fixedamount.

Table 4.4Format StringsUsed to Format

Output Data

80

Counters: Similar in concept to an Accumulator variable is aCounter variable. An accumulator increases a running total by a varyingamount each time, but a counter increases a running total by a fixedamount each time. For example, a Counter variable would be

intCounter = intCounter + 1I

Each time the line is encountered, it would increment the countervariable by one. Most counters increment by one, but any other value couldbe used, such as by counting by 2 or 3, etc. It could also decrement byusing a minus sign instead of a plus sign.

Using an accumulator and a counter would be an easy way todetermine the average by dividing the accumulator variable by the countervariable. For example, the average sales could be computed by dividing thetotal value of sales (the accumulator) by the number of sales (the counter).Accumulators and Counters are also frequently used in loops and repetitiveoperations which will be covered in a later chapter.

Depending upon how the programming algorithm is set up, it maybe necessary to give either the accumulator or counter variables modular-level scope so they won’t lose their values when the program flow exits theevent procedure. However, if everything is contained within the localprocedure, local scope should be used.

InfInfInfInfInfororororormamamamamational Messational Messational Messational Messational Messaggggge Boe Boe Boe Boe BoxxxxxesesesesesSometimes you need a convenient way to give a message to the

user without having to provide the information in a label on the form. Thiscan be accomplished using a Message Box, as shown in figure 4.7.

Message Boxes can be used to give the result of a computation, toinform a user that the wrong type of data was entered, or to signal thecompletion of a routine or task. They are shown in the middle of thescreen, and the user must respond to the message by clicking a button on

the message box before con-tinuing.

The typical messagebox, as shown in Figure 4.8,has four parts: the title (orcaption), the text (or prompt),the OK button, and the icon.The Text is the most importantpart because it provides theinformation the user needs. TheCaption is the title shown at thetop of the Message Box. The

Figure 4.7Sample

InformationalMessage Box

81

Figure 4.9Message Box

Icons

Button allows the user to respond, and by default shows “OK” as its text.The icon is optional, but can be used as a graphic image for the user. Theseparts of the Message Box are identified in Figure 4.8

Figure 4.8Four parts of a

InformationalMessage Box

Caption

Icon

Text Message

Button

MessageBoxIcon.Information

MessageBoxIcon.Exclamation

MessageBoxIcon.Stop

IconsIconsIconsIconsIcons PrPrPrPrProoooogggggrrrrramming codeamming codeamming codeamming codeamming code

Most of the parts have several options so the message box can becustomized to fit a wide variety of applications. For example, both the Textand Caption are text strings the programmer provides. Six possible buttoncombinations are allowed, but if the purpose of the Message Box is tomerely inform the user, then only the single OK button should be used.Decision Message Boxes (to be covered in the next chapter) require theuser to select between various buttons, and the button selected will deter-mine future actions of the program.

Four icons can be used depending on the purpose of the message,but for Informational Message Boxes, only the three icons shown in Figure4.9 should be used.

The programming code to show a Message Box uses theMessageBox.Show method. The general format for this statement is

MessageBox.Show(“Text”,”Caption”,button,icon)

82

Both the Text and Caption arguments are text strings, and must beenclosed inside double quotation marks. The code for the OK button isMessageBoxButtons.OK and the code to show the information icon isMessageBoxIcon.Information. (The code to show the other buttons andicons will be covered in the next chapter.) The arguments are separated bya comma.

If the caption text string is omitted, the title bar will be blank. If thebutton code is omitted, the OK button will show, and if the icon code isomitted, no icon will show on the Message Box. However, if the Textstring is omitted, you will receive an error message.

Variables and constants are permitted in the Text string in similarfashion as used to display text strings and variables in label controls.Concatenation and Line Continuation characters can also be used.

The complete code is shown below, and the resulting Message boximage is shown in Figure 4.10.

MessageBox.Show(“The transaction is complete.”, _ “Cactus Mail Order Sales”, _ MessageBoxButtons.OK, _ MessageBoxIcon.Information)

More will be said about message boxes in the next chapter.

Hands-On PrHands-On PrHands-On PrHands-On PrHands-On Prooooogggggrrrrramming Exampleamming Exampleamming Exampleamming Exampleamming ExampleAs in the previous chapter, this hands-on project is provided to help

you understand the concepts in this chapter to a higher level. You shouldattempt to complete the project on your own without looking at the solu-tion. And, then after your attempt, compare your project with the projectthat follows.

Figure 4.10Completed

Message Box

83

Step 1 – Plan the Project

TTTTThe Prhe Prhe Prhe Prhe Projectojectojectojectoject

Create a project that will compute the value of a base numberraised to an exponential value. The project should allow the user to enter abase number and an exponent (both whole numbers), and have the correctvalue displayed on the form. The user interface will have two text boxesfor entering the values, a label for displaying the result, and three buttons:one to perform the calculation, one to clear the contents of the text boxes,and one to end the project.

Planning the ActionPlanning the ActionPlanning the ActionPlanning the ActionPlanning the Action

The user will supply a base number and an exponent value, thenclick the Calculate button to show the result. A message box will notify theuser that the calculation is complete. Clicking the Clear button will clearthe contents of both text boxes, the label, and reset the focus to a text box.Clicking the End button will terminate the project.

The pseudocode for the Compute button will be:1. Declare the needed variables.2. Read the values from the text boxes into the variables.3. Perform the calculation using the variables.4. Display the formatted results on the form.5. Display a message box to the user.

The pseudocode for the Clear button will be:1. Clear both input text boxes.2. Clear the output label.3. Reset the focus to a text box.

The pseudocode for the Exit button will be:1. Terminate the program.

Step 2 – Create the User Interface

PPPPPopulaopulaopulaopulaopulating the Fting the Fting the Fting the Fting the Fororororormmmmm

Place the following objects on the form, and arrange them to match Figure4.11:

2 Text Boxes 5 Labels 3 Buttons

Pseudocode

84

Setting the PrSetting the PrSetting the PrSetting the PrSetting the Properoperoperoperopertiestiestiestiesties

Set the following properties for each object:

Object Property SettingForm Text Exponent Calculator

AcceptButton btnCalculateCancelButton btnClearStartPosition CenterScreen

TextBox1 Name txtBaseText (blank)

TextBox2 Name txtExponentText (blank)

Label1 Name (unnamed)Text Raising to the powerFontStyle Bold Italics

Label2 Name (unnamed)Text Exponent

Label3 Name (unnamed)Text Base

Label4 Name (unnamed)Text = [the equal sign]

Label5 Name lblResultText (blank)AutoSize TrueBorderStyle Fixed3DFontSize 14 pt.

Button1 Name btnCalculateText &Calculate

Button2 Name btnClearText Clea&r

Button3 Name btnExitText &Exit

85

Step 3 – Write the Code

You will need to write code for each of the following Event proce-dures. Start by wring the comment lines which come from the pseudocode:

Event Procedure Comment Lines (from the pseudocode)btnCalculate_Click ‘Perform exponent calculation

‘Declare local variables‘Initialize variables using parse method‘Perform calculation using variables‘Display formatted results in label‘Display message box

btnClear_Click ‘Clear both text boxes and label‘Reset the focus to Base text box

btnExit_Click ‘Terminates the program

Complete the EvComplete the EvComplete the EvComplete the EvComplete the Event Prent Prent Prent Prent Procedurocedurocedurocedurocedure Codee Codee Codee Codee Code

‘Programmer: Don Hoggan‘Title: Exponent Calculator‘Class: CIS 001‘Description: This project will compute the result‘ of raising a base number by the‘ exponent value

ProjectComment

Lines

Figure 4.11Completed

ExponentCalculator

Project UserInterface

86

Public Class Form1

Private Sub btnExit_Click(ByVal sender As _System.Object, ByVal e As System.EventArgs) HandlesbtnExit.Click ‘Terminates the program Me.Close()End Sub

Private Sub btnCalculate_Click(ByVal sender AsSystem.Object, ByVal e As System.EventArgs) HandlesbtnCalculate.Click ‘Performs Exponent calculation

‘Declare local variables Dim intBase As Integer Dim intExponent As Integer Dim intResult As Integer

‘Initialize variables intBase = Integer.Parse(txtBase.Text) intExponent = Integer.Parse(txtExponent.Text)

‘Perform calculation intResult = intBase ^ intExponent

‘display formatted results in label lblResult.Text = intResult.ToString(“n0”)

‘Display message box MessageBox.Show(“The computation is complete.”, _ “Exponent Calculator”, MessageBoxButtons.OK, _ MessageBoxIcon.Information)End Sub

Private Sub btnClear_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles btnClear.Click ‘Resets controls to start-up stats txtBase.Clear() txtExponent.Clear() lblResult.Text = “” txtBase.Focus()End Sub

End Class

btnClear_Clickevent procedure

btnExit_Clickevent procedure

btnCalculate_Click

event procedure

87

Step 4 – Test and Debug the Program

1. When running the program, the form should center on the screenwith the cursor blinking in the base text box.

2. Enter a 2 in the base text box and a 10 in the exponent text box,and then click the Calculate button. A message box should appearinforming the user that the calculation is complete. After pressingthe OK button on the message box, the label on the form shouldshow 1,024.

3. Click the Clear button and the text boxes and label should all becleared, and the blinking cursor should show in the Base text box.

4. Test the Tab sequence.5. Test the Keyboard Access keys.6. Click the End button and the project should terminate.

1. Variables and constants are temporary memory locations that have aname, data type, and a scope. The value contained in a variable can bechanged while the program is running, but a constant cannot bechanged.

2. Data types are like storage containers that hold values (numbers orstrings). Like containers, they are designed to hold different types ofdata.

3. The most common data types are Integer, Decimal, String andBoolean. Lesser used data types include Single, Double, Long, Short,Date, Char, and Byte. The Object data type is the default, and shouldonly be used when none of the others will work.

4. Variable and constant names must conform to the Visual Basic namingrules, and should contain specific lowercase prefixes to identify thedata type and be meaningful to its intended contents to aid inidentifying the data.

5. Variables are named using the Dim, Private, or Public keywords, andscope is assigned based on the location where the declarationstatement appears.

6. The scope of a variable can be local, modular-level, or global. Localvariables are active only within the event procedure where they aredeclared. Module-level variables are active in any event procedure onthe module sheet, and global variables are active anywhere within theproject. The lowest level possible should be used when assigningscope.

ChaChaChaChaChapter Summarpter Summarpter Summarpter Summarpter Summaryyyyy

88

7. Calculations can be performed using addition, subtraction,multiplication, division, Integer division, Modulus division, andexponentiation. When a formula has multiple arithmetic operators, theorder of arithmetic operations determines the order used to solveformulas. Parentheses can be used to alter the default order.

8. Numbers normally need to be converted into a numeric data type usinga conversion method before it can be used to perform calculations. Thepreferred method of conversion is using the Parse method.

9. Numeric values also need to be converted into the String data typebefore being placed in the Text property of a control. The ToStringmethod is used for conversions to the String data type.

10. String data can be formatted by placing dollar signs, comma separators,percent signs, etc. while it is being converted to a String data type.

11. Accumulators are used to maintain a running total by adding a varyingamount to the running total. Counters increase a running total by afixed amount, usually 1, each occurrence.

12. Message Boxes can be used to provide temporary and immediateinformation to the user without displaying the information in a controlon the form. Message boxes have the informational message, a title orcaption, and a button for the user to respond. They may also display anicon.

KKKKKeeeeey y y y y TTTTTererererermsmsmsmsms

accumulator identifier Private keywordBoolean initialize PromptCaption Integer Public keywordcasting Integer division reserved wordsChar Key words scopeConst Message box Stringconstant module ToStringcounter Modulus type declaration characterdata type Namespace variableDeclaration statement Naming rulesDim Parse

RRRRReeeeevievievievieview Questionsw Questionsw Questionsw Questionsw Questions

1. Explain the difference between a variable and a constant.2. What is an “identifier”?3. What is a “data type”? Name the four most common data types. Give

the main characteristics or use of each.4. Name the eight other data types. When should they be used?

89

5. How are variables created? What keywords are necessary?6. How is a data type assigned to a variable?7. What are the required naming rules for declaring variables?8. Indicate whether each of the following variable names conform to the

recommended naming rules. If the name is not correct, give the reasonand provide a correct alternative:

a. AverageAge d. intQuantity g. str$Addressb. conCompanyName e. strPayRate h. intPhoneNumberc. Private f. Minimum Wage i. 77points

9. When a numeric variable is created, what is its original value? What isa string variable initialized to?

10. How is a constant declared? What keywords are used?11. What is meant by “scope”? How is scope level determined?12. What is the difference between local and module-level scope? Module-

level and global scope?13. What level of scope should be used in normal situations? When should

modular-level scope be used? When can global scope be justified?14. Write a declaration statement to declare the following variables:

a. the number of hours an employee works (allow decimal point)b. an employee’s namec. the account number for a charge accountd. a variable for the number of employees in a department

15. What is the difference between complex and simple arithmetic?16. What is the “Order of Arithmetic Operations”? Give the levels from

highest to lowest? How do parentheses effect the order?17. Calculate the correct answer to the following problems:

a. 12 / 4 + 1 + 12 * 2 - 5 c. 5 + 9 / 3 - 16 / 2 + 3 * 7b. ( 7 + 5 ) / 3 + 9 * 3 - 5 d. 16 / 2 ^ 2 + 9 / 3

18. What is the difference between regular division and Interger division?Interger and Modulus division?

19. Which arithmetic symbols are used for regular, Integer, and modulardivision?

20. What is the result of each of the following calculations?a. 10 / 3? c. 10 mod 3?b. 10 \ 3? d. 10 ^ 3?

21. Why does the numeric contents of a text box need to be converted to anumeric data type before it can be used in a calculation? What methodis used to perform the conversion?

22. What method is used to convert a numeric variable to a stringvariaiable?

23. How is formatting symbols (dollar signs, percent signs, etc.) insertedin data to be displayed in a label?

24. What is the difference between an accumulator and a counter?25. What is the purpose of a message box?26. What are the four parts of a typical message box?

90

VVVVVocaocaocaocaocabbbbbularularularularulary Cry Cry Cry Cry Crossossossossosswwwwworororororddddd

Solve the crossword puzzle using the clues below. All terms are inthis chapter or previous chapters.

AAAAACRCRCRCRCROSSOSSOSSOSSOSS3. A data type that only has two possible values.6. A named placeholder for a value that can be changed.8. A method to cast data from one data type to another data type.10. A value that can not change while the program is running.11. A data type for text, numbers, and other characters.12. The process of raising a number to its power.

DODODODODOWNWNWNWNWN1. An arithmetic operation resulting in a fractional remainder.2. A numeric data type for whole numbers.4. The area of influence for a variable or constant.5. Giving a variable or constant its original value.7. A variable used to keep a running total.9. A method used to convert a numeric value to a text data type.

91

PrPrPrPrProoooogggggrrrrramming Pramming Pramming Pramming Pramming Practiceacticeacticeacticeactice

Exercise 4-1. Writing codeWrite a single line of Visual Basic code to accomplish each of the

following:a. Declare the variable blnGender as a local boolean variable.b. Declare the variable intQuantity as a modular-level integer

variable.c. Assign the string Jenny to the variable strFirstName.d. Assign the value 1234 to the label lblPrice and format it to show

a dollar sign with no decimal places.e. Set the focus to the txtQuantity text box.f. Increment the variable intCount by 1.g. Increment the variable decYTD by decGrossPay.

Exercise 4-2. Miles per Gallon CalculatorCreate a project that will calculate a car’s gas mileage. The form

will have text boxes that the user will fill in the number of miles driven,and the number of gallons of gas used. The miles per gallon will be dis-played in a label. Format the result to one decimal point. Include buttons toclear the entries and result, and a button to end the project. Use the decimaldata type for all entries. Test your project with the following inputs: 39.7gallons used and 1022.6 miles driven. The miles per gallon should be 25.8.

Exercise 4-3. Baseball Slugging Percentage CalculatorIn baseball, the Slugging Percentage statistic accounts for the

number of bases a player gets when batting. Home runs count as 4 bases,Triples count as 3 bases, Doubles count as 2 bases, and Singles count as 1base. No bases are given if the player makes an out. Other outcomes at batare not considered, such as bases on balls, hit batters, sacrifices, fielder’schoices, etc. are not counted.

Create a project that will compute the Slugging percentage. ProvideText Boxes for Home Runs, Triples, Doubles, Singles, and Total At-Bats.Display the slugging percentage in a label formatted to three decimalplaces. Declare variables as needed. Use local scope. Use the followingstatistics to test your project: At Bats = 90, Singles = 15, Doubles = 5,Triples = 2, and Home Runs = 4. The Slugging percentage should be .522.

Exercise 4-4. Basketball ScorekeeperAssume you are the scorekeeper for your son’s or daughter’s after

school basketball team. Create a project that will compute an individual’sseason statistics for shooting and rebounds. The inputs will be the numberof Free Throws, Field Goals, 3-Point Field Goals, and Rebounds. Theoutput will give the Total Points, Points per game, and Rebounds per

92

game. Remember that Free Throws earn 1 point each, Field Goals earn 2points each, and 3-Point Field Goals earn 3 points each. Declare variablesas needed. Format the Points per game and Rebounds per game to onedecimal point. Use the following to test your results: 16 Free Throws, 32Field Goals, 5 Three-point Goals, 50 Rebounds, and 12 games played. ThePoints per game should be 7.9 and the Rebounds per games should be 4.2.

Exercise 4-5. Currency Conversion.Assume you have decided to organize a tour group of your friends

to tour Europe. You know you will need to convert your U.S. currency tothe British Pound and European Euro as you arrive on foreign soil. Create aVisual Basic program that will compute the amount in Pounds and Eurosthat you will have after the conversion. Input an amount in U.S. currency ina text box, and the output will show both Pounds and Euros in separatelabels. The calculation should occur when a Convert button is clicked. Alsoinclude a Clear and an End button on your form. Assume the exchange ratefrom U.S. to Pounds is 0.627 and from U.S. to Euros is 0.696. You mayinclude the exchange rate inside your program, or place two additional textboxes on your form for the rates. Be sure proper data type conversionsoccur. Ignore exchange fees or commissions. To test your program, input$350 U.S.; you should receive 219.45 Pounds and 243.6 Euros.