Visual Basic -2

Download Report

Transcript Visual Basic -2

CSI 1306 PROGRAMMING IN VISUAL BASIC PART 2

Part 2

 1. Strings  2. Translating Conditional Branch Instructions  3. Translation Set 2  4. Debugging Programs  5. 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 statement

IF (condition) THEN instruction block END 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 Value Dim Y as Single 'A Value Dim Temp as Single 'Hold for a swap If (X > Y) Then temp = X X = Y Y = temp End If End Sub

Conditional Branch Instructions

 Are the results identical when these two code fragments are executed?

IF (big > small) THEN big = small small = 0 END IF IF (big > small) THEN big = small END IF small = 0 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

IF (x > 5) THEN do instruction block 1 END IF IF(x <= 5) THEN do instruction block 2 END IF IF (x > 5) THEN do instruction block 1 ELSE do instruction block 2 END IF 

What if we need multiple related tests?

Conditional Branch Instructions

IF statement with ELSEIF clauses

IF (condition 1) THEN Do instruction block 1 ELSEIF (condition 2) THEN Do instruction block 2 ELSEIF (condition 3) THEN Do instruction block 3 ELSE Do instruction block 4 END IF  Can include any number of ELSEIF clauses  The ELSE clause may be omitted

Conditional Branch Instructions

 ALGORITHM If student is a Male Let Mark = 60%Midterm + 40%Final Otherwise Let Mark = 40%Midterm + 60%Final If Mark > 80 Let Grade = A Else If Mark > 60 Let Grade = C Else Let Grade = F  VISUAL BASIC If (Gender = “M”) Then NG = 0.6*MT + 0.4*FE Else NG = 0.4*MT + 0.6*FE End If If (Mark > 80) Then Grade = “A” ElseIf (Mark > 60) Then Grade = “C” Else Grade = “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 Instructions

OPTION EXPLICIT 'Written by T. James Sub Grades () Dim Mark as Single 'Final Mark Dim Grade as String*1 'Letter Grade If (Mark >= 90) Then Grade = "A" ElseIf (Mark >= 80) Then Grade = "B" ElseIf (Mark >= 70) Then Grade = "C" ElseIf (Mark >= 60) Then Grade = "D" Else End Sub Grade = "F" End If

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 Instructions

 For choosing among integer values of a variable, the SELECT CASE statement may be used SELECT CASE variable CASE value1 Do instruction block 1 CASE value2 Do instruction block 2 CASE ELSE Do instruction block 3 END SELECT  Can include any number of CASE clauses  The CASE ELSE clause may be omitted

Conditional Branch Instructions

IF (X=1) THEN Y = 5 ELSEIF (X=3) THEN Y = 4 ELSEIF (X=6) THEN Y = 3 ELSE Y = 2 END IF SELECT CASE X CASE 1 Y = 5 CASE 3 Y = 4 CASE 6 Y = 3 CASE 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 used SELECT CASE variable CASE IS range1 Do instruction block 1 CASE IS range2 Do instruction block 2 CASE ELSE Do instruction block 3 END SELECT

Conditional Branch Instructions

IF (X<10) THEN Y = 5 ELSEIF (X<20) THEN Y = 4 ELSEIF (X<30) THEN Y = 3 ELSE Y = 2 END IF SELECT CASE X CASE IS <10 Y = 5 CASE IS <20 Y = 4 CASE IS <30 Y = 3 CASE ELSE Y = 2 END SELECT The two code fragments accomplish the same result

Translating Conditional Branch Instructions

 Look at the METHOD  Each 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: FARE Given: Age Change: None Result: Price Intermediates: None Definition: Price := FARE(Age) Get Age If (Age < 16) Let Price = $7 Else If (Age > 65) Else Let Price = $5 Let Price = $10 Give Price

Translate 4

 Translate Algorithm 2.4

Name: FARE Given: Age Change: None Result: Price Intermediates: None Definition: Price := FARE(Age) Get Age If (Age < 16) Let Price = $7 Else If (Age > 65) Let Price = $5 Else Let Price = $10 Give 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: FARE Given: Age Change: None Result: Price Intermediates: None Definition: Price := FARE(Age) Get Age If (Age < 16) Let Price = $7 Else If (Age > 65) Let Price = $5 Else Let Price = $10 Give Price Option Explicit

Algorithm 2.4

'Written By T. James Sub Fare() Dim Age as Integer Dim Price as Single Age = InputBox("Age?") If (Age < 16) Then Price = 7.00

ElseIf (Age > 65) Then Price = 5.00

Else Price = 10.00

End If MsgBox("Fare is " & Price) End Sub

Translate 5

 Translate Algorithm 2.2

Name: BIG3 Givens: N1, N2, N3 Result: Largest Intermediate: None Definition: Largest := BIG3(N1,N2,N3) Get N1 Get N2 Get N3 If (N1 > N2) Let Largest = N1 Else Let Largest = N2 If (N3 > Largest) Let Largest = N3 Give Largest

Translate 5

 Translate Algorithm 2.2

Name: BIG3 Givens: N1, N2, N3 Result: Largest Intermediate: None Definition: Largest := BIG3(N1,N2,N3) Get N1 Get N2 Get 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.2

Name: BIG3 Givens: N1, N2, N3 Result: Largest Intermediate: None Definition: Largest := BIG3(N1,N2,N3) Get N1 Get N2 Get N3 If (N1 > N2) Let Largest = N1 Else Let Largest = N2 If (N3 > Largest) Let Largest = N3 Give Largest Option Explicit

Algorithm 2.2

'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?") If (N1>N2) Then Largest = N1 Else Largest = N2 End If If (N3 > Largest) Then Largest = N3 End If MsgBox("L = " & Largest) End Sub

Translate 6

 Translate Algorithm 2.5

Name: MEDICAL Given: Expense Change: None Result: Refund Intermediates: LL, UL (Constants) Definition: Refund := MEDICAL(Expense) Set LL = 100 Set UL = 2,000 Get Expense If (Expense <= LL) Let Refund = 0 Else If (Expense <= UL) Let Refund = 90% (Expense-LL) Else Let Refund = 90% (UL-LL) + 100% (Expense - UL) Give Refund

Translate 6

 Translate Algorithm 2.5

Name: MEDICAL Given: Expense Change: None Result: Refund Intermediates: LL, UL (Constants) Definition: Refund := MEDICAL(Expense) Set LL = 100 Set UL = 2,000 Get Expense If (Expense <= LL) Let Refund = 0 Else If (Expense <= UL) Let Refund = 90% (Expense-LL) Else Let 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.5

Name: MEDICAL Given: Expense Change: None Result: Refund Intermediates: LL, UL (Constants) Definition: Refund := MEDICAL(Expense) Set LL = 100 Set UL = 2,000 Get Expense If (Expense <= LL) Let Refund = 0 Else If (Expense <= UL) Let Refund = 90% (Expense-LL) Else Let Refund = 90% (UL-LL) + 100% (Expense - UL) Give Refund Option Explicit 'Written By T. James

Algorithm 2.5

Sub 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

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

W

atch

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

is analogous to tracing debug capabilities

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 execution 

Quick 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.00

 Develop the visual basic code that will accept the sale price of the automobile and calculate and display the sales representative’s commission.