Section 5.2. If Blocks


[Page 201]

5.2. If Blocks

An If block allows a program to decide on a course of action based on whether certain conditions are true or false.

If Block

A block of the form:


If condition Then


action1


Else


action2


End If


causes the program to take action1 if condition is true and action2 if condition is false. Each action consists of one or more Visual Basic statements. After an action is taken, execution continues with the line after the If block. Figure 5.1 contains the pseudocode and flowchart for an If block.

Figure 5.1. Pseudocode and flowchart for an If block.


Example 1.
(This item is displayed on pages 201 - 202 in the print version)

The following program finds the larger of two numbers input by the user . The condition is


num1 > num2


and each action consists of a single assignment statement. With the inputs 3 and 7, the condition is false, and so the second action is taken.


[Page 202]

Object

Property

Setting

frmMaximum

Text

Maximum

lblFirstNum

Text

First Number:

txtFirstNum

   

lblSecondNum

Text

Second Number:

txtSecondNum

   

btnFindLarger

Text

Find Larger Number

txtResult

ReadOnly

True




Private Sub



btnFindLarger_Click(



...



)



Handles



btnFindLarger.Click



Dim



num1, num2, largerNum



As Double



num1 =



CDbl



(txtFirstNum.Text)


num2 =



CDbl



(txtSecondNum.Text)



If



num1 > num2



Then



largerNum = num1



Else



largerNum = num2



EndIf



txtResult.Text =

"The larger number is "

& largerNum



End Sub



[Run, type 3 and 7 into the text boxes, and press the button.]

Example 2.
(This item is displayed on pages 202 - 203 in the print version)

The following program requests the costs and revenue for a company and displays the message "Break even" if the costs and revenue are equal; otherwise , it displays the profit or loss. The action following Else is another If block.

Object

Property

Setting

frmStatus

Text

Profit/Loss

lblCosts

Text

Costs:

txtCosts

   

lblRev

Text

Revenue:

txtRev

   

btnShow

Text

Show Financial Status

txtResult

ReadOnly

True



[Page 203]



Private Sub

btnShow_Click(

...

)

Handles

btnShow.Click



Dim

costs, revenue, profit, loss

As Double



costs =

CDbl

(txtCosts.Text)


revenue =

CDbl

(txtRev.Text)



If

costs = revenue

Then



txtResult.Text =

"Break even"




Else




If

costs < revenue

Then



profit = revenue - costs


txtResult.Text =

"Profit is "

& FormatCurrency(profit)



Else



loss = costs - revenue


txtResult.Text =

"Loss is "

& FormatCurrency(loss)



End If




End If




End Sub



[Run, type 9500 and 8000 into the text boxes, and press the button.]

Example 3.
(This item is displayed on pages 203 - 204 in the print version)

The If block in the following program has a logical operator in its condition.

Object

Property

Setting

frmQuiz

Text

A Quiz

lblQuestion

Text

How many gallons does a ten-gallon hat hold?

txtAnswer

   

btnEvaluate

Text

Evaluate Answer

txtSolution

ReadOnly

True




Private Sub

btnEvaluate_Click(

...

)

Handles

btnEvaluate.Click



'Evaluate answer




Dim

answer

As Double



answer =

CDbl

(txtAnswer.Text)



If

(answer >= 0.5)

And

(answer <= 1)

Then



txtSolution.Text =

"Good, "




Else



[Page 204]

txtSolution.Text =

"No, "




End If



txtSolution.Text &=

"it holds about 3/4 of a gallon."




End Sub



[Run, type 10 into the text box, and press the button.]

The Else part of an If block can be omitted. This important type of If block appears in the next example.

Example 4.
(This item is displayed on pages 204 - 205 in the print version)

The following program offers assistance to the user before presenting a quotation.

Object

Property

Setting

frmQuotation

Text

Quotation

lblQuestion

Text

Do you know what the game of skittles is (Y/N)?

mtxtAnswer

Mask

L

btnDisplay

Text

Display Quotation

txtQuote

ReadOnly

True


{% if main.adsdop %}{% include 'adsenceinline.tpl' %}{% endif %}



Private Sub

btnDisplay_Click(

...

)

Handles

btnDisplay.Click



Dim

message

As String



message =

"Skittles is an old form of bowling in which a wooden "

& _



"disk is used to knock down nine pins arranged in a square."




If

mtxtAnswer.Text.ToUpper =

"N"


Then



MsgBox(message, 0,

""

)



End If



txtQuote.Text =

"Life ain't all beer and skittles."

& _



" - Du Maurier (1894)"




End Sub



[Run, type "N" into the masked text box, and press the button.]


[Page 205]

[Press OK.]

Note: Rerun the program, type "Y" into the masked text box, press the button, and observe that the description of the game is skipped .

ElseIf Clauses

An extension of the If block allows for more than two possible alternatives with the inclusion of ElseIf clauses. A typical block of this type is


If condition1 Then


action1


ElseIf condition2 Then


action2


ElseIf condition3 Then


action3


Else


action4


End If


This block searches for the first true condition, carries out its action, and then skips to the statement following End If. If none of the conditions is true, then Else's action is carried out. Execution then continues with the statement following the block. In general, an If block can contain any number of ElseIf clauses. As before, the Else clause is optional.


[Page 206]
Example 5.

The following program redoes Example 1 so that if the two numbers are equal, the program so reports :



Private Sub

btnFindLarger_Click(

...

)

Handles

btnFindLarger.Click



Dim

num1, num2

As Double



num1 =

CDbl

(txtFirstNum.Text)


num2 =

CDbl

(txtSecondNum.Text)



If

(num1 > num2)

Then



txtResult.Text =

"The larger number is "

& num1



ElseIf

(num2 > num1)

Then



txtResult.Text =

"The larger number is "

& num2



Else



txtResult.Text =

"The two numbers are equal."




End If




End Sub



[Run, type 7 into both text boxes, and press the button.]

If blocks allow us to define functions whose values are not determined by a simple formula. The function in Example 6 uses an If block.

Example 6.
(This item is displayed on pages 206 - 207 in the print version)

The Social Security or FICA tax has two componentsthe Social Security benefits tax, which in 2005 is 6.2 percent on the first $90,000 of earnings for the year, and the Medicare tax, which is 1.45 percent of earnings. The following program calculates an employee's FICA tax for the current pay period.

Object

Property

Setting

frm FICA

Text

FICA Taxes

lblToDate

Text

Total earnings for this year prior to the current pay period:

txtToDate

   

lblCurrent

Text

Earnings for the current pay period:

txtCurrent

   

btnCalculate

Text

Calculate FICA Taxes

lblTax

Text

FICA taxes for the current pay period:

txtTax

ReadOnly

True



[Page 207]



Private Sub



btnCalculate_Click(

...

)



Handles



btnCalculate.Click



Dim



ficaTaxes



As Double



ficaTaxes = CalcFICA(



CDbl



(txtToDate.Text),



CDbl



(txtCurrent.Text)) txtTax.Text = FormatCurrency(ficaTaxes)



End Sub




Function



CalcFICA(



ByVal



ytdEarnings



As Double


, _


ByVal



curEarnings



As Double



)



As Double




'Calculate Social Security benefits tax and Medicare tax




'for a single pay period in 2005




Dim



socialSecurityBenTax, medicareTax



As Double




If



(ytdEarnings + curEarnings) <= 90000 Then


socialSecurityBenTax = 0.062 * curEarnings



ElseIf



ytdEarnings < 90000



Then



socialSecurityBenTax = 0.062 * (90000 - ytdEarnings)



End If



medicareTax = 0.0145 * curEarnings



Return



socialSecurityBenTax + medicareTax



End Function



[Run, type 12345.67 and 543.21 into the top two text boxes, and press the button. The following is displayed in txtTax.]

$41.56


Comments

  1. Constructs in which an If block is contained inside another If block are referred to as nested If blocks.

  2. Care should be taken to make If blocks easy to understand. For instance, in Figure 5.2, the block on the left is difficult to follow and should be replaced by the clearer block on the right.

    Figure 5.2. A confusing If block and an improvement.

    
    If
    
    cond1
    
    Then If
    
    cond2
    
    Then
    
    action
    
    End If End If
    
    

    
    If
    
    cond1
    
    And
    
    cond2
    
    Then
    
    action
    
    End If
    
    


  3. In Appendix C, the section "Stepping through Programs Containing Decision Structures: Chapter 5" uses the Visual Basic debugging tools to trace the flow through an If block.

  4. Some programs call for selecting among many possibilities. Although such tasks can be accomplished with complicated If blocks, the Select Case block (discussed in the next section) is often a better alternative.


[Page 208]
Practice Problems 5.2
1.

Suppose the user is asked to input a number into txtNumber for which the square root is to be taken. Fill in the If block so that the lines of code that follow will display either the message "Number can't be negative." or the square root of the number.


Private Sub btnSqrt_Click(...) Handles btnSqrt.Click


'Check reasonableness of data


Dim num As Double


num = CDbl(txtNumber.Text)


If


End If


End Sub


2.

Improve the block


If a < b Then


If c < 5 Then


txtBox.Text =

"hello"



End If


End If


Exercises 5.2

In Exercises 1 through 12, determine the output displayed in the text box when the button is clicked.

1.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


Dim num As Double = 4


If num <= 9 Then


txtOutput.Text = "Less than ten."


Else


If num = 4 Then


txtOutput.Text = "Equal to four."


End If


End If


End Sub


2.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


Dim gpa As Double = 3.49


txtOutput.Clear()


If gpa >= 3.5 Then


txtOutput.Text = "Honors "


End If


txtOutput.Text &= "Student"


End Sub



[Page 209]
3.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


Dim a As Double = 5


txtOutput.Clear()


If (3 * a - 4) < 9 Then


txtOutput.Text = "Remember, "


End If


txtOutput.Text &= "tomorrow is another day."


End Sub


4.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


Dim change As Double = 356 'Amount of change in

cents



If change >= 100 Then


txtOutput.Text = "Your change contains " & _


Int(change / 100) & " dollars."


Else


txtOutput.Text = "Your change contains no dollars."


End If


End Sub


5.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


Dim a as Double = 2


Dim b As Double = 3


Dim c As Double = 5


If a * b < c Then


b = 7


Else


b = c * a


End If


txtOutput.Text = CStr(b) End Sub


6.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


Dim a, b As Double


a = CDbl(InputBox("Enter a number."))


b = CDbl(InputBox("Enter another number."))


If a > b Then


a += 1


Else


b += 1


End If


txtOutput.Text = a & " "& b End Sub


(Assume the responses are 7 and 11.)

7.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


'Cost of phone call from New York to London


Dim length As Double


InputLength(length)


DisplayCost(length)


End Sub


[Page 210]

Function Cost(ByVal length As Double) As Double


If length < 1 Then


Return .46


Else


Return .46 + (length - 1) * .36


End If


End Function


Sub DisplayCost(ByVal length As Double)


'Display the cost of a call


txtBox.Text = "Cost of call: "& FormatCurrency(Cost(length))


End Sub


Sub InputLength(ByRef length As Double)


'Request the length of a phone call


length = CDbl(InputBox("Duration of the call in minutes?"))


End Sub


(Assume the response is 31 .)

8.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


Dim letter As String


letter = InputBox("Enter A, B, or C.")


If letter = "A" Then


DisplayAmessage()


ElseIf letter = "B" Then


DisplayBmessage()


ElseIf letter = "C" Then


DisplayCmessage()


Else


txtOutput.Text = "Not a valid letter."


End If


End Sub


Sub DisplayAmessage()


txtOutput.Text = "A, my

name

is Alice."


End Sub


Sub DisplayBmessage()


txtOutput.Text = "To be, or not to be."


End Sub


Sub DisplayCmessage()


txtOutput.Text = "Oh, say, can you see."


End Sub


(Assume the response is B .)

9.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


Dim vowels As Integer 'Number of

vowels



ExamineLetter(vowels)


[Page 211]

ExamineLetter(vowels)


ExamineLetter(vowels)


txtOutput.Text = "The number of vowels is "& vowels End Sub Sub ExamineLetter(ByRef vowels As Integer)


Dim ltr As String


ltr = InputBox("Enter a letter.")


ltr = ltr.ToUpper


If (ltr = "A") Or (ltr = "E") Or (ltr = "I") Or _


(ltr = "O") Or (ltr = "U") Then


vowels += 1


End If


End Sub


(Assume the three responses are U , b , and a .)

10.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


Dim a As Double = 5


If (a > 2) And ((a = 3) Or (a < 7)) Then


txtOutput.Text = "Hi"


End If


End Sub


11.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


Dim num As Double = 5


If num < 0 Then


txtOutput.Text = "neg"


Else


If num = 0 Then


txtOutput.Text = "zero"


Else


txtOutput.Text = "positive"


End If


End If


End Sub


12.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


Dim msg As String, age As Integer


msg = "You are eligible to vote"


age = CInt(InputBox("Enter your age."))


If age >= 18 Then


txtOutput.Text = msg


Else


txtOutput.Text = msg & " in "& (18 - age) & "

years

."


End If


End Sub


(Assume the response is 16 .)


[Page 212]

In Exercises 13 through 20, identify the errors.

13.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


Dim num As Double = 0.5


If (1 < num < 3) Then


txtOutput.Text = "Number is between 1 and 3."


End If


End Sub


14.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


Dim num As Double = 6


If num > 5 And < 9 Then


txtOutput.Text = "Yes"


Else


txtOutput.Text = "No"


End If


End Sub


15.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


If (2 <> 3)


txtOutput.Text = "Numbers are not equal"


End If End Sub


16.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


Dim major As String


major = "Computer Science"


If major = "Business" Or "Computer Science" Then


txtOutput.Text = "Yes"


End If


End Sub


17.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


Dim numName As String, num As Double


numName = "Seven"


num = CDbl(InputBox("Enter a number."))


If num < numName Then


txtOutput.Text = "Less than"


Else


txtOutput.Text = "Greater than"


End If


End Sub


18.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


'Change switch from "on" to "off", or from "off" to "on"


Dim switch As String


switch = InputBox("Enter On or Off.")


If switch = "Off" Then


switch = "On"


End If


[Page 213]

If switch = "On" Then


switch = "Off"


End If


txtOutput.Text = switch


End Sub


19.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


'Display "OK" if either j or k equals 4


Dim j As Double = 2


Dim k As Double = 3


If j Or k = 4 Then


txtOutput.Text = "OK"


End If


End Sub


20.


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click


'Is your program correct?


Dim query, answer1, answer2 As String


query = "Are you sure everything in your program is correct?"


answer1 = InputBox(query)


answer1 = answer1.ToUpper.Substring(0, 1)


If answer1 = "N" Then


txtOutput.Text = "Don't patch bad code, rewrite it."


Else


query = "Does your program run correctly?"


answer2 = InputBox(query)


answer2 = answer2.ToUpper.Substring(0, 1)


If answer2 = "Y" Then


txtOutput.Text = "Congratulations."


Else


txtOutput.Text = "Something you are sure about is wrong."


End If


End Sub


In Exercises 21 through 26, simplify the code.

21.


If (a = 2) Then


a = 3 + a


Else


a = 5


End If


22.


If Not (answer <> "y") Then


txtOutput.Text = "YES"


Else


If (answer = "y") Or (answer = "Y") Then


txtOutput.Text = "YES"


End If


End If



[Page 214]
23.


If (j = 7) Then


b = 1


Else


If (j <> 7) Then


b = 2


End If


End If


24.


If (a < b) Then


If (b < c) Then


txtOutput.Text = b & " is between "& a & " and "& c


End If


End If


25.


message = "Is Alaska bigger than Texas and California combined?"


answer = InputBox(message)


If (answer.Substring(0, 1) = "Y") Then


answer = "YES"


End If


If (answer.Substring(0, 1) = "y") Then


answer = "YES"


End If


If (answer = "YES") Then


txtOutput.Text = "Correct"


Else


txtOutput.Text = "Wrong"


End If


26.


message = "How tall (in feet) is the Statue of Liberty?"


feet = CDbl(InputBox(message))


If (feet <= 141) Then


lstOutput.Items.Add("Nope")


End If


If (feet > 141) Then


If (feet < 161) Then


lstOutput.Items.Add("Close")


Else


lstOutput.Items.Add("Nope")


End If


End If


sltOutput.Items.Add("The statue is 151 feet from base to torch.")


27.

Write a program to determine how much to tip the server in a restaurant. The tip should be 15 percent of the check, with a minimum of $1.

28.

A bagel shop charges 75 cents per bagel for orders of less than a half-dozen bagels and charges 60 cents per bagel for orders of a half-dozen or more bagels. Write a program that requests the number of bagels ordered and displays the total cost. (Test the program for orders of four bagels and a dozen bagels.)


[Page 215]
29.

A computer store sells diskettes at 25 cents each for small orders or at 20 cents each for orders of 100 diskettes or more. Write a program that requests the number of diskettes ordered and displays the total cost. (Test the program for purchases of 5 and 200 diskettes.)

30.

A copy center charges 5 cents per copy for the first 100 copies and 3 cents per copy for each additional copy. Write a program that requests the number of copies as input and displays the total cost. (Test the program with the quantities 25 and 125.)

31.

Write a quiz program to ask "Who was the first Ronald McDonald?" The program should display "Correct." if the answer is "Willard Scott" and "Nice try" for any other answer.

32.

Suppose a program has a button with the caption "Quit." Suppose also that the Name property of this button is btnQuit. Write a btnQuit_Click event procedure that gives the user a second chance before ending the program. The procedure should use an input box to request that the user confirm that the program should be terminated , and then end the program only if the user responds in the affirmative .

33.

Write a program to handle a savings-account withdrawal. The program should request the current balance and the amount of the withdrawal as input and then display the new balance. If the withdrawal is greater than the original balance, the program should display "Withdrawal denied ." If the new balance is less than $150, the message "Balance below $150" should be displayed.

34.

Write a program that requests three scores as input and displays the average of the two highest scores. The input and output should be handled by Sub procedures, and the average should be determined by a user-defined function.

35.

A grocery store sells apples for 79 cents per pound . Write a cashier's program that requests the number of pounds and the amount of cash tendered as input and displays the change from the transaction. If the cash is not enough, the message "I need $x.xx more." should be displayed, where $x.xx is the difference between the cash and the total cost. (Test the program with six pounds and $5, and four pounds and $3.)

36.

Federal law requires hourly employees be paid "time-and-a-half" for work in excess of 40 hours in a week. For example, if a person's hourly wage is $8 and he works 60 hours in a week, his gross pay should be

(40 x 8) + (1.5 x 8 x (60 - 40)) = $560

Write a program that requests as input the number of hours a person works in a given week and his hourly wage, and then displays his gross pay.

37.

Write a program that requests a word (with lowercase letters ) as input and translates the word into pig latin. The rules for translating a word into pig latin are as follows :

  1. If the word begins with a consonant, move the first letter to the end of the word and add ay . For instance, chip becomes hipcay .

  2. If the word begins with a vowel, add way to the end of the word. For instance, else becomes elseway .

38.

The current calendar, called the Gregorian calendar, was introduced in 1582. Every year divisible by four was declared to be a leap year, with the exception of the years ending in 00 (that is, those divisible by 100) and not divisible by 400. For instance, the years 1600 and 2000 are leap years, but 1700, 1800, and 1900 are not. Write a program that requests a year as input and states whether it is a leap year. (Test the program on the years 1994, 1995, 1900, and 2000.)


[Page 216]
39.

Create a form with a text box and two buttons captioned Bogart and Raines. When Bogart is first pressed, the sentence "I came to Casablanca for the waters." is displayed in the text box. The next time Bogart is pressed, the sentence "I was misinformed." is displayed. When Raines is pressed, the sentence "But we're in the middle of the desert." is displayed. Run the program and then press Bogart, Raines, and Bogart to obtain a dialogue.

40.

Write a program that allows the user to use a button to toggle the color of the text in a text box between black and red.

41.

Write a program that allows the user ten tries to answer the question, "Which U.S. President was born on July 4?" After three incorrect guesses, the program should display the hint, "He once said, 'If you don't say anything, you won't be called upon to repeat it."' in a message box. After seven incorrect guesses, the program should give the hint, "His nickname was 'Silent Cal."' The number of guesses should be displayed in a text box. Note: Calvin Coolidge was born on July 4, 1872.

42.

Write a program that reads a test score from a text box each time a button is clicked and then displays the two highest scores whenever a second button is clicked. Use two class-level variables to track the two highest scores.

43.

The flowchart in Figure 5.3 (on the next page) calculates New Jersey state income tax. Write a program corresponding to the flowchart. (Test the program with taxable incomes of $15,000, $30,000, and $60,000.)

Figure 5.3. Flowchart for New Jersey state income tax program
(This item is displayed on page 217 in the print version)


44.

Write a program to play "Hide and Seek" with the name of our programming language. When the button is pressed, the name should disappear and the caption on the button should change to "Show Name of Language." The next time the button is pressed, the name should reappear and the caption should revert to "Hide Name of Language," and so on.

Object

Property

Setting

frmHideSeek

Text

Hide and Seek

lblLanguage

Text

VB 2005

 

Font.Size

26

btnDisplay

Text

Hide Name of Language


Solutions to Practice Problems 5.2
1.


If (num < 0) Then


MsgBox("Number can't be negative.", 0, "Input Error")


txtNumber.Clear()


txtNumber.Focus()


Else


txtSquareRoot.Text = CStr(Math.Sqrt(num))


End If



[Page 218]
2.

The word "hello" will be displayed when (a < b)is true and (c < 5)is also true. That is, it will be displayed when both of these two conditions are true. The clearest way to write the block is


If (a < b) And (c < 5) Then


txtBox.Text = "hello"


End If