2. The Visual Basic .NET Language
Review and Preview
• In the first class, we found there were three primary steps involved in developing a Windows application using Visual Basic .NET:
1. Draw the user interface
2. Assign properties to controls
3. Write code for events
In this class, we are primarily concerned with Step 3, writing code. We will become more familiar with moving around in the Code window and learn some of the elements of the BASIC language.
A Brief History of BASIC
• The BASIC language was developed in the early 1960's at Dartmouth College as a device for teaching programming to “ordinary” people. There is a reason it’s called BASIC:
B (eginner's)
A (All-Purpose)
S (Symbolic)
I (Instruction)
C (Code)
• When timesharing systems were introduced in the 1960’s, BASIC was the language of choice. Many of the first computer simulation games (Star Trek, for example) were written in timeshare BASIC.
• In the mid-1970's, two college students decided that the new Altair microcomputer needed a BASIC language interpreter. They sold their product on cassette tape for a cost of $350. You may have heard of these entrepreneurs: Bill Gates and Paul Allen!
• Every BASIC written since then has been based on that early version. Examples include: GW-Basic, QBasic, QuickBasic. All the toy computers of the early 80’s (anyone remember TI99/4A, Commodore 64, Timex, Atari 400?) used BASIC for programming.
• Visual Basic (allowing development of Windows applications) was first introduced in 1991. The latest (and last) version of Visual Basic is Version 6.0, which was released in 1997.
• Visual Basic .NET still uses the BASIC language to write code. Visual Basic .NET provides a long overdue enhancement to the language with many new features. In addition, many archaic features than have been around since Bill and Paul’s earliest efforts have finally been retired. This chapter provides an overview of the BASIC language used in the Visual Basic .NET environment. If you’ve ever used another programming language (or some version of BASIC), you will see equivalent structures in the language of Visual Basic .NET.
Visual Basic .NET Statements and Expressions
• The simplest (and most common) statement in Visual Basic .NET is the assignment statement. It consists of a variable name, followed by the assignment operator (=), followed by some sort of expression. The expression on the right hand side is evaluated, then the variable (or property) on the left hand side of the assignment operator is replaced by that value of the expression.
Examples:
StartTime = Now
lblExplorer.Text = "Captain Spaulding"
BitCount = ByteCount * 8
Energy = Mass * LIGHTSPEED ^ 2
NetWorth = Assets - Liabilities
The assignment statement stores information.
• Statements normally take up a single line with no terminator. Statements can be stacked by using a colon (:) to separate them. Example:
StartTime = Now : EndTime = StartTime + 10
The above code is the same as if the second statement followed the first statement. Be careful stacking statements, especially with If/End If structures (we’ll learn about these soon). You may not get the response you desire. The only place we tend to use stacking is for quick initialization of like variables.
• If a statement is very long, it may be continued to the next line using the continuation character, an underscore (_). Example:
Months = Math.Log(Final * IntRate / Deposit + 1) _
/ Math.Log(1 + IntRate)
We don’t use continuation statements very much in these notes or in our examples. Be aware that long lines of code in the notes many times wrap around to the next line (due to page margins).
• Comment statements begin with the keyword Rem or a single quote ('). For example:
Rem This is a remark
' This is also a remark
x = 2 * y ' another way to write a remark or comment
You, as a programmer, should decide how much to comment your code. Consider such factors as reuse, your audience, and the legacy of your code. In our notes and examples, we try to insert comment statements when necessary to explain some detail.
Strict Type Checking
• In each assignment statement, it is important that the type of data on both sides of the operator (=) is the same. That is, if the variable on the left side of the operator is an Integer, the result of the expression on the right side should be Integer.
• Visual Basic .NET (by default) will try to do any conversions for you. Sometimes, however, it ‘guesses’ incorrectly and may provide incorrect or undesired results. To insure consistency of data types in assignment statements, Visual Basic .NET offers, as an option, strict type checking. What this means is that your program will not run unless each side of an assignment operator has the same type of data. With strict type checking, the Intellisense feature of the Code window will identify where there are type inconsistencies and provide suggestions on how to correct the situation.
• Strict type checking will force you to write good code and eliminate many potential errors. Because of this, all examples for the remainder of this course will use strict type checking. To turn on strict type checking, we place a single line of code at the top of each application:
Option Strict On
This line will go right below the Option Explicit On line which forces us to declare each variable we use.
• Remember, every application should have the above two lines at the top of the code window. So, as a rule, every new application’s code window should immediately be changed to appear like this:
This will enforce both explicit variable declaration and type checking across the assignment operator, both very good programming practices.
•
• Strict type checking also means we need ways to convert one data type to another. Visual Basic .NET offers a wealth of functions that perform these conversions. Some of these functions are:
CBool(Expression) Converts a numerical Expression to a Boolean data type (if Expression is nonzero, the result is True, otherwise the result is False)
CDate(Expression) Converts any valid date or time Expression to a Date data type
CDbl(Expression) Converts a numerical Expression to a Double data type
CInt(Expression) Converts a numerical Expression to an Integer data type (any fractional parts are rounded up)
CLng(Expression) Converts a numerical Expression to a Long data type (any fractional parts are rounded up)
CShort(Expression) Converts a numerical Expression to a Short data type (any fractional parts are rounded up)
CSng(Expression) Converts a numerical Expression to a Single data type
CType(Expression, Type) Converts the Expression to the specified Type
• We will use many of these conversion functions as we write code for our applications and examples. The Intellisense feature of the code window will usually direct us to the function we need.
Visual Basic .NET Arithmetic Operators
• Operators modify values of variables. The simplest operators carry out arithmetic operations. There are seven arithmetic operators in Visual Basic .NET.
• Addition is done using the plus (+) sign and subtraction is done using the minus (-) sign. Simple examples are:
Operation Example Result
Addition 7 + 2 9
Addition 3.4 + 8.1 11.5
Subtraction 6 - 4 2
Subtraction 11.1 – 7.6 3.5
• Multiplication is done using the asterisk (*) and division is done using the slash (/). Simple examples are:
Operation Example Result
Multiplication 8 * 4 32
Multiplication 2.3 * 12.2 28.06
Division 12 / 2 6
Division 45.26 / 6.2 7.3
• The next operator is the exponentiation operator, represented by a carat symbol (^) or sometimes called a ‘hat.’ Some examples:
Example Result
5 ^ 2 25
2.6 ^ 4 45.6976
3.7 ^ 3.1 57.733162065075
Notice exponentiation is not limited to whole numbers (do you know how to multiply 3.7 times itself 3.1 times?).
• The other arithmetic operators are concerned with dividing integer numbers. The integer division operator is a backslash character (\). This works just like normal division except only integer (whole number) answers are possible - any fraction from the division is ignored. Conversely, the modulus operator, represented by the keyword Mod, divides two whole numbers, ignores the main part of the answer, and just gives you the remainder! It may not be obvious now, but the modulus operator is used a lot in computer programming. Examples of both of these operators are:
Operation Example Division Result Operation Result
Integer division 7 \ 2 3.5 3
Integer division 23.2 \ 10 2.32 2
Integer division 25.2 \ 3.6 7.0 7
Modulus 7 Mod 4 1 Remainder 3 3
Modulus 14 Mod 3 4 Remainder 2 2
Modulus 25 Mod 5 5 Remainder 0 0
• The mathematical operators have the following precedence indicating the order they are evaluated without specific groupings:
1. Exponentiation (^)
2. Multiplication (*) and division (/)
3. Integer division (\)
4. Modulus (Mod)
5. Addition (+) and subtraction (-)
If multiplications and divisions or additions and subtractions are in the same expression, they are performed in left-to-right order. Parentheses around expressions are used to force some desired precedence.
Comparison and Logical Operators
• There are six comparison operators in Visual Basic .NET used to compare the value of two expressions (the expressions must be of the same data type). These are the basis for making decisions:
Operator Comparison
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
= Equal to
<> Not equal to
It should be obvious that the result of a comparison operation is a Boolean value (True or False). Examples:
A = 9.6, B = 8.1, A > B returns True
A = 14, B = 14, A < B returns False
A = 14, B = 14, A >= B returns True
A = 7, B = 11, A <= B returns True
A = “Visual”, B=”Visual”, A = B returns True
A = “Basic”, B = “Basic”, A <> B returns False
• Logical operators operate on Boolean data types, providing a Boolean result. They are also used in decision making. We will use three logical operators
Operator Operation
Not Logical Not
And Logical And
Or Logical Or
• The Not operator simply negates a Boolean value. It is very useful for ‘toggling’ Boolean variables. Examples:
If A = True, then Not(A) = False
If A = False, then Not(A) = True
• The And operator checks to see if two different Boolean data types are both True. If both are True, the operator returns a True. Otherwise, it returns a False value. Examples:
A = True, B = True, then A And B = True
A = True, B = False, then A And B = False
A = False, B = True, then A And B = False
A = False, B = False, then A And B = False
• The Or operator checks to see if either of two Boolean data types is True. If either is True, the operator returns a True. Otherwise, it returns a False value. Examples:
A = True, B = True, then A Or B = True
A = True, B = False, then A Or B = True
A = False, B = True, then A Or B = True
A = False, B = False, then A Or B = False
• Logical operators follow arithmetic operators in precedence. Use of these operators will become obvious as we delve further into coding.
Concatenation Operators
• To concatentate two string data types (tie them together), use the & symbol or the + symbol, the string concatenation operators:
lblTime.Text = "The current time is" & Format(Now, “hh:mm”)
txtSample.Text = "Hook this “ + “to this”
Be aware that I use both concatenation operators (primarily the + sign) in these notes – I’m not very consistent (an old habit that’s hard to break).
• Visual Basic .NET offers other concatenation operators that perform an operation on a variable and assign the resulting value back to the variable. Hence, the operation
A = A + 1
Can be written using the addition concatenation operator (+=) as:
A += 1
This says A is incremented by 1.
• Other concatenation operators and their symbols are:
Operator Name Operator Symbol Operator Task
String A &= B A = A & B
String A += B A = A + B
Addition A += B A = A + B
Subtraction A -= B A = A – B
Multiplication A *= B A = A * B
Division A /= B A = A / B
Integer Division A \= B A = A \ B
Exponentiation A ^= B A = A ^ B
Notice both &= and += can be used as the string concatenator.
Visual Basic .NET Functions
• Visual Basic .NET offers a rich assortment of built-in functions that compute or provide various quantities. The on-line help utility will give you information on any or all of these functions and their use. The general form of a function is:
ReturnedValue = FunctionName(Arguments)
where Arguments represents a comma-delimited list of information needed by FunctionName to perform its computation. Once the arguments are supplied to the function it returns a value (ReturnedValue) for use in an application.
• Some example functions are:
Function Returned Value
Asc ASCII or ANSI code of a character
Chr Character corresponding to a given ASCII or ANSI code
Format Date or number converted to a text string
Instr Locates a substring in another string
Len Number of characters in a text string
Mid Selected portion of a text string
Now Current time and date
Rnd Random number between 0 and 1
Str Number converted to a text string
Timer Number of seconds elapsed since midnight
Trim Removes leading and trailing spaces from string
Val Numeric value of a given text string
String Functions
• Visual Basic .NET offers a powerful set of functions to work with string type variables, which are very important in Visual Basic .NET. The Text property of the label control and the text box control are string types. You will find you are constantly converting string types to numeric data types to do some math and then converting back to display the information.
• To convert a string type to a numeric value, use the Val function. As an example, to convert the Text property of a text box control named txtExample to a number, use:
Val(txtExample.Text)
This result can then be used with the various mathematical operators. The returned data type is Double. If you need the returned value to be some other data type, use one of the conversion functions seen earlier.
• There are two ways to convert a numeric variable to a string. The Str function does the conversion with no regard for how the result is displayed. This bit of code can be used to display the numeric variable MyNumber in a text box control:
MyNumber = 3.14159
txtExample.Text = Str(MyNumber)
If you need to control the number of decimal points (or other display features), the Format function is used. This function has two arguments, the first is the number, the second a string specifying how to display the number (use on-line help to see how these display specifiers work). As an example, to display MyNumber with no more than two decimal points, use:
MyNumber = 3.14159
txtExample.Text = Format(MyNumber, “#.##”)
In the display string (“#.##”), the pound signs represent place holders.
• Many times, you need to extract substrings from string variables. The Mid function lets you extract a specified number of characters from anywhere in the string (you specify the string, the starting position and the number of characters to extract). This example extracts 6 characters from the string variable, starting at character 3:
MyString = “Visual Basic .NET is fun!”
MidString = Mid(MyString, 3, 6)
The MidString variable is equal to “sual B”
• Perhaps, you just want a far left portion of a string. Use the Mid function with a starting position of 1. This example extracts the 3 left-most characters from a string:
MyString = “Visual Basic .NET is fun!”
LeftString = Mid(MyString, 1, 3)
The LeftString variable is equal to “Vis”
• Getting the far right portion of a string with the Mid function is just a bit trickier. First, we need to introduce the Len function, which tells us the number of characters in (or length of) a string variable. For our example,
MyString = “Visual Basic .NET is fun!”
LenString = Len(MyString)
LenString will have a value of 25. Now, if we want the 6 far right characters in the string example, we use:
MyString = “Visual Basic .NET is fun!”
RightString = Mid(MyString, Len(MyString) – 6 + 1, 6)
The RightString variable is equal to “s fun!” Note that without the + 1 in the second argument, we would start one character too far to the left.
• The Mid function can also be used to replace substrings in string variables, working in a reverse manner. Again, just specify the string, the starting position and number of characters to replace, but use the Mid function on the left side of the assignment operator. With our example, try:
MyString = “Visual Basic .NET is fun!”
Mid(MyString, 15, 3) = “net”
After this replacement, MyString will now have a value of:
MyString = “Visual Basic .net is fun!”
• To locate a substring within a string variable, use the Instr function. Three arguments are used: starting position in String1 (optional), String1 (the variable), String2 (the substring to find). The function will work left-to-right and return the location of the first character of the substring (it will return 0 if the substring is not found). For our example:
MyString = “Visual Basic .NET is fun!”
Location = Instr(3, MyString, “sic”)
This says find the substring “sic” in MyString, starting at character 3 (if this argument is omitted, 1 is assumed). The returned Location will have a value of 10.
• Related to the Instr function is the InstrRev function. This function also identifies substrings using identical arguments, but works right-to-left, or in reverse. So, with our example string:
MyString = “Visual Basic .NET is fun!”
Location = InstrRev(MyString, “is”)
This says find the substring “is” in MyString, starting at the right and working left. The returned Location will have a value of 20. Note is we use Instr instead, the returned Location would be 2.
• Many times, you want to convert letters to upper case or vice versa. Visual Basic .NET provides two functions for this purpose: UCase and LCase. The UCase function will convert all letters in a string variable to upper case, while the LCase function will convert all letters to lower case. Any non-alphabetic characters are ignored in the conversion. And, if a letter is already in the desired case, it is left unmodified. For our example (modified a bit):
MyString = “Visual Basic .NET in 2002 is fun!”
A = UCase(MyString)
B = LCase(A)
The first conversion using UCase will result in:
A = “VISUAL BASIC .NET IN 2002 IS FUN!”
And the second conversion using LCase will yield:
B = “visual basic .net in 2002 is fun!”
• Another useful pair of functions are the Asc and Chr functions. These work with individual characters. Every ‘typeable’ character has a numeric representation called an ASCII (pronounced “askey”) code. The Asc function returns the ASCII code for an individual character. For example:
Asc(“A”)
returns the ASCII code for the upper case A (65, by the way). The Chr function returns the character represented by an ASCII code. For example:
Chr(48)
returns the character represented by an ASCII value of 48 (a “1”). The Asc and Chr functions are used often in determining what a user is typing.
Random Number (Rnd) Function
• In writing games and learning software, we use the Rnd function to introduce randomness. This fun function insures different results each time you try a program. The Visual Basic .NET function Rnd returns a single precision, random number between 0 and 1 (actually greater than or equal to 0 and less than 1). To produce random integers (I) between Imin and Imax, use the formula:
I = CInt(Rnd() * (Imax - Imin + 1) – 0.5) + Imin
The - 0.5 is needed in the above expression because the CInt function rounds fractional parts up to the next highest integer. Without it, the highest value of I would actually be Imax + 1!
• The random number generator in Visual Basic .NET must be seeded. A Seed value initializes the generator. The Randomize statement is used to do this:
Randomize Seed
If you use the same Seed each time you run your application, the same sequence of random numbers will be generated. To insure you get different numbers every time you use your application (preferred for games), use the Randomize statement without a seed (it will be seeded using the built-in Timer function):
Randomize
Place the above statement in the Form_Load event procedure (to find that procedure in the Code window, either double-click the form or choose (Base Class Events) in the Object window and Load in the Event window).
• Examples using the Rnd function:
To roll a six-sided die, the number of spots would be computed using:
NumberSpots = CInt(Rnd() * 6 – 0.5) + 1
To randomly choose a number between 100 and 200, use:
Number = CInt(Rnd() * 101 – 0.5) + 100
Math Functions
• A last set of functions we need are mathematical functions (yes, programming involves math!) Visual Basic .NET provides a set of functions that perform tasks such as square roots, trigonometric relationships, and exponential functions.
• Each of the Visual Basic .NET math functions comes from the Math class of the .NET framework (an object-oriented programming concept). All this means is that each function name must be preceded by Math. (say Math-dot) to work properly. The functions and the returned values are:
Math Function Value Returned
Math.Abs Returns the absolute value of a specified number
Math.Atan Returns a Double value containing the angle whose tangent is the specified number
Math.Cos Returns a Double value containing the cosine of the specified angle
Math.Exp Returns a Double value containing e (the base of natural logarithms) raised to the specified power
Math.Log Returns a Double value containing the logarithm of a specified number
Math.Sign Returns an Integer value indicating the sign of a number
Math.Sin Returns a Double value containing the sine of the specified angle
Math.Sqrt Returns a Double value specifying the square root of a number
Math.Tan Returns a Double value containing the tangent of an angle
• Examples:
Math.Cos(2.3) returns the cosine of an angle of 2.3 radians
Math.Sign(-3) returns the sign on –3 (returns a –1)
Math.Sqrt(4.5) returns the square root of 4.5
Example 2-1
Savings Account
1. Start a new project. The idea of this project is to determine how much you save by making monthly deposits into a savings account. For those interested, the mathematical formula used is:
F = D [ (1 + I)M - 1] / I
where
F - Final amount
D - Monthly deposit amount
I - Monthly interest rate
M - Number of months
2. Place 4 labels, 4 text boxes, and 2 buttons on the form. It should look something like this:
3. Set the properties of the form and each object.
Form1:
Name frmSavings
FormBorderStyle Fixed Single
Starting Position CenterScreen
Text Savings Account
Label1:
Text Monthly Deposit
Label2:
Text Yearly Interest
Label3:
Text Number of Months
Label4:
Text Final Balance
Text1:
Name txtDeposit
Text [Blank]
Text2:
Name txtInterest
Text [Blank]
Text3:
Name txtMonths
Text [Blank]
Text4:
Name txtFinal
BackColor White
ReadOnly True
Text [Blank]
Button1:
Name btnCalculate
Text &Calculate
Button2:
Name btnExit
Text E&xit
Now, your form should look like this:
4. Declare four variables under the Windows Form Designer generated code line in the Code window. This gives them form level scope, making them available to all the form procedures:
Dim Deposit As Double
Dim Interest As Double
Dim Months As Double
Dim Final As Double
At this point, the Code window should look like this:
5. Write code for the btnCalculate button Click event (remember to select the btnCalculate object from the object box and the Click event from the event box):
Private Sub btncalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncalculate.Click
Dim IntRate As Double
'read values from text boxes
Deposit = Val(txtDeposit.Text)
Interest = Val(txtInterest.Text)
IntRate = Interest / 1200
Months = Val(txtMonths.Text)
'compute final value and put in text box
Final = Deposit * ((1 + IntRate) ^ Months - 1) / IntRate
txtFinal.Text = Format(Final, "0.00")
End Sub
This code reads the three input values (monthly deposit, interest rate, number of months) from the text boxes, converts those string variables to number using the Val function, converts the yearly interest percentage to monthly interest (IntRate) computes the final balance using the provided formula, and puts that result in a text box (after converting it back to a string variable).
6. Now, write code for the btnExit button Click event.
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub
7. Play with the program. Make sure it works properly. Save the project (Example 2-1 folder in the LearnVBN\VBN Code\Class 2 folder).
Tab Stops and Tab Order
• When you run Example 2-1, you should have noticed the cursor didn’t necessarily start out at the top text box where you enter the Monthly Deposit. And, if you try to move from text box to text box using the
• When interacting with a Windows application, we can work with a single control at a time. That is, we can click on a single button or type in a single text box. We can’t be doing two things at once. The control we are working with is known as the active control or we say the control has focus. In our savings account example, when the cursor is in a particular text box, we say that text box has focus. In a properly designed application, focus is shifted from one control to another (in a predictable, orderly fashion) using the
• To define an orderly Tab response, we do two things. First, for each control you want accessible via the
• There are two ways to set TabIndex values. You can set the property of each control using the Properties window. This is tedious especially when new controls are introduced to the form. The Visual Basic .NET IDE offers a great tool for setting the TabIndex property of all controls. To show how to use this tool requires a little example.
• Start a new project in Visual Basic .NET. Add two text boxes and two buttons to the form. Make your form look something like this:
(By the way, this is something you can easily do with Visual Basic .NET – set up quick examples to try different things.) By default, each control will have a TabStop of True and some value of TabIndex. Run the application. Yes, I know there is no code, but that’s OK. Press the
• Now, we’ll change the TabIndex properties. With the form selected (has resizing handles), choose the View menu option, and choose Tab Order. You should see this:
The little blue number on each control is its corresponding TabIndex property. To set (or reset) these values, simply click on each control in the sequence you want the Tab ordering to occur in. If you click on a control with a False TabStop property, the index value will be ignored in the Tab sequence. Reset the sequence and run the project again. Notice how easily the Tab sequence is modified. To turn off the tab order display, return to the V TabIndex iew menu and choose TabOrder again (make sure the form is active while doing this or that menu item does not appear in the View menu).
Example 2-2
Savings Account – Setting Tabs
1. We will modify our savings account example so it has orderly Tab sequencing. We want the focus to start in the text box requesting Monthly Deposit. Next in sequence will be the text boxes for Interest and Number of Months. We will delete the Tab stop for the Final Deposit box, since we can’t type a number there. Next the focus should move to the Calculate button (when this button has focus, if you press
2. Open Example 2-1. Add these two property changes:
txtFinal text box control:
TabStop False
btnExit button control:
TabStop False
3. Select the form and view the Tab Order. Set the values as shown:
4. Now run the project and notice the nicer orderly flow as the Tab key is pressed. Save the project (Example 2-2 folder in the LearnVBN\VBN Code\Class 2 folder).
Improving a Visual Basic .NET Application
• In the previous section, we noted a weakness in the savings application (unpredictable tab ordering) and fixed the problem, improving the performance of our application. This is something you, as a programmer, will do a lot of. You will build an application and while running it and testing it, will uncover weaknesses that need to be eliminated. These weaknesses could be actual errors in the application or just things that, if eliminated, make your application easier to use.
• You will find, as you progress as a programmer, that you will spend much of your time improving your applications. You will always find ways to add features to an application and to make it more appealing to your user base. You should never be satisfied with your first solution to a problem. There will always be room for improvement. And Visual Basic .NET provides a perfect platform for adding improvements to an application. You can easily add features and test them to see if the desired performance enhancements are attained.
• If you run the savings application a few more times, you can identify further weaknesses:
For example, what happens if you input a zero interest? The program will stop with an error message because the formula that computes the final value will not work with zero interest.
Notice you can type any characters you want in the text boxes when you should just be limited to numbers and a single decimal point – any other characters will cause the program to work incorrectly.
As a convenience, it would be nice if you hit the
• We can (and will) address each of these points as we improve the savings application. But, to do so, requires learning more BASIC coding. We’ll address the zero interest problem first. To solve this problem, we need to be able to make a decision. If the interest is zero, we’ll do one computation. If it’s not zero, we’ll user another. The mechanism for making decisions with Visual Basic .NET is the If statement.
Visual Basic .NET Decisions - If Statements
• The concept of an If statement for making a decision is very simple. We check to see if a particular condition is True. If so, we take a certain action. If not, we do something else. If statements are also called branching statements. Branching statements are used to cause certain actions within a program if a certain condition is met.
• The simplest branching statement is the single line If/Then statement:
If Condition Then [Do This]
In this statement, if Condition (some expression with a Boolean result) is True, then whatever single statement follow the Then keyword will be executed. If Condition is False, nothing is done and program execution continues following this line of code. Example:
If (Balance – Check) < 0 Then Trouble = True
Here, if and only if Balance - Check is less than zero, the Trouble variable is set to True.
Single line If/Then statements are not considered to be ‘structured programming.’ They are sloppy programming practice. But, having said this, you will see that this author uses them (a bad habit I’m trying to phase out).
• The structured approach to decisions is the If/Then/End If blocks which allow multiple statements to be processed for a decision:
If Condition Then
[process this code]
End If
Here, if Condition is True, the code bounded by the If/End If is executed. If Condition is False, nothing happens and code execution continues after the End If statement.
Example:
If Balance - Check < 0 Then
Trouble = True
lblBalance.ForeColor = Color.Red
End If
In this case, if Balance - Check is less than zero, two lines of information are processed: Trouble is set to True and the balance is displayed in red. Notice the indentation of the code between the If and End If lines. The Visual Basic .NET Intellisense feature will automatically do this indentation. It makes understanding (and debugging) your code much easier. You can adjust the amount of indentation using the Options choice under the Tools menu. You will also notice that the Intellisense feature of the IDE will add an End If statement for you as soon as you type the If/Then line.
• What if you want to do one thing if a condition is True and another if it is False? Use an If/Then/Else/End If block:
If Condition Then
[process this code]
Else
[process this code]
End If
In this block, if Condition is True, the code between the If and Else lines is executed. If Condition is False, the code between the Else and End If statements is processed.
Example:
If Balance - Check < 0 Then
Trouble = True
lblBalance.ForeColor = Color.Red
Else
Trouble = False
lblBalance.ForeColor = Color.Black
End If
Here, the same two lines are executed if you are overdrawn (Balance - Check < 0), but if you are not overdrawn (Else), the Trouble flag is turned off and your balance is in the black.
• Finally, we can test multiple conditions by adding the ElseIf statement:
If Condition1 Then
[process this code]
ElseIf Condition2 Then
[process this code]
ElseIf Condition3 Then
[process this code]
Else
[process this code]
End If
In this block, if Condition1 is True, the code between the If and first ElseIf line is executed. If Condition1 is False, Condition2 is checked. If Condition2 is True, the indicated code is executed. If Condition2 is not true, Condition3 is checked. Each subsequent condition in the structure is checked until a True condition is found, a Else statement is reached or the End If is reached.
Example:
If Balance - Check < 0 Then
Trouble = True
lblBalance.ForeColor = Color.Red
ElseIf Balance – Check = 0 Then
Trouble = False
lblBalance.ForeColor = Color.Yellow
Else
Trouble = False
lblBalance.ForeColor = Color.Black
End If
Now, one more condition is added. If your Balance equals the Check amount (ElseIf Balance - Check = 0), you’re still not in trouble and the balance is displayed in yellow.
• In using branching statements, make sure you consider all viable possibilities in the If/Else/End If structure. Also, be aware that each If and ElseIf in a block is tested sequentially. The first time an If test is met, the code associated with that condition is executed and the If block is exited. If a later condition is also True, it will never be considered.
Select Case - Another Way to Branch
* In addition to If/Then/Else type statements, the Select Case format can be used when there are multiple selection possibilities. Select Case is used to make decisions based on the value of a single variable. The structure is:
Select Case Variable
Case [variable has this value]
[process this code]
Case [variable has this value]
[process this code]
Case [variable has this value]
[process this code]
Case Else
[process this code]
End Select
The way this works is that the value of Variable is examined. Each Case statement is then sequentially examined until the value matches one of the specified cases. Once found, the corresponding code is executed. If no case match is found, the code in the Case Else segment (if there) is executed.
• As an example, say we've written this code using the If statement:
If Age = 5 Then
Category = "Five Year Old"
ElseIf Age >= 13 and Age <= 19 Then
Category = "Teenager"
ElseIf (Age >= 20 and Age <= 35) Or Age = 50 Or (Age >= 60 and Age <= 65) Then
Category = "Special Adult"
ElseIf Age > 65 Then
Category = "Senior Citizen"
Else
Category = "Everyone Else"
End If
This will work, but it is ugly code and difficult to maintain.
The corresponding code with Select Case is much ‘cleaner’:
Select Case Age
Case 5
Category = "Five Year Old"
Case 13 To 19
Category = "Teenager"
Case 20 To 35, 50, 60 To 65
Category = "Special Adult"
Case Is > 65
Category = "Senior Citizen"
Case Else
Category = "Everyone Else"
End Select
Notice there are several formats for the Case statement. Consult on-line help for discussions of these formats.
• Like the If structure, the Select Case searches down each Case until it finds the first ‘match.’ Then, that code is executed. Only one Case for each Select Case can be executed. There is no possibility of a ‘global’ Select Case that would execute multiple Case statements. Make sure each Select Case you use accurately reflects the decision you are trying to implement.
Key Trapping
• Recall in the savings example, there is nothing to prevent the user from typing in meaningless characters (for example, letters) into the text boxes expecting numerical data. We want to keep this from happening. Whenever getting input from a user using a text box control, we want to limit the available keys they can press. This process of intercepting and eliminating unacceptable keystrokes is called key trapping.
• Key trapping is done in the KeyPress event procedure of a text box control. Such a procedure has the form (for a text box named txtText):
Private Sub txtText_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtText.KeyPress
.
.
.
End Sub
What happens in this procedure is that every time a key is pressed in the corresponding text box, the KeyPressEventArgs class passes the key that has been pressed into the procedure via the e.KeyChar property. We can thus examine this key. If it is an acceptable key, we set the e.Handled property to False. This tells Visual Basic .NET that this procedure has not been handled and the KeyPress should be allowed. If an unacceptable key is detected, we set e.Handled to True. This ‘tricks’ Visual Basic .NET into thinking the KeyPress event has already been handled and the pressed key is ignored.
• We need someone way of distinguishing what keys are pressed. One possibility is to examine the ASCII code for the pressed key and see if it corresponds with the ASCII codes for acceptable keys. Some keys, known as control keys, may not have ASCII values. Visual Basic .NET has predefined these control keys in the ControlChars module. Some values for these keys we will use:
Value Definition
ControlChars.Back Backspace
ControlChars.Cr Carriage return (
ControlChars.NullChar Null character
ControlChars.Quote Double quote
ControlChars.Tab Tab
• As an example, let’s build a key trapping routine for our savings application example. We’ll work with the txtDeposit control, knowing the KeyPress events for the other text box controls will be similar. First, we will determine the ASCII code for the pressed key. The code to do this is:
Dim KeyAscii As Integer
KeyAscii = Asc(e.KeyChar)
• Next, I suggest a Select Case structure that, based on different values of KeyAscii, takes different steps. If KeyAscii represents a number, a decimal point or a backspace key (always include backspace or the user won’t be able to edit the text box properly), we will allow the keypress (e.Handled = False). Otherwise, we will set e.Handled = True to ignore the keypress. The code to do this is:
Select Case KeyAscii
Case Asc("0") To Asc("9"), Asc(“.”), Asc(ControlChars.Back)
e.Handled = False
Case Else
e.Handled = True
End Select
(Note Asc(ControlChars.Back) is not on a separate line in the code window, it is just displayed that way here due to page margins).
• Note, the above code does not eliminate one of the earlier identified problems. That is, there is nothing to keep the user from typing multiple decimal points. To solve this, we let the ‘decimal point’ have its own case:
Case Asc(".")
If InStr(txtInterest.Text, ".") = 0 Then
e.Handled = False
Else
e.Handled = True
End If
In this new case, if there is no decimal point (determined using the Instr function), the keypress is allowed. If a decimal point is already there, the keypress is disallowed.
Control Focus
• Earlier we saw that, in a running application, only one control can have user interaction at any one time. We say that control has focus. A text box with the cursor has focus – if the user begins typing, the typed characters go in that text box. If a button control has focus, that button can be ‘clicked’ by simply pressing the
• We also saw that the
• To programmatically assign focus to a control, apply the Focus() method to the control using this dot-notation:
ControlName.Focus()
• The Case to do this in our txtDeposit text box key trapping routine would be:
Case Asc(ControlChars.Cr)
'enter key - move to next box
txtInterest.Focus()
e.Handled = False
Here, if the
Example 2-3
Savings Account - Key Trapping
1. We modify the Savings Account example to handle a zero interest value and to implement key trapping in the three text box KeyPress events. The key trapping implemented will only allow numbers, a single decimal point and the backspace. If
2. Modify the btnCalculate Click event code to accommodate a zero interest input. Note if Interest is zero, the final value is just the deposited amount times the number of months. The modified routine is (new code italicized):
Private Sub btncalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
Dim IntRate As Double
'read values from text boxes
Deposit = Val(txtDeposit.Text)
Interest = Val(txtInterest.Text)
IntRate = Interest / 1200
Months = Val(txtMonths.Text)
'compute final value and put in text box
If Interest = 0 Then
'zero interest case
Final = Deposit * Months
Else
Final = Deposit * ((1 + IntRate) ^ Months - 1) / IntRate
End If
txtFinal.Text = Format(Final, "0.00")
End Sub
(In some of the statements above, the word processor may cause a line break where there really shouldn’t be one. In all code in these notes, always look for such things.)
3. Add the following code to txtDeposit text box KeyPress event:
Private Sub txtDeposit_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtDeposit.KeyPress
Dim KeyAscii As Integer
KeyAscii = Asc(e.KeyChar)
'only allow numbers, a single decimal point, backspace or enter
Select Case KeyAscii
Case Asc("0") To Asc("9"), Asc(ControlChars.Back)
'acceptable keystrokes
e.Handled = False
Case Asc(ControlChars.Cr)
'enter key - move to next box
txtInterest.Focus()
e.Handled = False
Case Asc(".")
'check for existence of decimal point
If InStr(txtDeposit.Text, ".") = 0 Then
e.Handled = False
Else
e.Handled = True
End If
Case Else
e.Handled = True
End Select
End Sub
This code limits keystrokes to numbers, a single decimal point, the backspace key and moves focus to the txtInterest control if
4. Add the following code to txtInterest text box KeyPress event (nearly same as above – use cut and paste – differences involve control names and where focus moves after
Private Sub txtInterest_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtInterest.KeyPress
Dim KeyAscii As Integer
KeyAscii = Asc(e.KeyChar)
'only allow numbers, a single decimal point, backspace or enter
Select Case KeyAscii
Case Asc("0") To Asc("9"), Asc(ControlChars.Back)
'acceptable keystrokes
e.Handled = False
Case Asc(ControlChars.Cr)
'enter key - move to next box
txtMonths.Focus()
e.Handled = False
Case Asc(".")
'check for existence of decimal point
If InStr(txtInterest.Text, ".") = 0 Then
e.Handled = False
Else
e.Handled = True
End If
Case Else
e.Handled = True
End Select
End Sub
This code limits keystrokes to numbers, a single decimal point, the backspace key and moves focus to the txtMonth control if
5. Add the following code to txtMonths text box KeyPress event (nearly same as above – use cut and paste – differences involve control names, no decimal points allowed and where focus moves after
Private Sub txtMonths_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtMonths.KeyPress
Dim KeyAscii As Integer
KeyAscii = Asc(e.KeyChar)
'only allow numbers, backspace or enter
Select Case KeyAscii
Case Asc("0") To Asc("9"), Asc(ControlChars.Back)
'acceptable keystrokes
e.Handled = False
Case Asc(ControlChars.Cr)
'enter key - move to calculate button
btnCalculate.Focus()
e.Handled = False
Case Else
e.Handled = True
End Select
End Sub
This code limits keystrokes to numbers, the backspace key and moves focus to the btnCalculate control if
6. Rerun the application and test the key trapping performance. Save the application (Example 2-3 folder in the LearnVBN\VBN Code\Class 2 folder).
Visual Basic .NET Looping
• Many applications require repetition of certain code segments. For example, you may want to roll a die (simulated die of course) until it shows a six. Or, you might generate financial results until a certain sum of returns has been achieved. This idea of repeating code is called iteration or looping.
• In Visual Basic .NET looping is done with the Do/Loop format.:
Do
[process this code]
Loop
In this structure, all code between the Do (starts the loop) and the Loop statement is repeated until the loop is exited. This brings up a very important point – if you use a loop, make sure you can get out of the loop!! It is especially important in the event-driven environment of Visual Basic .NET. As long as your code is operating in some loop, no events can be processed. The Exit Do statement will get you out of a loop and transfer program control to the statement following the Loop statement. Of course, you need logic in a loop to decide when an Exit Do is appropriate.
• Another way to exit a loop is to test conditions prior to or following execution of the code in loop. This is achieved using Until and While statements. These statements can be used with the Do statement or the Loop statement. Let’s look examples of all possible combinations.
• A Do While/Loop structure:
Do While Condition
[process this code]
Loop
In this structure, the loop is repeated ‘as long as’ the Boolean expression Condition is True. Note a Do While/Loop structure will not execute even once if the While condition is False the first time through. If we do enter the loop, it is assumed at some point Condition will become False to allow exiting.
Example:
Counter = 1
Do While Counter <= 1000
Counter += 1
Loop
This loop repeats as long as (While) the variable Counter is less than or equal to 1000.
• A Do Until/Loop structure:
Do Until Condition
[process this code]
Loop
In this structure, the loop is repeated ‘until’ the Boolean expression Condition is True. Note a Do Until/Loop structure will not be entered if the Until condition is already True on the first encounter. However, once the loop is entered, it is assumed at some point Condition will become True to allow exiting.
Example:
Counter = 0
Do Until Counter = 10
‘Roll a simulated die
If CInt(Rnd() * 6 – 0.5) + 1 = 6 Then
Counter += 1
End If
Loop
This loop repeats Until the Counter variable equals 10. The Counter variable is incremented each time a simulated die rolls a 6.
• A Do/Loop While structure:
Do
[process this code]
Loop While Condition
This loop repeats ‘as long as’ the Boolean expression Condition is True. The loop is always executed at least once. Somewhere in the loop, Condition must be changed to False to allow exiting.
Example:
Sum = 0
Do
Sum += 3
Loop While Sum <= 50
In this example, we increment a sum by 3 until that sum exceeds 50 (or While the sum is less than or equal to 50).
• A Do/Loop Until structure:
Do
[process this code]
Loop Until Condition
This loop repeats until the Boolean expression Condition is True. The loop is always executed at least once. Somewhere in the loop, Condition must be become True for proper exiting.
Example:
Sum = 0
Counter = 0
Do
‘Roll a simulated die
Sum += CInt(Rnd() * 6 – 0.5) + 1
Counter += 1
Loop Until Sum > 30
This loop rolls a simulated die Until the Sum of the rolls exceeds 30. It also keeps track of the number of rolls (Counter) needed to achieve this sum.
• Again, make sure you can always get out of a loop! Infinite loops are never nice. If you get into one, try Ctrl+Break. That sometimes works - other times the only way out is rebooting your machine!
Visual Basic .NET Counting
• With Do/Loop structures, we usually didn’t know, ahead of time, how many times we execute a loop or iterate. If you know how many times you need to iterate on some code, you want to use Visual Basic .NET counting. Counting is useful for adding items to a list or perhaps summing a known number of values to find an average.
• Visual Basic .NET counting is accomplished using the For/Next loop:
For Variable = Start To End [Step Increment]
[process this code]
Next Variable
In this loop, Variable is the counter (doesn’t necessarily need to be a whole number). The first time through the loop, Variable is initialized at Start. Each time the corresponding Next statement is reached, Variable is incremented by an amount Increment. If the Step value is omitted, a default increment value of one is used. Negative increments are also possible. The counting repeats until Variable equals or exceeds the final value End.
Example:
For Degrees = 0 To 360 Step 10
‘convert to radians
R =Degrees * Math.Pi / 180
A = Math.Sin(R)
B = Math.Cos(R)
C = Math.Tan(R)
Next Degrees
In this example, we compute trigonometric functions for angles from 0 to 360 degrees in increments (steps) of 10 degrees. . Notice that the Intellisense feature of the IDE will add a Next statement for you as soon as you type the For line. I suggest always appending the variable name to the Next statement as soon as it appears. This is not necessary (the variable name in the Next statement is optional), but good programming practice to make your code clearer.
Another Example:
For Countdown = 10 to 0 Step –1
lblTimeRemaining.Text = Format(Countdown, “0”) + “Seconds”
Next Countdown
NASA called and asked us to format a label control to countdown from 10 to 0. The loop above accomplishes the task.
And, Another Example:
Dim MyValues(100) as Double
Sum = 0
For I = 1 to 100
Sum += MyValues(I)
Next I
Average = Sum / 100
This code finds the average value of 100 numbers stored in the array MyValues. It first sums each of the values in a For/Next loop. That sum is then divided by the number of terms (100) to yield the average.
• You may exit a For/Next loop early using an Exit For statement. This will transfer program control to the statement following the Next statement.
Example 2-4
Savings Account - Decisions
As built, our savings account application is useful, but we can add more capability. For example, what if we know how much money we need in a number of months and the interest our deposits can earn. It would be nice if the program could calculate the needed month deposit. Or, what if we want to know how long it will take us to reach a goal, knowing how much we can deposit each month and the related interest. Here, we modify the Savings Account project to allow entering any three values and computing the fourth.
1. First, add a third button that will clear all of the text boxes. Assign the following properties:
Button3:
Name btnClear
Text Clear &Boxes
The form should look something like this when you’re done:
2. Code the btnClear button Click event:
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
'blank out text boxes
txtDeposit.Text = ""
txtInterest.Text = ""
txtMonths.Text = ""
txtFinal.Text = ""
txtDeposit.Focus()
End Sub
This code simply blanks out the four text boxes when the Clear button is clicked. It then redirects focus to the txtDeposit text box.
3. We now need the capability to enter information into the Final Value text box. Related to this:
Change the ReadOnly property of the txtFinal text box to False
Change TabStop to True
Reset the Tab Order so, the txtFinal text box is included
Modify the txtMonths KeyPress event so focus is transferred to the txtFinal text box when
4. Code the KeyPress event for the txtFinal object:
Private Sub txtFinal_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtFinal.KeyPress
Dim KeyAscii As Integer
KeyAscii = Asc(e.KeyChar)
'only allow numbers, a single decimal point, backspace or enter
Select Case KeyAscii
Case Asc("0") To Asc("9"), Asc(ControlChars.Back)
'acceptable keystrokes
e.Handled = False
Case Asc(ControlChars.Cr)
'enter key - move to calculate button
btnCalculate.Focus()
e.Handled = False
Case Asc(".")
'check for existance of decimal point
If InStr(txtFinal.Text, ".") = 0 Then
e.Handled = False
Else
e.Handled = True
End If
Case Else
e.Handled = True
End Select
End Sub
Recall, we need this code because we can now enter information into the Final Value text box. It is very similar to the other KeyPress events. This code limits keystrokes to numbers, a single decimal point, the backspace key and moves focus to the btnCalculate control if
4. The modified code for the Click event of the btnCalculate button is:
Private Sub btncalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
Dim IntRate As Double
Dim FinalCompute As Double, IntChange As Double, IntDirection As Integer
'Read the four text boxes
Deposit = Val(txtDeposit.Text)
Interest = Val(txtInterest.Text)
IntRate = Interest / 1200
Months = Val(txtMonths.Text)
Final = Val(txtFinal.Text)
'Determine which box is blank
'Compute that missing value and put in text box
If Trim(txtDeposit.Text) = "" Then
'Deposit missing
If Interest = 0 Then
Deposit = Final / Months
Else
Deposit = Final / (((1 + IntRate) ^ Months - 1) / IntRate)
End If
txtDeposit.Text = Format(Deposit, "0.00")
ElseIf Trim(txtInterest.Text) = "" Then
'Interest missing - requires iterative solution
'IntChange is how much we change interest each step
'IntDirection is direction (+ or -) we change interest
Interest = 0
IntChange = 1
IntDirection = 1
Do
Interest += IntDirection * IntChange
IntRate = Interest / 1200
FinalCompute = Deposit * ((1 + IntRate) ^ Months - 1) / IntRate
If IntDirection = 1 Then
If FinalCompute > Final Then
IntDirection = -1
IntChange /= 10
End If
Else
If FinalCompute < Final Then
IntDirection = 1
IntChange /= 10
End If
End If
Loop Until Math.Abs(FinalCompute - Final) < 0.005
txtInterest.Text = Format(Interest, "0.00")
ElseIf Trim(txtMonths.Text) = "" Then
'Months missing
If Interest = 0 Then
Months = Final / Deposit
Else
Months = Math.Log(Final * IntRate / Deposit + 1) / Math.Log(1 + IntRate)
End If
txtMonths.Text = Format(Months, "0.00")
ElseIf Trim(txtFinal.Text) = "" Then
'Final value missing
If Interest = 0 Then
Final = Deposit * Months
Else
Final = Deposit * ((1 + IntRate) ^ Months - 1) / IntRate
End If
txtFinal.Text = Format(Final, "0.00")
End If
End Sub
In this code. we first read the text information from all four text boxes and based on which one is blank (the Trim function strips off leading and trailing blanks), compute the missing information and display it in the corresponding text box.
Let’s look at the math involved in solving for missing information. Recall the equation given in Example 2-1:
F = D [ (1 + I)M - 1] / I
where F is the final amount, D the deposit, I the monthly interest, and M the number of months. This is the equation we’ve been using to solve for Final and we still use it here if the Final box is empty, unless the interest is zero. For zero interest, we use:
F = DM, if interest is zero
See if you can find these equations in the code.
If the Deposit box is empty, we can easily solve the equation for D (the needed quantity):
D = F/ {[ (1 + I)M - 1] / I}
If the interest is zero, this equation will not work. In that case, we use:
D = F/M, if interest is zero
You should be able to find these equations in the code above.
Solving for missing Months information requires knowledge of logarithms. I’ll just give you the equation:
M = log (FI / D + 1) / log (1 + I)
In this Visual Basic .NET, the logarithm (log) function is one of the math functions, Math.Log. Like the other cases, we need a separate equation for zero interest:
M = F/D, if interest is zero
.Again, see if you can find these equations in the code
If the Interest value is missing, we need to resort to a widely used method for solving equations – we’ll guess! But, we’ll use a structured guessing method. Here’s what we’ll do. We’ll start with a zero interest and increase it by one percent until the computed final amount is larger than the displayed final amount. At that point, we know the interest is too high so, we decrease the interest by a smaller amount (0.1 percent) until the computed final amount is less than the displayed final amount, meaning the interest is too low. We start increasing the interest again (this time by 0.01 percent). We’ll repeat this process until the computed final amount is with 1 cent of the displayed amount. This kind of process is called iteration and is used often in computer programs. You should be able to see each step in the code – a good example of a Do loop.
Don’t be intimidated by the code in this example. I’ll admit there’s a lot of it! Upon study, though, you should see that it is just a straightforward list of instructions for the computer to follow based on input from the user.
5. Test and save your application (Example 2-3 folder in the LearnVBN\VBN Code\Class 2 folder). Now, relax!.
Class Review
• After completing this class, you should understand:
Visual Basic .NET statements and reasons for strict type checking
The BASIC assignment operator, mathematics operators, comparison and logic operators and concatenation operators
The wide variety of built-in Visual Basic .NET functions, especially string function, the random number generator, and mathematics functions
How to set tabs and assign tab order to controls
The If/Then/Else If/Else/End If structure used for branching and decisions
The Select Case/End Select decision structure
How key trapping can be used to eliminate unwanted keystrokes from text box controls
The concept of control focus and how to assign focus in code
How the Do/Loop structure is used in conjunction with the While and Until statements
How the For/Next loop is used for counting
Practice Problems 2
Problem 2-1. Random Number Problem. Build an application where each time a button is clicked, a random number from 1 to 100 is displayed.
Problem 2-2. Price Problem. The neighborhood children built a lemonade stand. The hotter it is, the more they can charge. Build an application that produces the selling price, based on temperature:
Temperature Price
<50 Don’t bother
50 – 60 20 Cents
61 – 70 25 Cents
71 – 80 30 Cents
81 – 85 40 Cents
86 – 90 50 Cents
91 – 95 55 Cents
96 – 100 65 Cents
>100 75 Cents
Problem 2-3. Odd Integers Problem. Build an application that adds consecutive odd integers (starting with one) until the sum exceeds a target value. Display the sum and how many integers were added.
Problem 2-4. Pennies Problem. Here’s an old problem. Today, I’ll give you a penny. Tomorrow, I’ll give you two pennies. I’ll keep doubling the amount I’ll give you for 30 days. How much will you have at the end of the month (better use a Long integer type to keep track)?
Problem 2-5. Code Problem. Build an application with a text box and two buttons. Type a word or words in the text box. Click one of the buttons. Subtract one from the ASCII code of each character in the typed word(s), then redisplay it. This is a simple encoding technique. When you click the other button, reverse the process to decode the word.
Exercise 2-1
Computing a Mean and Standard Deviation
Develop an application that allows the user to input a sequence of numbers. When done inputting the numbers, the program should compute the mean of that sequence and the standard deviation. If N numbers are input, with the ith number represented by xi, the formula for the mean ( ) is:
= ( )/ N
and to compute the standard deviation (s), take the square root of this equation:
s2 = [N - ( )2]/[N(N - 1)]
The Greek sigmas in the above equations simply indicate that you add up all the corresponding elements next to the sigma. If the standard deviation equation scares you, just write code to find the average value – you should have no trouble with that one.
Exercise 2-2
Flash Card Addition Problems
Write an application that generates random addition problems. Provide some kind of feedback and scoring system as the problems are answered.
bersambung di volume 3# fey888.blog.com
Tidak ada komentar:
Posting Komentar