211
Student Solutions Manual (Page 1 of 211) STUDENT SOLUTIONS MANUAL to accompany An Introduction to Programming Using Visual Basic 2010, 8th Edition by David I. Schneider

Itroduction to Programming With Visual Basics

Embed Size (px)

DESCRIPTION

asdf

Citation preview

  • Student Solutions Manual (Page 1 of 211)

    STUDENT

    SOLUTIONS

    MANUAL

    to accompany

    An Introduction to Programming

    Using Visual Basic 2010, 8th Edition

    by David I. Schneider

  • Student Solutions Manual (Page 2 of 211)

    Copyright 2011 by Pearson Higher Education. All rights reserved.

  • Student Solutions Manual (Page 3 of 211)

    CONTENTS

    Chapter Comments

    Chapter 2 Visual Basic Controls and Events Exercises 2.2 Visual Basic Controls 11 Exercises 2.3 Visual Basic Events 15

    Chapter 3 Variables, Input, and Output Exercises 3.1 Numbers 18 Exercises 3.2 Strings 21 Exercises 3.3 Input and Output 26

    Chapter 4 Decisions Exercises 4.1 Relational and Logical Operators 30 Exercises 4.2 If Blocks 31 Exercises 4.3 Select Case Blocks 38 Exercises 4.4 Input via User Selection 42

    Chapter 5 General Procedures Exercises 5.1 Function Procedures 47 Exercises 5.2 Sub Procedures, Part I 50 Exercises 5.3 Sub Procedures, Part II 55

    Chapter 6 Repetition Exercises 6.1 Do Loops 57 Exercises 6.2 ForNext Loops 62 Exercises 6.3 List Boxes and Loops 68

    Chapter 7 Arrays Exercises 7.1 Creating and Accessing Arrays 77 Exercises 7.2 Using LINQ with Arrays 85 Exercises 7.3 Arrays of Structures 89 Exercises 7.4 Two-Dimensional Arrays 99

    Chapter 8 Text Files Exercises 8.1 Managing Text Files 106 Exercises 8.2 StreamReaders, StreamWriters, Structured Exception Handling 111 Exercises 8.3 XML 115

    Chapter 9 Additional Controls and Objects Exercises 9.1 List Boxes and Combo Boxes 120 Exercises 9.2 Eight Additional Controls and Objects 125 Exercises 9.3 Multiple-Form Programs 132 Exercises 9.4 Graphics 142

  • Student Solutions Manual (Page 4 of 211)

    Chapter 10 Databases Exercises 10.1 An Introduction to Databases 151 Exercises 10.2 Editing and Designing Databases 164

    Chapter 11 Object-Oriented Programming Exercises 11.1 Classes and Objects 165 Exercises 11.2 Working with Objects 172 Exercises 11.3 Inheritance 186

    Chapter 12 Web Applications Exercises 12.1 Programming for the Web, Part 1 193 Exercises 12.2 Programming for the Web, Part 2 199 Exercises 12.3 Using Databases in Web Programs 204

  • Student Solutions Manual (Page 5 of 211)

    Chapter Comments

    Chapter 1

    1. Your instructor might skip this chapter. If so, I recommend that you take a quick look at two items from the chapter. Look at the last question and answer on page 3 to see how the appearance of a program varies with the version of Windows being used. Also, look at the discussion of "Displaying File Extensions" on pages 5 and 6. I recommend that you configure Windows to show all file extensions.

    Chapter 2

    1. On page 44 you are asked to run a program that was downloaded from the Pearson website for the book. All of the programs appearing in Examples and Case Studies can be downloaded from that website. There is never any need for you to manually type in the code for a program in this textbook. The website also contains all the text files, databases, and pictures needed for the exercises.

    All of these files are contained in the folders Ch02, Ch03, Ch04, and so on. Each chapter file contains a subfolder named Text_Files_for_Exercises which contains the text files needed for that chapters exercises. The folder Ch09 has a subfolder named Pictures that contains picture files. The folders Ch10 and "Ch12" have a subfolder named Databases containing all the databases needed for the exercises.

    Each program is contained in a folder with a name in the form chaptersectionexample number. For instance, the program in Chapter 3, Section 1, Example 2 is contained in the folder 3-1-2. Many of the programs make use of a text file in the subfolder Debug of the programs bin subfolder.

    2. At the top of page 44, we explain our use of ellipses (...) as place holders for the phrase "ByVal sender As System.Object, ByVal e As System.EventArgs". A program will not run when the phrase is replaced with an ellipsis. However, a program will run if the phrase is simply deleted. Therefore, if you use Ctrl+C to copy code from this Student Solutions Manual and paste it into your own program, the code will execute after you delete the ellipses.

    3. Every program you write requires use of the Properties window. By default, the Properties window is docked to the right side of the IDE. You might find the Properties window easier to use if you undock it while setting properties. If you double-click on the Properties windows title bar, the window will become undocked and larger. After you have finished using the Properties window, right-click on its title bar and click on Dock. Note: This process also can be used to undock (and redock) the Toolbar and the Solution Explorer window.

  • Student Solutions Manual (Page 6 of 211)

    Chapter 3

    1. Figure 3.1 on page 70 shows the settings for Options Explicit, Strict, and Infer set to On. Most instructors will recommend that the first two Options be set to On. Option Infer, on the other hand, is controversial. (The default setting is On.) If you want to learn more about the effect of Option Infer, take a quick look at the discussion of local type inference on page 236.

    2. On page 77, we discuss line continuation. In earlier versions of Visual Basic, the underscore character was needed to continue a statement onto another line. Beginning with VB2010, the underscore character can be omitted when a line that obviously has a continuation (such as, when the line ends with a comma or an arithmetic operator) and therefore will seldom be needed in the programs you write. Underscore characters frequent appear in the answer section of the book and in the Student Solutions Manual following the word "Handles". This was necessary due to the fact that we must limit the length of lines in a printed page.

    3. A discussion of sending output to the printer is presented at the end of Section 3.3. This material is optional. If your instructor decides to skip this topic, you might want to take a quick look (just a few minutes) to see what's involved in printing the output of a program. This material is not needed in the textbook. I included it at the request of some instructors.

    Chapter 4

    1. Section 4.1 is unusual in that you will not be asked to write any programs in the exercise set. However, the concepts presented in this section will be fundamental to the rest of the textbook.

    2. In Chapter 3 we used list boxes to display data. In Section 4.4, we show how list boxes are used to allow the user to make selections. Another control used to make a selection from a list, a combo box, will be discussed in Chapter 9.

    3. The first two sentences after Figure 4.12 on page 149 should read as follows:

    When you click on an unselected item in a list box, the SelectedIndexChanged event is raised. When you click on a check box or on an unchecked radio button, the CheckedChanged event is raised.

  • Student Solutions Manual (Page 7 of 211)

    Chapter 5

    1. Except for the three case studies, Function procedures appear in many more programs than Sub procedures. The use of Sub procedures is part of good programming practice, but it is not essential. Any computer program can be written without Sub procedures. However, there are a number of programs in this textbook that would be very difficult to write without Function procedures.

    2. The above comment is not intended to diminish the importance of Sub procedures. They are a fundamental component of good program design. However, if you find Sub procedures somewhat confusing at first, don't worry. You will still be able to work the exercises. You will eventually become comfortable with Sub procedures after seeing them used in subsequent chapters.

    Chapter 6

    1. There are two types of loops presented in this chapterDo loops and For...Next loops. A third type of loop, called a For Each loop, will be presented in Section 7.1.

    2. Loops have traditionally been used to process lists of data. For instance, loops can be used with a list of numbers to compute the sum of the numbers, the average of the numbers, the largest number in the list and the smallest number in the lists. The algorithms for calculating sums and averages is obvious. In Example 4 of Section 6.3, the maximum value of the numbers in a list box are calculated with the following algorithm:

    (a) Declare a variable named max.

    (b) Assign a value to the variable that is guaranteed to be less than or equal to the maximum value in the list. One possibility is to set the value of max equal to the first number in the list. Another possibility requires some knowledge of the number in the list. For instance, if the number are all grades on an exam, the initial value of max can be set to 0.

    (c) Use a loop to examine the numbers one at a time. Whenever a number is greater than the current value of max, change the value of max to be that number. After the loop has executed, the value of max will be the largest number in the list.

    Example 4 uses an analogous algorithm to find the smallest number in the list box. These two algorithms appear several times in the textbook in both examples and exercises.

    3. Section 6.3 presents techniques for processing lists of data with loops. In Section 7.2, a method for processing lists without using loops will be presented.

  • Student Solutions Manual (Page 8 of 211)

    Chapter 7

    1. A very important idea to take away from Section 7.1 is that there are four ways to fill an array. Let's illustrate the ways by filling an array with the names of the first three presidents.

    (a) Dim pres() As String = {"Washington", "Jefferson", "Adams}

    (b) Dim pres() As String = IO.File.ReadAllLines("Pres.txt"), where the text file Pres.txt is located in the program's bin\Debug folder of the program and contains three lines (each containing the name of a president).

    (c) Dim strVar As String = "Washington,Jefferson,Adams"

    Dim pres() As String = strVar.Split(","c)

    (d) Dim pres(2) As String

    pres(0) = "Washington"

    pres(1) = "Jefferson"

    pres(2) = "Adams"

    In the first three ways, the array is declared and sized automatically at the same time it is filled. The second and third ways will be the most used in this book.

    2. Section 7.3 is perhaps the most challenging section in the book. However, the techniques presented in this section are very powerful and are heavily used later in the book with text files and databases. The techniques also are presented in Section 8.1 in a slightly different form. Some instructors will skip Section 7.3 and rely solely on Section 8.1.

    3. Some important text files used in this chapter are as follows: a. Baseball.txt: contains statistics for all of the players in the major league who had at least 350 at bats in 2009. b. Justices.txt: contains all people who served on the U.S. Supreme Court prior to May 2010. c. SBWinners.txt: contains all Super Bowl winners up to and including 2010.

    Chapter 8

    1. The two sections in this chapter are independent of each other.

    2. The preliminaries section at the beginning of Section 8.1 can be omitted if you covered Section 8.3. The techniques presented in the preliminaries will take a fair amount of effort to master. However, the payoff will be substantial.

    3. Section 8.1 shows some modern techniques for combining lists of data. In earlier versions of Visual Basic, these tasks could only be carried out with complicated algorithms involving loops.

  • Student Solutions Manual (Page 9 of 211)

    4. Some important data files used in this chapter are as follows: a. Baseball.xml: contains statistics for all of the players in the major league who had at least 350 at bats in 2009.

    b. Justices.txt: contains all people who served on the U.S. Supreme Court prior to the summer of 2010. Justice Stevens retired in the summer of 2010. If you want to update the file after his replacement is named, change the last entry in his record to 2010 and add a record for the person replacing him. c. Senate111.txt: contains the composition of the U.S. Senate as of May 1, 2010. d. USPres.txt: contains the names of all U.S.

    Chapter 9

    1. Most of Chapter 9 is not needed in the remainder of the book. However, the chapter shows how to use several tools that are familiar to you from major programs you have used.

    2. Programs written by professional programmers often use more than one form. Section 9.3 shows how this is done. However, since this is an introductory book, all programs outside of Section 9.3 use only one form.

    Chapter 10

    1. The steps for binding a database to a program may look complicated at first. However, after you get used to it you will find it easy and quick to carry out. Also, when you work several exercises using the same database, you can just bind the database once and write a different event procedure for each exercise.

    2. Some important databases used in this chapter are as follows: a. Baseball.accdb: contains statistics for all of the players in the major league who had at least 350 at bats in 2009. b. Justices.accdb: contains all people who served on the U.S. Supreme Court prior to the summer of 2010. c. UN.accdb: contains the composition of the United Nations as of May 1, 2010. d. Exchrate.accdb: contains currency exchange rates in December 2009.

    Chapter 11

    1. This chapter is independent of the rest of the book.

  • Student Solutions Manual (Page 10 of 211)

    Chapter 12

    1. The programs in the chapter are not created with Visual Basic. Most people will use Visual Web Developer that is contained on the DVD packaged with this book. However, if you have a complete version of Visual Studio, you do not have to install Visual Web Developer. The Visual Studio File menu contains the items New Web Site and Open Web Site that you can use to create and access Web programs.

    2. Be sure to read the solution to the practice problem in Section 12.3. It shows you how to save a lot of time when writing the programs for the exercise set.

  • Student Solutions Manual (Page 11 of 211)

    CHAPTER 2

    EXERCISES 2.2

    1. After a button is clicked it has a blue border.

    3. Click on the form to make it the selected object.

    Click on the Properties window or Press F4 to activate the Properties window.

    Select the Text property.

    Type "CHECKING ACCOUNT".

    5. Double-click the TextBox icon in the Toolbox.

    Activate the Properties window.

    Select the BackColor property.

    Click on the down-arrow to the right of the Settings box.

    Click on the Custom tab, and then click on the desired yellow in the palette.

    Click on the form to see the empty yellow text box.

    7. Double-click on the Label icon in the Toolbox.

    Activate the Properties window, and select the AutoSize property. Set the AutoSize property to False.

    Select the Text property and type the requested sentence.

    Select the TextAlign property.

    Click on the down-arrow button to the right of the Settings box, and click on one of the

    center rectangles.

    Resize the label so that the sentence occupies three lines.

    9. Double-click on the TextBox icon in the Toolbox.

    Activate the Properties window.

    Set the Name property to txtLanguage.

    Select the Text property and type "Visual Basic 2010".

    Select the Font property and click on the ellipsis to the right of the Settings box.

    Scroll up the Font list box, and click on Courier New in the Font box.

    Click OK.

    Widen the text box to accommodate its text.

    11. Double-click on the Button icon in the Toolbox.

    Activate the Properties window, and select the BackColor property.

    Click on the down-arrow button to the right of the Settings box.

    Click on the Custom tab, and then click on the white square in upper-left corner of the

    palette.

    Select the Text property and type "PUSH".

    Select the Font property, and click on the ellipsis.

    Click on Italic (with XP or Vista) or Oblique (with Windows 7) in the "Font style" list.

    Click on 24 in the Size box and click OK.

    Resize the button.

  • Student Solutions Manual (Page 12 of 211)

    13. Double-click on the Button icon in the Toolbox.

    Activate the Properties window.

    Select the Text property and type "PUS&H".

    Click on the form to see the resulting button.

    15. Double-click on the Label icon in the Toolbox.

    Activate the Properties window.

    Select the Name property and type "lblAKA".

    Select the Text property and type "ALIAS".

    Select the AutoSize property and set it to False.

    Select the Font property and click on the ellipsis.

    Click on Italic (with XP or Vista) or Oblique (with Windows 7) in the "Font style" list.

    Click OK.

    Select the TextAlign property, click on the down-arrow box to the right of the Settings

    box, and click on one of the center rectangles.

    17. Double-click on the Label icon in the Toolbox.

    Activate the Properties window, and select the TextAlign property.

    Click on the down-arrow box to the right of the Settings box, and click on one of the

    rectangles on the right.

    Select the AutoSize property and set it to False.

    Select the Text property, type "VISUAL BASIC", and press Enter.

    If the words " VISUAL BASIC " are on one line, resize the label until the words

    occupy two lines.

    19. Double-click on the Label icon in the Toolbox.

    Activate the Properties window, and select the Font property.

    Click on the ellipsis to the right of the Settings box.

    Click on Wingdings in the Font box.

    Click on the largest size available (72) in the Size box.

    Click OK.

    Select the Text property and change the setting to a less than sign (

  • Student Solutions Manual (Page 13 of 211)

    23. In the Solution Explorer window, right click on Form1.vb and select Rename from the context menu.

    Type frmYellow.vb. Right-click on the form in the Form Designer, and select Properties from the context

    menu.

    Click on BackColor property in the Properties window.

    Click on the down-arrow button in the right part of the Settings box, click on the

    Custom tab, and click on a yellow square.

    25. Begin a new project.

    Change the text in the form's title bar to "Dynamic Duo".

    Place two buttons on the form.

    Position and resize the buttons as shown.

    Enter Batman as the text of the first button, and enter Robin as the text of the second button.

    Increase the font size for both buttons to 14.

    27. Begin a new project.

    Change the text in the form's title bar to "Fill the Blank".

    Place a label, a text box, and another label on the form at appropriate locations.

    Change the Text setting of the first label to "Im the king of the" and the Text setting of the second label to "A Quote by Leonardo DiCaprio".

    29. Begin a new project.

    Change the text in the form's title bar to "Uncle's Advice".

    Place five labels and three buttons on the form.

    Change the Text setting of each label as indicated.

    Change the settings of the buttons' Text properties to "1", "2", and "3".

    Resize and position the labels and buttons.

    33. 1 35. Each arrow key moves the text box in the indicated direction.

    37. Pressing the right and left arrow keys widens and narrows the text boxes, buttons, and

    list boxes in the group of selected controls. The up and down arrow keys shorten and

    lengthen the buttons and list boxes in the group. The arrow keys have no effect on the

    labels, and only the left and right arrow keys affect the text boxes.

  • Student Solutions Manual (Page 14 of 211)

    39. Drag a label and a list box onto the form.

    Click on the label.

    Hold down the Ctrl key and click on the list box. (You have now selected a group of

    two controls.)

    In the Properties window, click on the plus sign (in XP) or the right-pointing triangle

    (Vista or Windows 7) to the left of the Font property.

    Click on the Size property, change the setting to 12, and press the Enter key.

    (Alternative: Replace the last three lines with the following steps.)

    In the Properties window, select the Font property.

    Click on the ellipsis button to the right of the Settings box.

    Click on 12 in the Size list and click OK.

    41. The label is positioned just to the left of the text box, and the middles of the two

    controls are aligned.

    43. Center refers to the midpoint horizontally, whereas middle refers to the midpoint

    vertically.

    45. First blue snap line: tops of the two controls are aligned

    Purple snap line: middles of the two controls are aligned

    Second blue snap line: bottoms of the two controls are aligned

    47. The setting is cycling through the different available colors.

  • Student Solutions Manual (Page 15 of 211)

    EXERCISES 2.3

    1. The word "Hello" 3. The word "Hello" on an orange-colored background

    5. The text box vanishes. 7. The word "Hello" in green letters

    9. The word "Hello" on a gold background. 11. Form1.Text should be Me.Text.

    13. Red should be replaced with Color.Red.

    15. Font.Size is a read-only property. The statement txtOutput.Text =

    txtBox.Font.Size is valid since it is reading the value of txtBox.Font.Size. However,

    txtBox.Font.Size = 20 is not valid since it is setting the value of txtBox.Font.Size.

    17. lblTwo.Text = "E.T. phone home."

    19. txtBox.ForeColor = Color.Red

    txtBox.Text = "The stuff that dreams are made of."

    21. txtBox.Enabled = False 23. lblTwo.Visible = False

    25. btnOutcome.Enabled = True 27. txtBoxTwo.Focus()

    29. The Enter event occurs when a control gets the focus.

    31. Private Sub Label1_Click(...) Handles Label1.Click

    lstOutput.Items.Add("Click")

    End Sub

    Private Sub Label1_DoubleClick(...) Handles Label1.DoubleClick

    lstOutput.Items.Add("Double Click")

    End Sub

    Whenever the DoubleClick event is raised, the Click event is also raised.

    33. Private Sub btnLeft_Click(...) Handles btnLeft.Click

    txtBox.Text = "Left Justify"

    txtBox.TextAlign = HorizontalAlignment.Left

    End Sub

    Private Sub btnCenter_Click(...) Handles btnCenter.Click

    txtBox.Text = "Center"

    txtBox.TextAlign = HorizontalAlignment.Center

    End Sub

    Private Sub btnRight_Click(...) Handles btnRight.Click

    txtBox.Text = "Right Justify"

    txtBox.TextAlign = HorizontalAlignment.Right

    End Sub

  • Student Solutions Manual (Page 16 of 211)

    35. Private Sub btnRed_Click(...) Handles btnRed.Click

    txtBox.BackColor = Color.Red

    End Sub

    Private Sub btnBlue_Click(...) Handles btnBlue.Click

    txtBox.BackColor = Color.Blue

    End Sub

    Private Sub btnWhite_Click(...) Handles btnWhite.Click

    txtBox.ForeColor = Color.White

    End Sub

    Private Sub btnYellow_Click(...) Handles btnYellow.Click

    txtBox.ForeColor = Color.Yellow

    End Sub

    37. Private Sub txtLife_Enter(...) Handles txtLife.Enter

    txtQuote.Text = "I like life, it's something to do."

    End Sub

    Private Sub txtFuture_Enter(...) Handles txtFuture.Enter

    txtQuote.Text = "The future isn't what it used to be."

    End Sub

    Private Sub txtTruth_Enter(...) Handles txtTruth.Enter

    txtQuote.Text = "Tell the truth and run."

    End Sub

    39. Private Sub btnOne_Click(...) Handles btnOne.Click

    btnOne.Visible = False

    btnTwo.Visible = True

    btnThree.Visible = True

    btnFour.Visible = True

    End Sub

    Private Sub btnTwo_Click(...) Handles btnTwo.Click

    btnOne.Visible = True

    btnTwo.Visible = False

    btnThree.Visible = True

    btnFour.Visible = True

    End Sub

    Private Sub btnThree_Click(...) Handles btnThree.Click

    btnOne.Visible = True

    btnTwo.Visible = True

    btnThree.Visible = False

    btnFour.Visible = True

    End Sub

    Private Sub btnFour_Click(...) Handles btnFour.Click

    btnOne.Visible = True

    btnTwo.Visible = True

    btnThree.Visible = True

    btnFour.Visible = False

    End Sub

  • Student Solutions Manual (Page 17 of 211)

    41. Private Sub btnVanish_Click(...) Handles btnVanish.Click

    lblFace.Visible = False

    End Sub

    Private Sub btnReappear_Click(...) Handles btnReappear.Click

    lblFace.Visible = True

    End Sub

    43. Private Sub btnAny_Click(...) Handles btnOne.Click, btnTwo.Click

    txtOutput.Text = "You just clicked on a button."

    End Sub

  • Student Solutions Manual (Page 18 of 211)

    CHAPTER 3

    EXERCISES 3.1

    1. 12 3. .125 5. 8 7. 2 9. 1 11. Not valid

    13. Valid 15. Not valid 17. 10 19. 16 21. 9

    23. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    lstOutput.Items.Add((7 * 8) + 5)

    End Sub

    25. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    lstOutput.Items.Add(0.055 * 20)

    End Sub

    27. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    lstOutput.Items.Add(17 * (3 + 162))

    End Sub

    29.

    x y

    Private Sub btnEvaluate_Click(...) Handles btnEvaluate.Click

    Dim x, y As Double 0 0

    x = 2 2 0

    y = 3 * x 2 6

    x = y + 5 11 6

    lstResults.Items.Clear() 11 6

    lstResults.Items.Add(x + 4) 11 6

    y = y + 1 11 7

    End Sub

    31. 6 33. 1 35. 1 37. 2

    8 64 15

    9

    39. The third line should read c = a + b

    41. The first assignment statement should not contain a comma. The second assignment

    statement should not contain a dollar sign.

    43. 9W is not a valid variable name. 45. Dim quantity As Integer = 12

    47. 10 49. 6 51. 3.128 53. 3 55. 0 57. 6

  • Student Solutions Manual (Page 19 of 211)

    59. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim revenue, costs, profit As Double

    revenue = 98456

    costs = 45000

    profit = revenue - costs

    lstOutput.Items.Add(profit)

    End Sub

    61. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim price, discountPercent, markdown As Double

    price = 19.95

    discountPercent = 30

    markdown = (discountPercent / 100) * price

    price = price - markdown

    lstOutput.Items.Add(Math.Round(price, 2))

    End Sub

    63. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim balance As Double

    balance = 100

    balance += 0.05 * balance

    balance += 0.05 * balance

    balance += 0.05 * balance

    lstOutput.Items.Add(Math.Round(balance, 2))

    End Sub

    65. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim balance As Double

    balance = 100

    balance = balance * (1.05 ^ 10)

    lstOutput.Items.Add(Math.Round(balance, 2))

    End Sub

    67. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim acres, yieldPerAcre, corn As Double

    acres = 30

    yieldPerAcre = 18

    corn = yieldPerAcre * acres

    lstOutput.Items.Add(corn)

    End Sub

  • Student Solutions Manual (Page 20 of 211)

    69. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim distance, elapsedTime, averageSpeed As Double

    distance = 233

    elapsedTime = 7 - 2

    averageSpeed = distance / elapsedTime

    lstOutput.Items.Add(averageSpeed)

    End Sub

    71. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim waterPerPersonPerDay, people, days, waterUsed As Double

    waterPerPersonPerDay = 1600

    people = 315000000

    days = 365

    waterUsed = waterPerPersonPerDay * people * days

    lstOutput.Items.Add(waterUsed)

    End Sub

  • Student Solutions Manual (Page 21 of 211)

    EXERCISES 3.2

    1. Visual Basic 3. Ernie 5. flute 7. 123 9. Your age is 21.

    11. A ROSE IS A ROSE IS A ROSE 13. 5.5 15. goodbye 17. WALLAWALLA

    19. ABC 21. 12 23. 8 (0 through 7) 25. True 2 MUNICIPALITY

    4 city

    55 mph 6

    STU

    27. The variable phoneNumber should be declared as type String, not Double.

    29. End is a keyword and cannot be used as a variable name.

    31. The IndexOf method cannot be applied to a number, only a string.

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

    Dim firstName, middleName, lastName As String

    Dim yearOfBirth As Integer

    firstName = "Thomas"

    middleName = "Alva"

    lastName = "Edison"

    yearOfBirth = 1847

    txtOutput.Text = firstName & " " & middleName & " " & lastName &

    ", " & yearOfBirth

    End Sub

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

    Dim publisher As String

    publisher = "Prentice Hall, Inc."

    txtOutput.Text = "(c) " & publisher

    End Sub

    37. Dim str As String 'Place in the Declarations section of the program

  • Student Solutions Manual (Page 22 of 211)

    39. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim distance As Double

    distance = CDbl(txtNumSec.Text) / 5

    distance = Math.Round(distance, 2)

    txtOutput.Text = "The distance of the storm is " & distance & " miles."

    End Sub

    41. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim cycling, running, swimming, pounds As Double

    cycling = CDbl(txtCycle.Text)

    running = CDbl(txtRun.Text)

    swimming = CDbl(txtSwim.Text)

    pounds = (200 * cycling + 475 * running + 275 * swimming) / 3500

    pounds = Math.Round(pounds, 1)

    txtWtLoss.Text = pounds & " pounds were lost."

    End Sub

    43. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim revenue, expenses, income As Double

    revenue = CDbl(txtRevenue.Text)

    expenses = CDbl(txtExpenses.Text)

    income = revenue - expenses

    txtNetIncome.Text = CStr(income)

    End Sub

  • Student Solutions Manual (Page 23 of 211)

    45. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim amount, percentage, tip As Double

    amount = CDbl(txtAmount.Text)

    percentage = CDbl(txtPercentage.Text)

    tip = amount * (percentage / 100)

    txtTip.Text = CStr(Math.Round(tip, 2))

    End Sub

    47. Dim number As Integer = 100 'in Declarations section

    'Note: the Text property of txtOutput was set to 100 at design time

    Private Sub btnPressMe_Click(...) Handles btnPressMe.Click

    number = number - 1 'decrease number by 1

    txtOutput.Text = CStr(number)

    End Sub

  • Student Solutions Manual (Page 24 of 211)

    49. Private Sub btnModifySentence_Click(...) Handles btnModifySentence.Click

    Dim sentence, oldWord, newWord As String

    Dim position As Integer

    sentence = txtSentence.Text

    oldWord = txtOriginalWord.Text

    newWord = txtReplacementWord.Text

    position = sentence.IndexOf(oldWord)

    txtOutput.Text = sentence.Substring(0, position) & newWord &

    sentence.Substring(position + oldWord.Length)

    End Sub

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

    Dim speed, distance As Double

    distance = CDbl(txtDistanceSkidded.Text)

    speed = Math.Sqrt(24 * distance)

    speed = Math.Round(speed, 2)

    txtEstimatedSpeed.Text = speed & " mph"

    End Sub

  • Student Solutions Manual (Page 25 of 211)

    53. Dim sum As Double 'sum of the scores entered

    Dim num As Integer 'number of scores entered

    Private Sub btnRecord_Click(...) Handles btnRecord.Click

    num += 1

    sum += CDbl(txtScore.Text)

    txtScore.Clear()

    txtScore.Focus()

    End Sub

    Private Sub btnCalculate_Click(...) Handles btnCalculate.Click

    txtAverage.Text = CStr(sum / num)

    End Sub

    55. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim num1, num2, sum As Double

    num1 = CDbl(txtFirstNum.Text)

    num2 = CDbl(txtSecondNum.Text)

    sum = num1 + num2

    txtSum.Text = CStr(sum)

    End Sub

    Private Sub txtEitherNum_TextChanged(...) Handles _

    txtFirstNum.TextChanged, txtSecondNum.TextChanged

    txtSum.Clear()

    End Sub

  • Student Solutions Manual (Page 26 of 211)

    EXERCISES 3.3

    1. 1,235 3. 1,234.0 5. 0.0 7. -0.67 9. 12,346.000 11. 12

    13. $12,346 15. ($0.23) 17. $0.80 19. 7.50% 21. 100.00%

    23. 66.67% 25. Pay to France $27,267,622.00

    27. 25.6% of the U.S. population 25+ years old are college graduates.

    29. The likelihood of Heads is 50% 31. 10/23/2010

    33. Thursday, November 25, 2010 35. 10/2/2011 37. 4/5/2013 39. 29

    41. You might win 360 dollars. 43. Hello John Jones 45. $106.00

    47. Prints the words Hello World using a 10-point bold Courier New font in blue letters 2

    inches from the left side of the page and 2 inches from the top of the page.

    49. The statement n += 1 is not valid since the value of a named constant cannot be

    changed.

    51. The second line should use CDbl to convert the right-hand side to type Double.

    53. FormatNumber(123456) is a string and therefore cannot be assigned to a numeric

    variable.

    55. You must insert .Show, after the word MessageBox.

    57. 000 59. LLL000 61. 0-00-000000-&

    63. MessageBox.Show("First solve the problem. Then write the code.",

    "Good Advice")

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

    Dim begOfYearCost, endOfYearCost As Double

    Dim percentIncrease As Double

    begOfYearCost = 200

    endOfYearCost = CDbl(InputBox("Enter cost at the end of the year:"))

    percentIncrease = (endOfYearCost - begOfYearCost) / begOfYearCost

    txtOutput.Text = "The increase in cost for the year is " &

    FormatPercent(percentIncrease) & "."

    End Sub

  • Student Solutions Manual (Page 27 of 211)

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

    Dim firstDayOfYr, firstDayOfNextYr As Date

    Dim numDays As Double

    firstDayOfYr = CDate("1/1/" & mtbYear.Text)

    firstDayOfNextYr = firstDayOfYr.AddYears(1)

    numDays = DateDiff(DateInterval.Day, firstDayOfYr, firstDayOfNextYr)

    txtNumDays.Text = CStr(numDays)

    End Sub

    69. Private Sub Determine_Click(...) Handles btnDetermine.Click

    Dim dt As Date = CDate(mtbDate.Text)

    Dim fullDate As String = FormatDateTime(dt, DateFormat.LongDate)

    Dim position As Integer = fullDate.IndexOf(",")

    Dim dayOfWeek As String = fullDate.Substring(0, position)

    txtDayOfWeek.Text = dayOfWeek

    End Sub

    71. Private Sub Determine_Click(...) Handles btnDetermine.Click

    Dim month, yr As Integer 'month given as 1 through 12

    Dim dt, dt2 As Date

    Dim numDays As Double

    month = CInt(txtMonth.Text)

    yr = CInt(mtbYear.Text)

    dt = CDate(month & "/1/" & yr)

    dt2 = dt.AddMonths(1)

    numDays = DateDiff(DateInterval.Day, dt, dt2)

    txtNumDays.Text = CStr(numDays)

    End Sub

  • Student Solutions Manual (Page 28 of 211)

    73. Private Sub txtPhoneNumber_Enter(...) Handles txtPhoneNumber.Enter

    MessageBox.Show("Be sure to include the area code!", "Reminder")

    End Sub

    75. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim principal, intRate, yrs, amt As Double

    lstOutput.Items.Clear()

    principal = CDbl(txtPrincipal.Text)

    intRate = CDbl(txtIntRate.Text)

    yrs = 10

    amt = principal * (1 + intRate) ^ yrs

    lstOutput.Items.Add("When " & FormatCurrency(principal) & " is")

    lstOutput.Items.Add("invested at " & FormatPercent(intRate))

    lstOutput.Items.Add("for " & yrs & " years, the ")

    lstOutput.Items.Add("balance is " & FormatCurrency(amt) & ".")

    End Sub

  • Student Solutions Manual (Page 29 of 211)

    77. Const ONE_INCH As Integer = 100 'number of pixels in an inch

    Const LINE_HEIGHT As Integer = 20 'one-quarter of an inch

    Private Sub btnPrint_Click(...) Handles btnPrint.Click

    PrintDocument1.Print()

    End Sub

    Private Sub PrintDocument1_PrintPage(...) Handles PrintDocument1.PrintPage

    Dim gr As Graphics = e.Graphics

    Dim x1 As Integer = ONE_INCH 'use one inch beyond left margin

    Dim x2 As Integer = CInt(1.5 * ONE_INCH) 'offset for second column

    Dim x3 As Integer = CInt(2.25 * ONE_INCH) 'offset for third column

    Dim y As Integer = ONE_INCH 'use one inch top margin

    Dim font1 As New Font("Courier New", 10, FontStyle.Underline)

    Dim font2 As New Font("Courier New", 10, FontStyle.Regular)

    gr.DrawString("% of", font2, Brushes.Black, x3, y)

    y += LINE_HEIGHT

    gr.DrawString("Rank", font1, Brushes.Black, x1, y)

    gr.DrawString("Country", font1, Brushes.Black, x2, y)

    gr.DrawString("WW Users", font1, Brushes.Black, x3, y)

    y += LINE_HEIGHT

    gr.DrawString("1", font2, Brushes.Black, x1, y)

    gr.DrawString("USA", font2, Brushes.Black, x2, y)

    gr.DrawString(FormatPercent(0.16, 1), font2, Brushes.Black, x3, y)

    y += LINE_HEIGHT

    gr.DrawString("2", font2, Brushes.Black, x1, y)

    gr.DrawString("China", font2, Brushes.Black, x2, y)

    gr.DrawString(FormatPercent(0.119, 1), font2, Brushes.Black, x3, y)

    y += LINE_HEIGHT

    gr.DrawString("3", font2, Brushes.Black, x1, y)

    gr.DrawString("Japan", font2, Brushes.Black, x2, y)

    gr.DrawString(FormatPercent(0.065, 1), font2, Brushes.Black, x3, y)

    End Sub

    Private Sub btnPreview_Click(...) Handles btnPreview.Click

    PrintPreviewDialog1.Document = PrintDocument1

    PrintPreviewDialog1.ShowDialog()

    End Sub

  • Student Solutions Manual (Page 30 of 211)

    CHAPTER 4

    EXERCISES 4.1

    1. hi 3. The letter before G is F

    5. "We're all in this alone." - Lily Tomlin

    7. True 9. True 11. True 13. True 15. False 17. False 19. True 21. True

    23. False 25. False 27. False 29. True 31. Equivalent 33. Not Equivalent

    35. Equivalent 37. Not Equivalent 39. Equivalent 41. a = b) Or (c = d) 45. (a = "") Or (a >= b) Or (a.Length >= 5)

    [In Exercises 46 through 49, execute a statement of the form txtOutput.Text = Boolean

    expression.]

    47. True 49. False 51. False 53. True 55. True 57. False 59. True

  • Student Solutions Manual (Page 31 of 211)

    EXERCISES 4.2

    1. Less than ten. 3. tomorrow is another day. 5. 10

    7. To be, or not to be. 9. Hi 11. You are old enough to vote in 7 days.

    13. Syntax error. Third line should be If ((1 < num) And (num < 3)) Then

    15. Syntax error. Fourth line should be If ((major = "Business") Or (major = "Computer Science")) Then

    17. a = 5

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

    answer = InputBox(message)

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

    txtOutput.Text = "Correct"

    Else

    txtOutput.Text = "Wrong"

    End If

    21. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim cost, tip As Double

    cost = CDbl(InputBox("Enter cost of meal:"))

    tip = cost * 0.15

    If tip < 1 Then

    tip = 1

    End If

    txtOutput.Text = "Leave " & FormatCurrency(tip) & " for the tip."

    End Sub

    23. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim num, cost As Double

    num = CDbl(InputBox("Number of widgets:"))

    If num < 100 Then

    cost = 0.25 * num '25 cents each

    Else

    cost = 0.2 * num '20 cents each

    End If

    txtOutput.Text = "The cost is " & FormatCurrency(cost) & "."

    End Sub

  • Student Solutions Manual (Page 32 of 211)

    25. Private Sub btnAskQuestion_Click(...) Handles btnAskQuestion.Click

    Dim name As String

    name = (InputBox("Who was the first Ronald McDonald?")).ToUpper

    If name = "WILLARD SCOTT" Then

    txtOutput.Text = "Correct."

    Else

    txtOutput.Text = "Nice try."

    End If

    End Sub

    27. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim s1, s2, s3 As Double '3 scores

    Dim avg As Double 'average of the two highest scores

    s1 = CDbl(InputBox("Enter the first of the three scores."))

    s2 = CDbl(InputBox("Enter the second of the three scores."))

    s3 = CDbl(InputBox("Enter the third of the three scores."))

    If (s1

  • Student Solutions Manual (Page 33 of 211)

    29. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim weight, cost, amount, change As Double

    weight = CDbl(txtWeight.Text)

    amount = CDbl(txtAmount.Text)

    cost = weight * 1.7

    If (amount >= cost) Then

    change = amount - cost

    txtOutput.Text = "Your change is " & FormatCurrency(change) & "."

    Else

    txtOutput.Text = "I need " & FormatCurrency(cost - amount) & " more."

    End If

    End Sub

    31. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim wage, hours, grossPay As Double

    wage = CDbl(txtHourlyWage.Text) 'Hourly pay

    hours = CDbl(txtHoursWorked.Text) 'Hours worked

    If hours

  • Student Solutions Manual (Page 34 of 211)

    33. Dim numLines As Integer = 0 'In Declarations section of Code Editor

    'numLines tells the number of lines that have been displayed.

    Private Sub btnBogart_Click(...) Handles btnBogart.Click

    If numLines = 0 Then

    lstOutput.Items.Add("I came to Casablanca for the waters.")

    numLines += 1

    ElseIf numLines = 2 Then

    lstOutput.Items.Add("I was misinformed.")

    numLines += 1

    End If

    End Sub

    Private Sub btnRaines_Click(...) Handles btnRaines.Click

    If numLines = 1 Then

    lstOutput.Items.Add("But we're in the middle of the desert.")

    numLines += 1

    End If

    End Sub

  • Student Solutions Manual (Page 35 of 211)

    35. Dim numGuesses As Integer = 0

    Private Sub btnEvaluate_Click(...) Handles btnEvaluate.Click

    'Assume that the Text property of txtNumberOfGuesses

    'was set to 0 in the Form Designer

    numGuesses += 1

    txtNumberOfGuesses.Text = CStr(numGuesses)

    Dim msg As String

    If txtAnswer.Text.ToUpper.IndexOf("COOLIDGE") -1 Then

    MessageBox.Show("Calvin Coolidge was born on July 4, 1872.",

    "Correct")

    Me.Close()

    ElseIf CInt(numGuesses) = 10 Then

    msg = "Calvin Coolidge was born on July 4, 1872."

    MessageBox.Show(msg, "You've Run Out of Guesses")

    Me.Close()

    Else

    If CInt(numGuesses) = 3 Then

    msg = "He once said, 'If you don't say anything," &

    " you won't be called upon to repeat it.'"

    ElseIf CInt(numGuesses) = 7 Then

    msg = "His nickname was 'Silent Cal.'"

    Else

    msg = "Sorry!"

    End If

    MessageBox.Show(msg, "Incorrect")

    End If

    txtAnswer.Clear()

    txtAnswer.Focus()

    End Sub

    4.2 Exercise 35 4.2 Exercise 37

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

    If lblLanguage.Visible Then

    lblLanguage.Visible = False

    btnDisplay.Text = "Show Name of Language"

    Else

    lblLanguage.Visible = True

    btnDisplay.Text = "Hide Name of Language"

    End If

    End Sub

  • Student Solutions Manual (Page 36 of 211)

    39. Private Sub btnCompute_Click(...) Handles lblDetermine.Click

    Dim day As String

    Dim day1, day2 As Date

    Dim numDays As Double

    day = "1/1/" & txtYear.Text

    day1 = CDate(day)

    day2 = day1.AddYears(1)

    numDays = DateDiff(DateInterval.Day, day1, day2)

    If numDays = 366 Then

    txtLeapYear.Text = "YES"

    Else

    txtLeapYear.Text = "NO"

    End If

    End Sub

    41. Private Sub Determine_Click(...) Handles btnDetermine.Click

    Dim dt, dt2 As Date

    Dim approximateAge As Double

    dt = CDate(mtbDate.Text)

    approximateAge = DateDiff(DateInterval.Year, dt, Today)

    dt2 = dt.AddYears(CInt(approximateAge))

    If Today < dt2 Then

    txtAge.Text = CStr(approximateAge - 1)

    Else

    txtAge.Text = CStr(approximateAge)

    End If

    End Sub

  • Student Solutions Manual (Page 37 of 211)

    43. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click

    Dim gpa As Double = CDbl(txtGPA.Text)

    Dim honors As String = ""

    If gpa >= 3.9 Then

    honors = " summa cum laude."

    End If

    If (3.6

  • Student Solutions Manual (Page 38 of 211)

    EXERCISES 4.3 1. The price is $3.75 3. Mesozoic Era

    The price is $3.75 Paleozoic Era

    ?

    5. The equation has no real solutions.

    The equation has two solutions.

    The equation has exactly one solution.

    7. Should have a Case clause before the 4th line.

    9. Case nom = "Bob" should be Case "Bob"

    11. Logic error: >= "Peach" should be >= "PEACH".

    Syntax error: "ORANGE TO PEACH" should be "ORANGE" To "PEACH".

    13. Valid 15. Invalid 17. Valid

    19. Select Case a

    Case 1

    txtOutput.Text = "one"

    Case Is > 5

    txtOutput.Text = "two"

    End Select

    21. Select Case a

    Case 2

    txtOutput.Text = "yes"

    Case Is < 5

    txtOutput.Text = "no"

    End Select

  • Student Solutions Manual (Page 39 of 211)

    23. Private Sub btnDescribe_Click(...) Handles btnDescribe.Click

    Dim percent As Double

    percent = CDbl(InputBox("Percentage of cloud cover:"))

    Select Case percent

    Case 0 To 30

    txtOutput.Text = "Clear"

    Case 31 To 70

    txtOutput.Text = "Partly cloudy"

    Case 71 To 99

    txtOutput.Text = "Cloudy"

    Case 100

    txtOutput.Text = "Overcast"

    Case Else

    txtOutput.Text = "Percentage must be between 0 and 100."

    End Select

    End Sub

    25. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim shapeNum As Integer

    Dim radius, length, height, width As Double

    'Input choice of shape and its dimensions

    '1. Circle 2. Parallelogram 3. Kite

    shapeNum = CInt(mtbSelection.Text) 'Mask is 0

    Select Case shapeNum

    Case 1

    radius = CDbl(InputBox("Input the radius of the circle: "))

    txtArea.Text = CStr(3.141593 * radius ^ 2)

    Case 2

    length = CDbl(InputBox("Input the length of the parallelogram: "))

    height = CDbl(InputBox("Input the height of the parallelogram: "))

    txtArea.Text = CStr(length * height)

    Case 3

    length = CDbl(InputBox("Input the length of the kite: "))

    width = CDbl(InputBox("Input the width of the kite: "))

    txtArea.Text = CStr((length * width) / 2)

    Case Else

    MessageBox.Show("Your choice is not valid.", "Try Again.")

    mtbSelection.Clear()

    End Select

    mtbSelection.Focus()

    End Sub

  • Student Solutions Manual (Page 40 of 211)

    27. Private Sub btnAssign_Click(...) Handles btnAssign.Click

    Dim score As Integer, letterGrade As String

    score = CInt(InputBox("What is the score?"))

    Select Case score

    Case 90 To 100

    letterGrade = "A"

    Case 80 To 89

    letterGrade = "B"

    Case 70 To 79

    letterGrade = "C"

    Case 60 To 69

    letterGrade = "D"

    Case 0 To 59

    letterGrade = "F"

    Case Else

    letterGrade = "Invalid"

    End Select

    txtOutput.Text = "The letter grade is " & letterGrade & "."

    End Sub

    29. Private Sub btnDescribe_Click(...) Handles btnDetermine.Click

    Dim amountRecovered, payment As Double

    amountRecovered = CDbl(InputBox("How much was recovered?"))

    Select Case amountRecovered

    Case Is 50000 Then

    payment = 50000

    End If

    End Select

    txtOutput.Text = "The amount given as reward is " &

    FormatCurrency(payment) & "."

    End Sub

  • Student Solutions Manual (Page 41 of 211)

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

    Dim pres, state, trivia, whichBush As String

    pres = txtLastName.Text

    Select Case pres.ToUpper

    Case "CARTER"

    state = "Georgia"

    trivia = "The only soft drink served in the Carter " &

    "White House was Coca-Cola."

    Case "REAGAN"

    state = "California"

    trivia = "His secret service code name was Rawhide."

    Case "BUSH"

    state = "Texas"

    whichBush = InputBox("Are his middle initials HW or W?")

    Select Case whichBush.ToUpper

    Case "HW"

    trivia = "He celebrated his 85th birthday by parachuting " &

    "out of an airplane."

    Case "W"

    trivia = "He once owned the Texas Rangers baseball team."

    End Select

    Case "CLINTON"

    state = "Arkansas"

    trivia = "In college he did a good imitation of Elvis Presley."

    Case "OBAMA"

    state = "Illinois"

    trivia = "He was the eighth left-handed president."

    Case Else

    state = ""

    trivia = ""

    End Select

    If state "" Then

    lstOutput.Items.Clear()

    lstOutput.Items.Add("President " & pres & "'s" &

    " home state was " & state & ".")

    lstOutput.Items.Add(trivia)

    End If

    End Sub

  • Student Solutions Manual (Page 42 of 211)

    EXERCISES 4.4

    1. The word "Income" becomes the caption embedded in the top of GroupBox1.

    3. The CheckBox1 check box becomes (or remains) unchecked.

    5. The radio button becomes (or remains) unselected.

    7. The radio buttons caption becomes "Clear All".

    9. RadioButton1.Text = "Yes" 11. CheckBox1.Checked = True

    13. RadioButton2 is on and RadioButton1 is off. 15. Yes

    17. Private Sub CheckedChanged(...) Handles _

    radDeluxe.CheckedChanged, radSuper.CheckedChanged,

    chkUpgradedVideo.CheckedChanged, chkModem.CheckedChanged,

    chkMemory.CheckedChanged

    If radDeluxe.Checked Or radSuper.Checked Then

    Dim cost As Double = 0

    'Add amounts to the cost based upon selections.

    If radDeluxe.Checked Then

    cost += 1000

    Else 'Super model

    cost += 1500

    End If

    If chkUpgradedVideo.Checked Then

    cost += 200

    End If

    If chkModem.Checked Then

    cost += 30

    End If

    If chkMemory.Checked Then

    cost += 120

    End If

    txtTotalCost.Text = FormatCurrency(cost)

    Else

    MessageBox.Show("You must first select a model!")

    End If

    End Sub

  • Student Solutions Manual (Page 43 of 211)

    19. Private Sub btnVote_Click(...) Handles btnVote.Click

    If radCandidate1.Checked Then

    txtVote.Text = "You voted for Kennedy."

    ElseIf radCandidate2.Checked Then

    txtVote.Text = "You voted for Nixon."

    Else

    txtVote.Text = "You voted for neither."

    End If

    End Sub

    Private Sub btnClear_Click(...) Handles btnClear.Click

    radCandidate1.Checked = False

    radCandidate2.Checked = False

    End Sub

  • Student Solutions Manual (Page 44 of 211)

    21. Private Sub btnRecord_Click(...) Handles btnRecord.Click

    Dim majorSelected As Boolean

    Dim yearSelected As Boolean

    If lstMajors.Text = "" Then

    majorSelected = False

    Else

    majorSelected = True

    End If

    If (radFrosh.Checked Or radSoph.Checked Or radJunior.Checked Or

    radSenior.Checked) Then

    yearSelected = True

    Else

    yearSelected = False

    End If

    If majorSelected And yearSelected Then

    MessageBox.Show("Information Processed")

    ElseIf Not majorSelected Then

    If Not yearSelected Then

    MessageBox.Show("You must select a Major and a Year.")

    Else

    MessageBox.Show("You must select a Major.")

    End If

    Else

    MessageBox.Show("You must select a Year.")

    End If

    End Sub

  • Student Solutions Manual (Page 45 of 211)

    23. Private Sub CheckedChanged(...) Handles _

    chkSenior.CheckedChanged, chkBlind.CheckedChanged,

    chkSpouse.CheckedChanged, chkSpouseBlind.CheckedChanged

    Dim count As Integer = 0

    If chkSenior.Checked Then

    count += 1

    End If

    If chkBlind.Checked Then

    count += 1

    End If

    If chkSpouse.Checked Then

    count += 1

    End If

    If chkSpouseBlind.Checked Then

    count += 1

    End If

    txtOutput.Text = CStr(count)

    End Sub

  • Student Solutions Manual (Page 46 of 211)

    25. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click

    Dim fee As Double = 0

    If radAdult.Checked Or radSenior.Checked Then

    Dim numExtras As Integer = 0

    If chkTennis.Checked Then

    numExtras += 1

    End If

    If chkLocker.Checked Then

    numExtras += 1

    End If

    If chkLaundry.Checked Then

    numExtras += 1

    End If

    If radAdult.Checked Then

    fee = 100 + numExtras * 25

    Else

    fee = 75 + numExtras * 25

    End If

    txtFee.Text = FormatCurrency(fee)

    Else

    MessageBox.Show("You must select a membership category.")

    End If

    End Sub

  • Student Solutions Manual (Page 47 of 211)

    CHAPTER 5

    EXERCISES 5.1

    1. 203 3. The population will double in 24 years.

    5. 27 is an odd number. 7. Your state income tax is $150.00.

    9. age before beauty

    11. The function header should end with "As String", not "As Integer".

    13. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click

    Dim radius, height As Double

    lstOutput.Items.Clear()

    radius = CDbl(InputBox("Enter radius of can (in centimeters):"))

    height = CDbl(InputBox("Enter height of can (in centimeters):"))

    lstOutput.Items.Add("A can of radius " & radius & " and height " &

    height)

    lstOutput.Items.Add("requires " & TinArea(radius, height) &

    " square centimeters")

    lstOutput.Items.Add("of tin.")

    End Sub

    Function TinArea(ByVal radius As Double, ByVal ht As Double) As Double

    'Calculate surface area of a cylindrical can.

    Return 6.283 * (radius ^ 2 + radius * ht)

    End Function

    15. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click

    Dim weight As Double = CDbl(txtWeight.Text)

    Dim height As Double = CDbl(txtHeight.Text)

    txtBMI.Text = CStr(BMI(weight, height))

    End Sub

    Function BMI(ByVal w As Double, ByVal h As Double) As Double

    Return Math.Round((703 * w) / (h ^ 2))

    End Function

  • Student Solutions Manual (Page 48 of 211)

    17. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click

    Dim popcorn, butter, bucket, price As Double 'amount in dollars

    popcorn = CDbl(InputBox("What is the cost of the popcorn kernels?"))

    butter = CDbl(InputBox("What is the cost of the butter substitute?"))

    bucket = CDbl(InputBox("What is the cost of the bucket?"))

    price = CDbl(InputBox("What is the sale price?"))

    txtProfit.Text = FormatCurrency(Profit(popcorn, butter, bucket, price))

    End Sub

    Function Profit(ByVal popcorn As Double, ByVal butter As Double,

    ByVal bucket As Double, ByVal price As Double) As Double

    'Calculate the profit on a bucket of popcorn

    Return price - (popcorn + butter + bucket)

    End Function

    19. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim weight As Double

    weight = CDbl(txtWeight.Text)

    txtOutput.Text = "The cost of mailing the letter was " &

    FormatCurrency(Cost(weight)) & "."

    End Sub

    Function Ceil(ByVal x As Double) As Double

    Return -Int(-x)

    End Function

    Function Cost(ByVal weight As Double) As Double

    Return 0.05 + 0.1 * Ceil(weight - 1)

    End Function

  • Student Solutions Manual (Page 49 of 211)

    21. Private Sub btnAddressNGreet_Click(...) Handles btnAddressNGreet.Click

    Dim name As String

    name = InputBox("Enter the senator's name:")

    lstOutput.Items.Add("The Honorable " & name)

    lstOutput.Items.Add("United States Senate")

    lstOutput.Items.Add("Washington, DC 20001")

    lstOutput.Items.Add("")

    lstOutput.Items.Add("Dear Senator " & LastName(name) & ",")

    End Sub

    Function LastName(ByVal name As String) As String

    Dim spacePos As Integer

    spacePos = name.IndexOf(" ")

    Return name.Substring(spacePos + 1)

    End Function

    23. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click

    If IsLeapYear(CInt(mtbYear.Text)) Then 'mask is 0000

    txtOutput.Text = mtbYear.Text & " is a leap year."

    Else

    txtOutput.Text = mtbYear.Text & " is not a leap year."

    End If

    End Sub

    Function IsLeapYear(ByVal yr As Integer) As Boolean

    Dim date1 As Date = CDate("#1/1/" & yr & "#")

    Dim date2 As Date = CDate("#1/1/" & (yr + 1) & "#")

    If DateDiff(DateInterval.Day, date1, date2) = 366 Then

    Return True

    Else

    Return False

    End If

    End Function

  • Student Solutions Manual (Page 50 of 211)

    EXERCISES 5.2 1. 88 keys on a piano 3. You look dashing in blue.

    5. 1440 minutes in a day 7. Why do clocks run clockwise?

    Because they were invented in the northern

    hemisphere where sundials go clockwise.

    9. It was the best of times. 11. divorced 13. 24 blackbirds

    It was the worst of times. beheaded baked in

    died a pie.

    divorced

    beheaded

    survived

    15. The first 6 letters are Visual. 17. Cost: $250.00

    Shipping cost: $15.00

    Total cost: $265.00

    19. You passed with a grade of 92.

    21. There is a parameter in the Sub procedure, but no argument in the statement calling the

    Sub procedure.

    23. Since Handles is a keyword, it cannot be used as the name of a Sub procedure.

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

    Dim num As Integer = 7

    Lucky(num)

    End Sub

    Sub Lucky(ByVal num As Integer)

    txtOutput.Text = num & " is a lucky number."

    End Sub

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

    Tallest("redwood", 362)

    Tallest("pine", 223)

    End Sub

    Sub Tallest(ByVal tree As String, ByVal ht As Double)

    lstBox.Items.Add("The tallest " & tree &

    " tree in the U.S. is " & ht & " feet.")

    End Sub

  • Student Solutions Manual (Page 51 of 211)

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

    DisplaySource()

    Majors(16.7, "business")

    Majors(1.0, "computer science")

    End Sub

    Sub DisplaySource()

    Dim phrase As String

    phrase = "According to a 2008 survey of college freshmen" &

    " taken by"

    lstOutput.Items.Add(phrase)

    lstOutput.Items.Add("the Higher Education Research Institute:")

    End Sub

    Sub Majors(ByVal percentOfStudents As Double, ByVal field As String)

    lstOutput.Items.Add(percentOfStudents &

    " percent said they intend to major in " & field & ".")

    End Sub

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

    Dim num As Double

    num = CDbl(txtBox.Text)

    Sum(num)

    Product(num)

    End Sub

    Sub Sum(ByVal num As Double)

    Dim phrase As String

    phrase = "The sum of your favorite number with itself is "

    lstOutput.Items.Add(phrase & (num + num) & ".")

    End Sub

    Sub Product(ByVal num As Double)

    Dim phrase As String

    phrase = "The product of your favorite number with itself is "

    lstOutput.Items.Add(phrase & (num * num) & ".")

    End Sub

  • Student Solutions Manual (Page 52 of 211)

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

    ShowVerse("lamb", "baa")

    ShowVerse("duck", "quack")

    ShowVerse("firefly", "blink")

    End Sub

    Sub ShowVerse(ByVal animal As String, ByVal sound As String)

    'Display a verse from Old McDonald Had a Farm

    lstOutput.Items.Add("Old McDonald had a farm. Eyi eyi oh.")

    lstOutput.Items.Add("And on his farm he had a " & animal &

    ". Eyi eyi oh.")

    lstOutput.Items.Add("With a " & sound & " " & sound & " here, and a " &

    sound & " " & sound & " there.")

    lstOutput.Items.Add("Here a " & sound & ", there a " & sound &

    ", everywhere a " & sound & " " & sound & ".")

    lstOutput.Items.Add("Old McDonald had a farm. Eyi eyi oh.")

    lstOutput.Items.Add("")

    End Sub

  • Student Solutions Manual (Page 53 of 211)

    35. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click

    Dim grade1 As Double = CDbl(txtGrade1.Text)

    Dim grade2 As Double = CDbl(txtGrade2.Text)

    Dim grade3 As Double = CDbl(txtGrade3.Text)

    DisplayHighestTwo(grade1, grade2, grade3)

    End Sub

    Sub DisplayHighestTwo(ByVal grade1 As Double, ByVal grade2 As Double,

    ByVal grade3 As Double)

    Dim first, second As Double

    first = Max(grade1, grade2)

    If first = grade1 Then

    second = Max(grade2, grade3)

    Else

    second = Max(grade1, grade3)

    End If

    txtOutput.Text = "The highest two grades are " & first &

    " and " & second & "."

    End Sub

    Function Max(ByVal num1 As Double, ByVal num2 As Double) As Double

    If num1

  • Student Solutions Manual (Page 54 of 211)

    37. Private Sub btnAlphabetize_Click(...) Handles btnAlphabetize.Click

    Dim word1 = txtWord1.Text

    Dim word2 = txtWord2.Text

    DisplayWords(word1, word2)

    End Sub

    Sub DisplayWords(ByVal word1 As String, ByVal word2 As String)

    Dim first, second As String

    If word1

  • Student Solutions Manual (Page 55 of 211)

    EXERCISES 5.3 1. Gabriel was born in the year 1980. 3. The state flower of Alaska is the Forget Me Not. 5. The first 3 letters of EDUCATION are EDU. 7. Current inventory: 2 is displayed both times the button is clicked. The second click also

    produces the message "Insufficient inventory, purchase cancelled.")

    9. sum = 4

    difference = 2

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

    Dim firstName As String = ""

    Dim lastName As String = ""

    Dim salary, newSalary As Double

    InputData(firstName, lastName, salary)

    newSalary = RaisedSalary(salary)

    DisplayOutput(firstName, lastName, newSalary)

    End Sub Sub InputData(ByRef firstName As String, ByRef lastName As String,

    ByRef salary As Double)

    firstName = txtFirstName.Text

    lastName = txtLastName.Text

    salary = CDbl(txtCurrentSalary.Text)

    End Sub Function RaisedSalary(ByVal salary As Double) As Double

    If salary

  • Student Solutions Manual (Page 56 of 211)

    13. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click

    Dim annualRateOfInterest, monthlyPayment, begBalance As Double

    Dim intForMonth, redOfPrincipal, endBalance As Double

    InputData(annualRateOfInterest, monthlyPayment, begBalance)

    Calculate(annualRateOfInterest, monthlyPayment, begBalance,

    intForMonth, redOfPrincipal, endBalance)

    DisplayData(intForMonth, redOfPrincipal, endBalance)

    End Sub

    Sub InputData(ByRef annualRateOfInterest As Double,

    ByRef monthlyPayment As Double,

    ByRef begBalance As Double)

    annualRateOfInterest = CDbl(txtAnnualRateOfInterest.Text)

    monthlyPayment = CDbl(txtMonthlyPayment.Text)

    begBalance = CDbl(txtBegBalance.Text)

    End Sub

    Sub Calculate(ByVal annualRateOfInterest As Double,

    ByVal monthlyPayment As Double,

    ByVal begBalance As Double, ByRef intForMonth As Double,

    ByRef redOfPrincipal As Double, ByRef endBalance As Double)

    Dim monthlyRateOfInterest As Double = annualRateOfInterest / 12

    intForMonth = (monthlyRateOfInterest / 100) * begBalance

    redOfPrincipal = monthlyPayment - intForMonth

    endBalance = begBalance - redOfPrincipal

    End Sub

    Sub DisplayData(ByVal intForMonth, ByVal redOfPrincipal,

    ByVal endBalance)

    txtIntForMonth.Text = FormatCurrency(intForMonth)

    txtRedOfPrincipal.Text = FormatCurrency(redOfPrincipal)

    txtEndBalance.Text = FormatCurrency(endBalance)

    End Sub

  • Student Solutions Manual (Page 57 of 211)

    CHAPTER 6

    EXERCISES 6.1

    1. 18

    3. 10

    5. Maximum number: 7

    7. Infinite loop. (To end the program, click on the Stop Debugging button on the Toolbar.)

    9. Do and Loop are interchanged 11. While num >= 7 13. Until response "Y"

    15. Until name = ""

    17. Until (a = 3)

    19. While n = 0

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

    'Request and display three names.

    Dim name As String, num As Integer = 0

    Do While num < 3

    name = InputBox("Enter a name:")

    lstOutput.Items.Add(name)

    num +=1 'Add 1 to value of num.

    Loop

    End Sub

  • Student Solutions Manual (Page 58 of 211)

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

    Dim celsius As Double = 10

    lstOutput.Items.Add("Celsius Fahrenheit")

    Do While celsius

  • Student Solutions Manual (Page 59 of 211)

    Sub InputWord(ByRef word As String)

    Dim prompt As String

    prompt = "Enter a word containing the letters 'r' and 'n'."

    word = InputBox(prompt, "Enter Word")

    End Sub

    Sub ShowFirst(ByVal rPlace As Integer, ByVal nPlace As Integer)

    'Tell which letter, r or n, comes first.

    If nPlace > rPlace Then

    txtOutput.Text = "The letter r is first."

    Else

    txtOutput.Text = "The letter n is first."

    End If

    End Sub

    27. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim num, max, min As Double

    Dim count As Double = 0

    Dim prompt As String = "Enter a nonnegative number. " &

    "Enter -1 to terminate entering numbers."

    num = CDbl(InputBox(prompt))

    max = num

    min = num

    Do While num >= 0

    count += 1

    num = CDbl(InputBox(prompt))

    If (num -1) Then

    If num < min Then

    min = num

    End If

    If num > max Then

    max = num

    End If

    End If

    Loop

    If count > 0 Then

    txtRange.Text = CStr(max - min)

    Else

    MessageBox.Show("No numbers were entered.")

    End If

    End Sub

  • Student Solutions Manual (Page 60 of 211)

    29. Private Sub btnFind_Click(...) Handles btnFind.Click

    Dim m, n, t As Integer

    InputIntegers(m, n)

    Do While n 0

    t = n

    n = m Mod n 'Remainder after m is divided by n

    m = t

    Loop

    txtOutput.Text = CStr(m)

    End Sub

    Sub InputIntegers(ByRef m As Integer, ByRef n As Integer)

    m = CInt(txtM.Text)

    n = CInt(txtN.Text)

    End Sub

    31. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim age As Integer = 1

    Do While 1980 + age age ^ 2

    age += 1

    Loop

    txtOutput.Text = age & " years old"

    End Sub

    33. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click

    Dim amount As Double = 100

    Dim yrs As Integer = 0

    Do Until amount < 1

    amount = 0.5 * amount

    yrs += 28

    Loop

    txtOutput.Text = yrs & " years"

    End Sub

    35. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click

    Const INTEREST_PER_MONTH As Double = 0.005

    Dim loanAmount As Double = 15000

    Dim months As Integer = 0

    Dim balance As Double = loanAmount

    Do Until balance < loanAmount / 2

    balance = (1 + INTEREST_PER_MONTH) * balance - 290

    months += 1

    Loop

    txtOutput.Text = months & " months"

    End Sub

  • Student Solutions Manual (Page 61 of 211)

    37. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click

    Dim months As Integer = 0

    Dim balance As Double = 10000

    Do Until balance < 600

    balance = 1.003 * balance - 600

    months += 1

    Loop

    txtOutput.Text = months & " months; " & FormatCurrency(balance)

    End Sub

  • Student Solutions Manual (Page 62 of 211)

    EXERCISES 6.2

    1. Pass #1 3. 2 5. 5

    Pass #2 4 6

    Pass #3 6 7

    Pass #4 8

    Who do we appreciate?

    7. 9. 4

    11. The loop is never executed since 25 is greater than 1 and the step is negative.

    13. The For ... Next loop will not execute since 20 is greater than 0. You must add Step -

    1 to the end of the For statement.

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

    For num As Integer = 1 To 9 Step 2

    lstBox.Items.Add(num)

    Next

    End Sub

    17. Private Sub btndisplay_Click(...) Handles btndisplay.Click

    For i As Integer = 2 To 100 Step 2

    lstOutput.Items.Add(i)

    Next

    End Sub

    19. Private Sub btnFind_Click(...) Handles btnFind.Click

    Dim sum As Double = 0, num as Double = 0

    For i As Integer = 1 To 5

    num = CDbl(InputBox("Enter #" & i))

    sum += num

    Next

    txtAverage.Text = FormatNumber(sum / 5, 2)

    End Sub

  • Student Solutions Manual (Page 63 of 211)

    21. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim sum As Double = 0

    For denominator As Double = 1 To 100

    sum += 1 / denominator

    Next

    txtOutput.Text = FormatNumber(sum, 5)

    End Sub

    23. Private Sub btnCalculate_Click(...) Handles btnCalculate.Click

    Dim value As Double = 20000

    For i As Integer = 1 To 5

    value = 0.85 * value

    lstOutput.Items.Add(i & ": " & FormatCurrency(value))

    Next

    End Sub

    25. Private Sub btnCompute_Click(...) Handles btnCompute.Click

    Dim PERCENT_RAISE As Double = 0.05

    Dim name As String, age As Integer, salary As Double

    Dim earnings As Double = 0

    name = txtName.Text

    age = CInt(txtAge.Text)

    salary = CDbl(txtSalary.Text)

    For i As Integer = age To 64

    earnings += salary

    salary = salary + (PERCENT_RAISE * salary)

    Next

    txtOutput.Text = name & " will earn about " &

    FormatCurrency(earnings, 0) & "."

    End Sub

  • Student Solutions Manual (Page 64 of 211)

    27. Private Sub btnComputeIdealWeights_Click(...) Handles _

    btnComputeIdealWeights.Click

    Dim lower, upper As Integer

    lstWeightTable.Items.Clear()

    InputBounds(lower, upper)

    ShowWeights(lower, upper)

    End Sub

    Function IdealMan(ByVal height As Integer) As Double

    'Compute the ideal weight of a man given his height

    Return 4 * height - 128

    End Function

    Function IdealWoman(ByVal height As Integer) As Double

    'Compute the ideal weight of a woman given her height

    Return 3.5 * height - 108

    End Function

    Sub InputBounds(ByRef lower As Integer, ByRef upper As Integer)

    lower = CInt(InputBox("Enter lower bound on height in inches:"))

    upper = CInt(InputBox("Enter upper bound on height in inches:"))

    End Sub

    Sub ShowWeights(ByVal lower As Integer, ByVal upper As Integer)

    lstWeightTable.Items.Add(" " & "WEIGHT " & " " & "WEIGHT")

    lstWeightTable.Items.Add("HEIGHT" & " " & "WOMEN " & " " & "MEN")

    For height As Integer = lower To upper

    lstWeightTable.Items.Add(height & " " &

    FormatNumber(IdealWoman(height), 1) &

    " " & FormatNumber(IdealMan(height), 1))

    Next

    End Sub

  • Student Solutions Manual (Page 65 of 211)

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

    Dim balance As Double = 0

    Dim yr As Integer = 2010

    For i As Integer = 1 To 120

    balance = (1.0025) * balance + 100

    If i Mod 12 = 0 Then

    lstOutput.Items.Add(yr & " " & FormatCurrency(balance))

    yr += 1

    End If

    Next

    End Sub

    31. Private Sub btnAnalyze_Click(...) Handles btnAnalyze.Click

    Const DECAY_RATE As Double = 0.12

    Dim grams As Double

    grams = 10

    For yearNum As Integer = 1 To 5

    grams = (1 - DECAY_RATE) * grams

    Next

    lstOutput.Items.Add("Beginning with 10 grams of cobalt 60,")

    lstOutput.Items.Add(FormatNumber(grams) &

    " grams remain after 5 years.")

    End Sub

  • Student Solutions Manual (Page 66 of 211)

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

    Dim price, quantity As Double

    lstOutput.Items.Clear()

    quantity = 80 'current crop of soybeans in millions of bushels

    lstOutput.Items.Add("YEAR" & " " & "QUANTITY" & " " & "PRICE")

    For yr As Integer = 2010 To 2020

    price = 20 - 0.1 * quantity

    lstOutput.Items.Add(yr & " " & FormatNumber(quantity) &

    " " & FormatCurrency(price))

    quantity = 5 * price - 10

    Next

    End Sub

    35. Private Sub btnAnalyzeOptions_Click(...) Handles btnAnalyzeOptions.Click

    'Compare salaries

    Dim opt1, opt2 As Double

    opt1 = Option1()

    opt2 = Option2()

    lstOutput.Items.Add("Option 1 = " & FormatCurrency(opt1))

    lstOutput.Items.Add("Option 2 = " & FormatCurrency(opt2))

    If opt1 > opt2 Then

    lstOutput.Items.Add("Option 1 pays better.")

    ElseIf opt1 = opt2

    lstOutput.Items.Add("Options pay the same.

    Else

    lstOutput.Items.Add("Option 2 pays better.")

    End If

    End Sub

    Function Option1() As Double

    'Compute the total salary for 10 days,

    'with a flat salary of $100/day

    Dim sum As Integer = 0

    For i As Integer = 1 To 10

    sum += 100

    Next

    Return sum

    End Function

  • Student Solutions Manual (Page 67 of 211)

    Function Option2() As Double

    'Compute the total salary for 10 days,

    'starting at $1 and doubling each day

    Dim sum As Integer = 0, daySalary As Integer = 1

    For i As Integer = 1 To 10

    sum += daySalary

    daySalary = 2 * daySalary

    Next

    Return sum

    End Function

    37. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click

    Dim dt As Date = CDate("#1/1/" & mtbYear.Text & "#")

    Dim d As Date

    For i As Integer = 0 To 11

    d = dt.AddMonths(i)

    lstOutput.Items.Add(FirstTuesday(d))

    Next

    End Sub

    Function FirstTuesday(ByVal d As Date) As Date

    For i As Integer = 0 To 6

    If FormatDateTime(d.AddDays(i),

    DateFormat.LongDate).StartsWith("Tuesday") Then

    Return d.AddDays(i)

    End If

    Next

    End Function

  • Student Solutions Manual (Page 68 of 211)

    EXERCISES 6.3

    1. Mozart 3. Tchaikovsky 5. 3 7. 80 9. 70 11. 300

    13. Private Sub btnCount_Click(...) Handles btnCount.Click

    Dim numWon As Integer = 0

    For i As Integer = 0 To lstBox.Items.Count - 1

    If CStr(lstBox.Items(i)) = "USC" Then

    numWon += 1

    End If

    Next

    txtOutput.Text = CStr(numWon)

    End Sub

    15. Private Sub btnCount_Click(...) Handles btnDetermine.Click

    Dim college As String = txtCollege.Text

    txtOutput.Clear()

    For i As Integer = 0 To lstBox.Items.Count - 1

    If CStr(lstBox.Items(i)) = college Then

    txtOutput.Text = "YES"

    Exit For

    End If

    Next

    If txtOutput.Text = "" Then

    txtOutput.Text = "NO"

    End If

    End Sub

    or

  • Student Solutions Manual (Page 69 of 211)

    Private Sub btnCount_Click(...) Handles btnDetermine.Click

    Dim college As String = txtCollege.Text

    Dim i As Integer = 0

    Dim found As Boolean = False

    Do Until (found = True) Or (i = lstBox.Items.Count)

    If CStr(lstBox.Items(i)) = college Then

    found = True

    End If

    i += 1

    Loop

    If found Then

    txtOutput.Text = "YES"

    Else

    txtOutput.Text = "NO"

    End If

    End Sub

    17. Private Sub btnReverse_Click(...) Handles btnReverse.Click

    Dim highestIndex As Integer = lstBox.Items.Count - 1

    For i As Integer = highestIndex To 0 Step -1

    lstBox2.Items.Add(lstBox.Items(i))

    Next

    End Sub

  • Student Solutions Manual (Page 70 of 211)

    19. Private Sub btnAlphabetize_Click(...) Handles btnAlphabetize.Click

    lstBox2.Sorted = True

    Dim highestIndex As Integer = lstBox.Items.Count - 1

    For i As Integer = 0 To highestIndex

    lstBox2.Items.Add(lstBox.Items(i))

    Next

    End Sub

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

    Dim highestIndex As Integer = lstBox.Items.Count - 1

    Dim state As String

    For i As Integer = 0 To highestIndex

    state = CStr(lstBox.Items(i))

    If state.Length = 7 Then

    lstBox2.Items.Add(state)

    End If

    Next

    End Sub

  • Student Solutions Manual (Page 71 of 211)

    23. Private Sub btnDetermine_Click(...) Handles btnDetermine.Click

    Dim highestIndex As Integer = lstBox.Items.Count - 1

    Dim state As String

    For i As Integer = 0 To highestIndex

    state = CStr(lstBox.Items(i))

    If state.StartsWith("New") Then

    txtOutput.Text = state

    Exit For

    End If

    Next

    End Sub

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

    Dim highestIndex As Integer = lstBox.Items.Count - 1

    Dim maxLength As Integer = 0

    Dim state As String

    For i As Integer = 0 To highestIndex

    state = CStr(lstBox.Items(i))

    If state.Length > maxLength Then