csi 1306 programming in visual basic part 2. part 2 1. strings 2. translating conditional branch...
TRANSCRIPT
CSI 1306
PROGRAMMING IN VISUAL BASIC
PART 2
Part 2
1. Strings2. Translating Conditional Branch Instructions3. Translation Set 24. Debugging Programs5. Additional Material
1. Strings
Strings
A string is any combination of letters, numbers or symbols surrounded by double quotes " "
Two strings are considered equal if and only if each and every character is identical– “Bob” is equal to “Bob”
– but not equal to “BOB”, “bob” or “Robert”
Strings can be manipulated in assignment statements
Strings
The following operators can be used on Strings– Len, Lcase, Ucase, Right, Left, InStr, Ltrim, Rtrim,
Trim, Val, Str, &For example
– Str(Number)• converts a numeric type into a string• Str(456) “ 456”
– Concatenation (joining two strings) • done with & (ampersand)• “Hello” & “World” “HelloWorld” (no space)
These operators are defined in the Additional Material at the end of the lecture slides
2. Translating Conditional Branch Instructions
Review of Comparisons
The arithmetic logic unit in the central processing unit of a computer is capable of comparing 2 numbers
The result of the comparison is either a True or a False
We use the result to determine which block of code to execute (conditional branch) or whether to exit a loop
Review of Comparisons
Comparisons can be made on both numeric and string data types
The comparison operators in Visual Basic are– < Less Than
– > Greater Than
– = Equal
– <= Less Than or Equal
– >= Greater Than or Equal
– <> Not Equal
Conditional Branch Instructions
IF statementIF (condition) THEN
instruction blockEND IF
Condition is a variable or expression which must evaluate to either True or False
If the condition is True, then execute the instruction block
If the condition is False, do not execute the instruction block
Conditional Branch Instructions
Write a program that will order the values of X and Y so that the smaller value will be in X and the larger value will be in Y.
Use the concept of a SWAP
Conditional Branch Instructions
OPTION EXPLICIT'Written by T. James
Sub swap ()Dim X as Single 'A ValueDim Y as Single 'A ValueDim Temp as Single 'Hold for a swap
If (X > Y) Thentemp = X X = YY = temp
End IfEnd Sub
Conditional Branch Instructions
Are the results identical when these two code fragments are executed?
IF (big > small) THEN big = smallEND IFsmall = 0
IF (big > small) THEN big = small small = 0END IF
In the left code fragment, small becomes zero only when big is greater than small.
In the right code fragment, small always becomes zero
Conditional Branch Instructions IF statement with an ELSE clause
What if we need multiple related tests?
IF (x > 5) THEN do instruction block 1END IFIF(x <= 5) THEN do instruction block 2END IF
IF (x > 5) THEN do instruction block 1ELSE do instruction block 2END IF
Conditional Branch Instructions
IF statement with ELSEIF clausesIF (condition 1) THEN
Do instruction block 1
ELSEIF (condition 2) THENDo instruction block 2
ELSEIF (condition 3) THEN Do instruction block 3
ELSEDo instruction block 4
END IFCan include any number of ELSEIF clausesThe ELSE clause may be omitted
Conditional Branch Instructions
ALGORITHMIf student is a Male
Let Mark = 60%Midterm + 40%Final
OtherwiseLet Mark = 40%Midterm + 60%Final
If Mark > 80Let Grade = A
Else If Mark > 60Let Grade = C
ElseLet Grade = F
VISUAL BASICIf (Gender = “M”) Then
NG = 0.6*MT + 0.4*FEElse
NG = 0.4*MT + 0.6*FEEnd If
If (Mark > 80) ThenGrade = “A”
ElseIf (Mark > 60) ThenGrade = “C”
ElseGrade = “F”
End If
Conditional Branch Instructions
Write an IF statement to assign the correct grade to an exam mark
– A if exam mark is 90 or above
– B if exam mark is 80 to 89
– C if exam mark is 70 to 79
– D if exam mark is 60 to 69
– F if exam mark is below 60
Conditional Branch InstructionsOPTION EXPLICIT'Written by T. James
Sub Grades ()Dim Mark as Single 'Final MarkDim Grade as String*1 'Letter Grade
If (Mark >= 90) ThenGrade = "A"
ElseIf (Mark >= 80) ThenGrade = "B"
ElseIf (Mark >= 70) ThenGrade = "C"
ElseIf (Mark >= 60) ThenGrade = "D"
ElseGrade = "F"
End IfEnd Sub
Conditional Branch Instructions
What is wrong with this code fragment?If (Mark >= 60) Then
Grade = “D”ElseIf (Mark >= 70) Then
Grade = “C”ElseIf (Mark >= 80) Then
Grade = “B”ElseIf (Mark >= 90) Then
Grade = “A”Else
Grade = “F”End If
The only two grades ever assigned are D and F
Review of Comparisons
Note that in a comparison, if Pass is a Boolean variable
If (Pass = True) Then
is the same as
If Pass Then
and
If (Pass = False) Then
is the same as
If (not Pass) Then
Conditional Branch InstructionsFor choosing among integer values of a variable,
the SELECT CASE statement may be usedSELECT CASE variable
CASE value1Do instruction block 1
CASE value2Do instruction block 2
CASE ELSEDo instruction block 3
END SELECTCan include any number of CASE clausesThe CASE ELSE clause may be omitted
Conditional Branch Instructions
IF (X=1) THENY = 5
ELSEIF (X=3) THENY = 4
ELSEIF (X=6) THENY = 3
ELSEY = 2
END IF
SELECT CASE XCASE 1
Y = 5CASE 3
Y = 4CASE 6
Y = 3CASE ELSE
Y = 2
END SELECT
The two code fragments accomplish the same result. The one on the right is easier to read.
Conditional Branch Instructions
For choosing among multiple ranges of values of a variable, the CASE IS clause can be usedSELECT CASE variable
CASE IS range1Do instruction block 1
CASE IS range2Do instruction block 2
CASE ELSEDo instruction block 3
END SELECT
Conditional Branch Instructions
IF (X<10) THENY = 5
ELSEIF (X<20) THENY = 4
ELSEIF (X<30) THENY = 3
ELSEY = 2
END IF
SELECT CASE XCASE IS <10
Y = 5CASE IS <20
Y = 4CASE IS <30
Y = 3CASE ELSE
Y = 2
END SELECT
The two code fragments accomplish the same result
Translating Conditional Branch InstructionsLook at the METHODEach conditional branch instruction should be
translated to an IF (or, if appropriate, a SELECT CASE) statement
Make your code easy to read. Use a uniform indentation scheme
3. Translation Set 2
Translate 4
Translate Algorithm 2.4
Name: FAREGiven: Age
Change: NoneResult: PriceIntermediates: NoneDefinition: Price := FARE(Age)
Get AgeIf (Age < 16)
Let Price = $7Else If (Age > 65)
Let Price = $5Else
Let Price = $10Give Price
Translate 4
Translate Algorithm 2.4
Name: FAREGiven: Age
Change: NoneResult: PriceIntermediates: NoneDefinition: Price := FARE(Age)
Get AgeIf (Age < 16)
Let Price = $7Else If (Age > 65)
Let Price = $5Else
Let Price = $10Give Price
Option Explicit
'Written By T. James
Sub Fare()
Dim Age as Integer
Dim Price as Single
Age = InputBox("Age?")
MsgBox("Fare is " & Price)
End Sub
Translate 4
Translate Algorithm 2.4
Name: FAREGiven: Age
Change: NoneResult: PriceIntermediates: NoneDefinition: Price := FARE(Age)
Get AgeIf (Age < 16)
Let Price = $7Else If (Age > 65)
Let Price = $5Else
Let Price = $10Give Price
Option Explicit
'Written By T. James
Sub Fare()
Dim Age as Integer
Dim Price as Single
Age = InputBox("Age?")
MsgBox("Fare is " & Price)
End Sub
If (Age < 16) Then
Price = 7.00
ElseIf (Age > 65) Then
Price = 5.00
Else
Price = 10.00
End If
Algorithm 2.4
Translate 5
Translate Algorithm 2.2Name: BIG3Givens: N1, N2, N3Result: LargestIntermediate: NoneDefinition: Largest := BIG3(N1,N2,N3)
Get N1Get N2Get N3
If (N1 > N2)Let Largest = N1
Else Let Largest = N2
If (N3 > Largest)Let Largest = N3
Give Largest
Translate 5Translate Algorithm 2.2Name: BIG3Givens: N1, N2, N3Result: LargestIntermediate: NoneDefinition: Largest := BIG3(N1,N2,N3)
Get N1Get N2Get N3
If (N1 > N2)Let Largest = N1
Else Let Largest = N2
If (N3 > Largest)Let Largest = N3
Give Largest
Option Explicit
'Written By T. James
Sub Big3 ()
Dim N1 as Integer
Dim N2 as Integer
Dim N3 as Integer
Dim Largest as Integer
N1 = InputBox("N1?")
N2 = InputBox("N2?")
N3 = InputBox("N3?")
Translate 5 Translate Algorithm 2.2Name: BIG3Givens: N1, N2, N3Result: LargestIntermediate: NoneDefinition: Largest := BIG3(N1,N2,N3)
Get N1Get N2Get N3
If (N1 > N2)Let Largest = N1
Else Let Largest = N2
If (N3 > Largest)Let Largest = N3
Give Largest
Option Explicit'Written By T. JamesSub Big3 () Dim N1 as Integer Dim N2 as Integer Dim N3 as Integer Dim Largest as Integer N1 = InputBox("N1?") N2 = InputBox("N2?") N3 = InputBox("N3?")
If (N1>N2) Then Largest = N1 Else Largest = N2 End If
If (N3 > Largest) Then Largest = N3 End If
MsgBox("L = " & Largest)End Sub
Algorithm 2.2
Translate 6 Translate Algorithm 2.5Name: MEDICALGiven: Expense
Change: NoneResult: RefundIntermediates: LL, UL (Constants)Definition: Refund := MEDICAL(Expense)
Set LL = 100Set UL = 2,000Get Expense
If (Expense <= LL)Let Refund = 0
Else If (Expense <= UL)Let Refund = 90% (Expense-LL)
ElseLet Refund = 90% (UL-LL) +
100% (Expense - UL)Give Refund
Translate 6 Translate Algorithm 2.5Name: MEDICALGiven: Expense
Change: NoneResult: RefundIntermediates: LL, UL (Constants)Definition: Refund := MEDICAL(Expense)
Set LL = 100Set UL = 2,000Get Expense
If (Expense <= LL)Let Refund = 0
Else If (Expense <= UL)Let Refund = 90% (Expense-LL)
ElseLet Refund = 90% (UL-LL) +
100% (Expense - UL)Give Refund
Option Explicit
'Written By T. James
Sub Medical()
Dim Expense as Single
Dim Refund as Single
Const LL = 100
Const UL = 2000
Expense=InputBox("E?")
Translate 6 Translate Algorithm 2.5Name: MEDICALGiven: Expense
Change: NoneResult: RefundIntermediates: LL, UL (Constants)Definition: Refund := MEDICAL(Expense)
Set LL = 100Set UL = 2,000Get Expense
If (Expense <= LL)Let Refund = 0
Else If (Expense <= UL)Let Refund = 90% (Expense-LL)
ElseLet Refund = 90% (UL-LL) +
100% (Expense - UL)Give Refund
Option Explicit'Written By T. JamesSub Medical() Dim Expense as Single Dim Refund as Single Const LL = 100 Const UL = 2000
Expense=InputBox("E?")
If (Expense <= LL) Then
Refund = 0
ElseIf (Expense<=UL) Then
Refund = .90*(Expense-LL)
Else Refund = 0.9*(UL-LL)+Expense-2000
End If
MsgBox("Refund " & Refund)
End Sub
Algorithm 2.5
4. Debugging Programs
Debugging Programs
Step 1– Check the translation from your algorithm to Visual
Basic
Step 2– Recheck the logic in your algorithm
Step 3– Use the debug facilities of Visual Basic
Debugging Programs
To debug a program is to identify and correct errors in your program– Usually, these are semantic (logic) or runtime errors.
You will already have corrected most syntax errors when entering the code
Add Watch capability– Shows the current value of variables and expressions
as the program executes
Debugging Programs
Step Into your code– Runs the next executable line of code. If the code calls
another program, your view of the code shifts to the called program until it ends
– Step Over also runs the next executable line of code. However, if the code calls another program, the entire called program is run so that your view of the code is never shifted from the calling program
Using the watch and step into debug capabilities is analogous to tracing
Debugging Programs
For programs with many lines of code, where you might not want to step through each line of executable code, you can set breakpoints
Toggle Breakpoint– Creates or removes a breakpoint, a location in the code
where Visual Basic halts executionQuick Watch
– During break mode, lets you check the value of a variable or expression for which you have not defined a watch
4. Additional Material
String Operators
String Operators
Len(String)– returns the number of characters in the String– Len(“Hello World”) 11
Lcase(String)– changes all the characters in String to lower case– Lcase(“Hello World”) “hello world”
Ucase(String)– changes all the characters in String to upper case– Ucase(“Hello World”) “HELLO WORLD”
String Operators
Right (String, N)– returns the last N characters in the String– Right(“Hello World”, 5) “World”
Left (String, N)– returns the first N characters in the String– Left(“Hello World”, 5) “Hello”
InStr (String1, String2)– returns a number, counting from the left, where String2
can be found in String1 – returns 0 if String 2 is not in String1– InStr(“Hello World”, “World”) 7
String Operators
Ltrim (String)– eliminates leading blanks– Ltrim (“ Hello “) “Hello “
Rtrim(String)– eliminates trailing blanks– Rtrim (“ Hello “) “ Hello“
Trim(String)– eliminates both leading and trailing blanks– Trim (“ Hello “) “Hello“
String Operators
Val(String)– converts a string (consisting of numbers) into a numeric
type– Val(“123”) 123
Str(Number)– converts a numeric type into a string– Str(456) “ 456” (a leading space is always reserved
for the sign)Concatenation (joining two strings)
– done with & (ampersand)– “Hello” & “World” “HelloWorld” (no space)
Homework
For each of the following questions:Develop an algorithm
Translate the algorithm into Visual Basic Code
•Write an algorithm to reverse the digits in a three digit number and then add that number to 500. For example, 468 becomes 864. When added to 500, the result is 1364.
•Write an algorithm to get the names and ages of two people. Return the name of the person who is older (in the format “x is older than y”, where x and y are the names of the two people), unless the two people are the same age, in which case, return the message “x is the same age as y”.
An automotive sales representative’s commission is calculated as a percentage of the sale: – 8% of the first $5,000.00 of the sale price– 10% on the remainder of the sale price, if the remainder
is less than or equal to $80,000.00 or– 12.5% on the remainder, if the remainder is more than
$80,000.00Develop the visual basic code that will accept the
sale price of the automobile and calculate and display the sales representative’s commission.