Test Bank for Programming With Microsoft Visual Basic 2019-2022, 9th Edition by Diane Zak (1)

Page 1


Name:

Class:

Date:

Chapter 01 9e Indicate whether the statement is true or false. 1. A class definition is a block of code that specifies or defines an object’s appearance and behavior. a. True b. False ANSWER: True 2. The Project Designer window allows you to verify the form that will display when the application starts. a. True b. False ANSWER: True 3. A source file with a .vb file name extension contains a list of projects in a solution. a. True b. False ANSWER: False 4. The Auto Hide button is located on the window’s status bar. a. True b. False ANSWER: False 5. If you change your default environment settings after configuring Visual Studio, you will need to perform the configuration steps again. a. True b. False ANSWER: True 6. Each namespace contains the code that defines a group of related classes. a. True b. False ANSWER: True 7. Actions performed by the user such as clicking, double-clicking, and scrolling are known as events. a. True b. False ANSWER: True

Page 1


Name:

Class:

Date:

Chapter 01 9e 8. The Auto Hide button allows you to hide windows that you are not currently using. a. True b. False ANSWER: True 9. The Properties window lists the names of the files included in the application you are creating. a. True b. False ANSWER: False 10. An object created from a class is called an instance of the class and is said to be instantiated from the class. a. True b. False ANSWER: True Indicate the answer choice that best completes the statement or answers the question. 11. To verify that a solution has been closed, you can look in the __________ window. a. Toolbox b. Server Explorer c. Start Page d. Solution Explorer ANSWER: d Case-Based Critical Thinking Questions Case 1 You have been hired to develop an application for Ridgeline Realty, a local real estate agency. The owner wants the application to display an image of the company logo and to say “Ridgeline Realty” in the title bar. You will use the most common properties of a picture box to complete the project. 12. To make sure the title bar displays the text that Ridgeline Realty has requested, enter it into the form’s __________ property. a. TitleBar b. Name c. Text d. Title ANSWER: c

Page 2


Name:

Class:

Date:

Chapter 01 9e 13. When an object is selected, the __________ that appears in the Object box indicates a hierarchy of namespaces, and it allows the computer to locate the object’s class in a computer’s main memory. a. colon b. backslash c. dot member access operator d. apostrophe ANSWER: c 14. Which term is used for the general shape of the characters the text displayed on a form? a. property b. splash c. format d. font ANSWER: d 15. Which statement is true? a. A button’s Text property determines the text that appears on the button’s face. b. By default, the size of a form cannot be changed by a user while an application is running. c. The title bar cannot be removed from a form. d. The Minimize button can be removed from the title bar without removing the Maximize button from the title bar. ANSWER: a Case-Based Critical Thinking Questions Case 1 You have been hired to develop an application for Ridgeline Realty, a local real estate agency. The owner wants the application to display an image of the company logo and to say “Ridgeline Realty” in the title bar. You will use the most common properties of a picture box to complete the project. 16. To create the Windows application for Ridgeline, you will first need to __________. a. auto-hide any windows you do not need to use b. set the StartPosition property for the form c. create a new project and determine the directory for the application d. code the Exit button ANSWER: c

Page 3


Name:

Class:

Date:

Chapter 01 9e 17. You use a(n) __________ box to display an image on a form. a. picture b. form c. text d. object ANSWER: a 18. To keep you from inadvertently moving controls as you work in the IDE, click the form or control, then click the __________ option in the Format menu. a. Protect b. Freeze Controls c. Lock Controls d. Hold ANSWER: c 19. When an application is started, Visual Basic will automatically create a file that has the project name and a(n) __________ file extension. a. .dll b. .exe c. .sln d. .suo ANSWER: b Case-Based Critical Thinking Questions Case 1 You have been hired to develop an application for Ridgeline Realty, a local real estate agency. The owner wants the application to display an image of the company logo and to say “Ridgeline Realty” in the title bar. You will use the most common properties of a picture box to complete the project. 20. Which property is used to specify how the image in a picture box is displayed? a. Image b. Name c. SizeMode d. Visible ANSWER: c

Page 4


Name:

Class:

Date:

Chapter 01 9e 21. A form’s __________ property specifies the text that appears in the form’s title bar. a. Caption b. Label c. Text d. Title ANSWER: c 22. What does the Solution Explorer window display? a. a list of the projects contained in the current solution b. data connections and servers c. items that you can use when creating a project d. objects and properties included in a solution ANSWER: a 23. The Toolbox window displays __________. a. names of projects and files included in a solution b. data connections and servers c. tools you use when creating your application’s interface d. properties of objects ANSWER: c 24. A(n) __________ is a block of code that performs a specific task. a. event b. form c. class d. sub procedure ANSWER: d 25. Which term is used for a container that stores the projects and files for an entire application? a. window b. solution c. interface d. package ANSWER: b

Page 5


Name:

Class:

Date:

Chapter 01 9e 26. To start an application using the menu bar, you click __________ on the menu bar and then click Start Debugging. a. Debug b. Project c. View d. Build ANSWER: a 27. You tell an object how to respond to an event by writing an event __________, which is a set of Visual Basic instructions that are processed only when the event occurs. a. incident b. procedure c. object d. action ANSWER: b 28. The position of the form on the screen when an application first starts is controlled by setting the __________ property. a. Position b. Size c. Location d. StartPosition ANSWER: d 29. Each object has a set of attributes, called __________, that determine the object’s appearance and behavior. a. codes b. events c. global settings d. properties ANSWER: d 30. In Windows applications, a(n) __________ is commonly used to perform an immediate action when clicked. a. object b. menu c. form d. button ANSWER: d

Page 6


Name:

Class:

Date:

Chapter 01 9e 31. When you want the application to end when the user clicks the Exit button, you write the Me.Close() statement in the __________ event procedure. a. Exit button’s End b. Exit button’s Click c. form’s Stop d. form’s Exit ANSWER: b Case-Based Critical Thinking Questions Case 1 You have been hired to develop an application for Ridgeline Realty, a local real estate agency. The owner wants the application to display an image of the company logo and to say “Ridgeline Realty” in the title bar. You will use the most common properties of a picture box to complete the project. 32. To add the image of the company logo, you must first add a __________ control in which to display it. a. picture b. logo c. graphic d. picture box ANSWER: d 33. Which character on the designer window’s tab indicates that a change was made to the form since the last time it was saved? a. -b. @ c. * d. ^ ANSWER: c 34. When you click the ellipsis (...) button in the Settings box of the Font property, a(n) __________. a. list of font styles appears b. color palette appears c. dialog box opens d. attribute is removed ANSWER: c

Page 7


Name:

Class:

Date:

Chapter 01 9e 35. Which window allows you to create a graphical user interface? a. Properties b. solution designer c. designer d. Form Explorer ANSWER: c 36. Based on the naming convention used in the book, which is an example of an appropriate name for a control? a. BtnMessage b. btnExit c. labelmessage d. housepicturebox ANSWER: b 37. You enter a procedure’s code in the __________ window. a. Code Editor b. Server c. Solution d. designer ANSWER: a Case-Based Critical Thinking Questions Case 1 You have been hired to develop an application for Ridgeline Realty, a local real estate agency. The owner wants the application to display an image of the company logo and to say “Ridgeline Realty” in the title bar. You will use the most common properties of a picture box to complete the project. 38. According to the naming convention used in the book, an example of a valid value for the form’s Name property is __________. a. form Ridgeline b. formridgeline c. Ridgeline d. frmRidgeline ANSWER: d

Page 8


Name:

Class:

Date:

Chapter 01 9e 39. A(n) __________ is a predefined procedure that you can call (or invoke) when needed. a. method b. object c. class d. event ANSWER: a 40. To align two or more selected controls along their left, right, top, or bottom borders, you would use the __________ menu. a. Edit b. Format c. Align d. View ANSWER: b 41. Which function key will start an application? a. F2 b. F1 c. F4 d. F5 ANSWER: d 42. What term is used for instructions that are processed (executed) by the computer? a. events b. application c. statements d. instance ANSWER: c 43. All objects in an object-oriented program are instantiated (created) from a(n) __________. a. object b. method c. class d. source ANSWER: c

Page 9


Name:

Class:

Date:

Chapter 01 9e 44. A solution file will have a(n) __________ file extension. a. .sol b. .app c. .vbs d. .sln ANSWER: d 45. A graphical user __________ is what the user sees and interacts with while an application is running. a. service b. profile c. splash d. interface ANSWER: d 46. Explain why and how the auto-hide feature is used when managing windows in the IDE. ANSWER: Answers may vary. In most cases, you will find it easier to work in the IDE if you either close or auto-hide the windows you are not currently using. You close an open window by clicking the Close button on its title bar. You will find the options for opening a closed window on the View menu. You auto-hide a window by using its Auto Hide button, which is located on the window’s title bar. The Auto Hide button is a toggle button: Clicking it once activates it, and clicking it again deactivates it.

47. Explain when and why controls should be locked on a form. ANSWER: Answers may vary. After placing all of the controls in their appropriate locations, you should lock them on the form, which prevents them from being moved inadvertently as you work in the IDE. You can lock the controls by clicking the form (or any control on the form) and then clicking the Lock Controls option on the Format menu; you can follow the same procedure to unlock the controls. You can also lock and unlock the controls by right-clicking the form (or any control on the form) and then clicking Lock Controls on the context menu. When a control is locked, a small lock appears in the upper-left corner of the control.

Page 10


Name:

Class:

Date:

Chapter 01 9e 48. Explain why and how an application’s code or interface may be printed. ANSWER: Answers may vary. It is a good idea to print a copy of your application’s code for future reference. To print the code, the Code Editor window must be the active (current) window. You might also want to print a copy of the user interface; you can do this using either the Windows Snipping Tool or the Windows Snip & Sketch app, as long as the designer window is the active window.

49. What are the two methods of exiting Visual Studio? ANSWER: You can exit Visual Studio using either the Close button on its title bar or the Exit option on its File menu.

Essay 50. Briefly describe the job of a programmer and how a programmer is employed. ANSWER: Answers may vary. When a company has a problem that requires a computer solution, typically a programmer comes to the rescue. The programmer might be an employee of the company or a freelance programmer who works on temporary contracts. First, the programmer meets with the person (or people) responsible for describing the problem. This person might be the one who will eventually use the solution; or they might be a software developer, who serves as an intermediary between the user and the programmer. The software developer will meet with the user and then outline the problem specification for the programmer. After the problem is fully understood, the programmer will begin planning an appropriate solution. When the planning is complete, the programmer will translate the solution into computer instructions—a process called coding. The programmer then will test the program rigorously with sample data to make sure it works both correctly and to the user’s satisfaction. Depending on the complexity of the problem, multiple programmers might be involved in the planning and coding phases. Programming teams often contain subject-matter experts, who might or might not be programmers. For example, an accountant might be part of a team working on a program that requires accounting expertise.

Page 11


Name:

Class:

Date:

Chapter 02 9e Indicate whether the statement is true or false. 1. Access keys are not case sensitive. a. True b. False ANSWER: True 2. If you are going to include color in an interface, limit the number of colors to four, not including white, black, and gray. a. True b. False ANSWER: False 3. Tab order is the order in which each control receives the focus when the user presses the Tab key. a. True b. False ANSWER: True 4. In most cases, an identifying label should consist of one to three words only and appear on one line. a. True b. False ANSWER: True 5. It is best to use black text on a white, off-white, or light gray background. a. True b. False ANSWER: True 6. The Windows standard is to use sentence capitalization for identifying labels. a. True b. False ANSWER: True 7. It is rare for the controls to be added to the form in the correct tab order. a. True b. False ANSWER: True

Page 1


Name:

Class:

Date:

Chapter 02 9e 8. Even if none of a label control’s events will be coded and it will not be referred to in code, you should change its name from the default value. a. True b. False ANSWER: False 9. In a well-designed user interface, each control that can accept user input or respond to the user’s action has an access key assigned to it. a. True b. False ANSWER: True 10. Pressing a button’s access key invokes the button’s Click event. a. True b. False ANSWER: True 11. The text contained in a label control that identifies another control’s contents should be right-aligned within the label, according to Windows standards. a. True b. False ANSWER: False 12. The first step in planning a Windows Forms application is to sketch the user interface. a. True b. False ANSWER: False 13. All controls have a TabIndex property. a. True b. False ANSWER: False

Page 2


Name:

Class:

Date:

Chapter 02 9e Indicate the answer choice that best completes the statement or answers the question. Case-Based Critical Thinking Questions Case 1: BrainPower Tutoring The owner of BrainPower Tutoring needs an application that clients can use to request an appointment. The application should allow users to enter their name, subject, preferred appointment time, and phone number, and submit their request. It should also allow them to print their appointment request, clear the screen, and exit the application. The tutoring center has some clients with visual impairments, so the application should be easy for them to use. 14. How many text boxes do you need for the application? a. three b. four c. five d. six ANSWER: b 15. If you do not see the underlined access keys while an application is running, you can show them temporarily by pressing the __________ key. a. Ctrl b. Shift c. Alt d. Tilde (˜) ANSWER: c 16. Each access key in an interface should be _____________. a. a vowel b. in alphabetical order c. unique d. an integer ANSWER: c 17. Which property determines the order in which each control receives the focus? a. GetFocus b. PrevControl c. NextControl d. TabIndex ANSWER: d

Page 3


Name:

Class:

Date:

Chapter 02 9e 18. Which sequence for the five steps for planning a Windows Forms application is correct? a. Draw a sketch of the user interface, identify the application’s purpose, identify the items that the user must provide, identify the items that the application must provide, and determine how the user and the application will provide their respective items. b. Identify the application’s purpose, draw a sketch of the user interface, identify the items that the user must provide, identify the items that the application must provide, and determine how the user and the application will provide their respective items. c. Identify the application’s purpose, identify the items that the application must provide, identify the items that the user must provide, determine how the user and the application will provide their respective items, and draw a sketch of the user interface. d. Identify the application’s purpose, identify the items that the user must provide, identify the items that the application must provide, determine how the user and the application will provide their respective items, and draw a sketch of the user interface. ANSWER: d 19. According to GUI design guidelines, a meaningful __________ should be displayed on the face of each button. a. name b. caption c. picture color d. title ANSWER: b 20. In Windows applications, which buttons do not typically have access keys assigned to them? a. Exit and Cancel b. OK and Exit c. OK and Next d. OK and Cancel ANSWER: d 21. You can tell whether a control has a TabIndex property by viewing its ____________ list. a. Properties b. Styles c. Tabs d. Formatting ANSWER: a

Page 4


Name:

Class:

Date:

Chapter 02 9e 22. In Windows applications, pressing the __________ and Tab keys simultaneously will move the focus backward. a. Shift b. Ctrl c. Alt d. Ctrl+Shift ANSWER: a 23. Which property of a control is used to specify the position of the text within the control? a. AlignText b. Alignment c. Justify d. TextAlign ANSWER: d 24. Which property is not a commonly used property of a text box? a. BackColor b. Multiline c. ScrollBars d. Description ANSWER: d Case-Based Critical Thinking Questions Case 1: BrainPower Tutoring The owner of BrainPower Tutoring needs an application that clients can use to request an appointment. The application should allow users to enter their name, subject, preferred appointment time, and phone number, and submit their request. It should also allow them to print their appointment request, clear the screen, and exit the application. The tutoring center has some clients with visual impairments, so the application should be easy for them to use. 25. How many buttons do you need for the application? a. one b. two c. three d. four ANSWER: d

Page 5


Name:

Class:

Date:

Chapter 02 9e 26. The TabIndex value assigned to a text box’s identifying label must be __________ for the text box’s access key to work correctly. a. identical to the TabIndex value assigned to the text box itself b. one number less than the TabIndex value assigned to the text box itself c. one number more than the TabIndex value assigned to the text box itself d. no greater than 10 ANSWER: b 27. The text contained in a label control that identifies another control’s contents should be meaningful and __________ within the label. a. right-aligned b. centered c. left-aligned d. justified ANSWER: c 28. The label control property that specifies the color of the text inside the control is called the __________ property. a. ForeColor b. FontColor c. TextColor d. CharacterColor ANSWER: a 29. Which is not a commonly used property of a label control? a. LabelSize b. BorderStyle c. TextAlign d. AutoSize ANSWER: a 30. Which assigns the letter C as the Calculate button’s access key? a. ˜Calculate b. ^Calculate c. &Calculate d. <Calculate ANSWER: c

Page 6


Name:

Class:

Date:

Chapter 02 9e 31. Which control provides an area in the form where the user can enter data? a. text box b. label c. button d. check box ANSWER: a 32. Which label control property determines whether the control automatically sizes to fit its current contents? a. TextAlign b. Fit c. MiddleCenter d. AutoSize ANSWER: d 33. The purpose of a __________ control is to display text that the user is not allowed to edit while the application is running. a. label b. text box c. read-only d. tab order ANSWER: a 34. The last step in planning a Windows Forms application is to __________. a. draw a sketch of the user interface b. identify the items that the application must provide c. identify the items that the user must provide d. determine how the user and the application will provide their respective items ANSWER: a 35. You should adhere to the Windows standards when designing an interface because that consistency will give your interface a familiar look, which will make your application easier for users to learn and use. These guidelines are referred to as __________. a. access controls b. standardized labelling c. core assignment operators d. graphical user interface (GUI) guidelines ANSWER: d

Page 7


Name:

Class:

Date:

Chapter 02 9e 36. When a group of buttons is organized based on Windows standards, which button will appear first? a. the button with the shortest caption b. the button that comes first in alphabetical order by caption c. the most commonly used button d. the least commonly used button ANSWER: c 37. When designing an interface, you should use no more than ____________ different font sizes. a. one b. two c. three d. four ANSWER: b 38. The fourth step in the planning process is to __________. a. draw a sketch of the user interface b. identify the items that the application must provide c. determine how the user and the application will provide their respective items d. identify the items that the user must provide ANSWER: c 39. Which statement about user interface design is true? a. The interface should be designed using black text on a white background. b. The interface should include a text-to-speech reader. c. The interface should use plenty of colors to appeal to young clients. d. The interface should use a different font for each field to keep users from being confused. ANSWER: a 40. An access key allows the user to select an object using the __________ key in combination with a letter or number. a. Shift b. Tab c. Alt d. Backspace ANSWER: c

Page 8


Name:

Class:

Date:

Chapter 02 9e 41. While the text is being entered into the text box, which is used to specify whether the text should remain as typed or be converted to either uppercase or lowercase? a. CharacterCasing b. PasswordChar c. ScrollBars d. TabStop ANSWER: a 42. Which form element typically has its AutoSize property set to False? a. a label control that identifies the contents of a text box b. a label control that identifies the contents of another label control c. a text box that identifies a label control d. a label control that displays program output ANSWER: d 43. A label control that displays program output should use which BorderStyle setting? a. FixedSingle b. Fixed3D c. no BorderStyle (None) d. Sizable ANSWER: a 44. What is a label control? What are two requirements for the text contained in a label control? Should a label control that identifies another label control include an access key? Why or why not? ANSWER: A label control is used in an interface to display text that the user is not allowed to edit during run time, such as text that identifies other controls and text that represents the results of a calculation. The text contained in a label control that identifies another control’s contents, such as the contents of a text box, should be meaningful and left-aligned within the label. Users cannot access label controls, so it is inappropriate to include an access key in the label controls that identify them.

Page 9


Name:

Class:

Date:

Chapter 02 9e Essay 45. Describe how an interface should be organized according to the GUI guidelines covered in the book. ANSWER: In Western countries, the user interface should be organized so that the information flows either vertically (top to bottom) or horizontally (left to right). Related controls should be grouped together using either white (empty) space or one of the tools located in the Containers section of the toolbox. When positioning the controls in the interface, place related controls close to each other and be sure to maintain a consistent margin from the edges of the form. Also, it is helpful to align the borders of the controls wherever possible to minimize the number of different margins appearing in the interface. Doing this allows the user to more easily scan the information.

46. What access key should be used for an Exit button? Why? ANSWER: The access key should be X because X provides a more meaningful association with “Exit” than the letter E does.

47. Explain how the BorderStyle property is used for label controls. ANSWER: The BorderStyle property specifies the appearance of a label’s border. Labels that display program output typically have their BorderStyle property set to FixedSingle. Identifying labels should have the default property setting (None).

48. What is sentence capitalization? How is it used in developing a user interface? ANSWER: Sentence capitalization means you capitalize only the first letter in the first word and in any words that are customarily capitalized. The Windows standard is to use sentence capitalization for identifying labels in an interface.

Page 10


Name:

Class:

Date:

Chapter 02 9e 49. If a text box’s TabIndex value is the number 10, what TabIndex value should its identifying label have and why? ANSWER: The identifying label’s TabIndex value should be 9. This is necessary for a text box’s access key to work correctly. The TabIndex value assigned to each text box’s identifying label is one number less than the value assigned to the text box itself.

50. Define “focus.” How do “focus” and “tab order” relate to each other? ANSWER: When a control has the focus, it can accept user input. The TabIndex property values of the controls in an interface determine when each control receives the focus when the user either presses the Tab key or employs an access key while an application is running. A control whose TabIndex is 4 will receive the focus immediately after the control whose TabIndex is 3, and so on.

51. What are the guidelines for selecting the fonts to be used in an interface? ANSWER: You should use only one font type for all of the text in the interface, and no more than two different font sizes. Avoid using italics and underlining in an interface. The use of bold should be limited to titles, headings, and key items that you want to emphasize.

Page 11


Name:

Class:

Date:

Chapter 02 9e 52. Explain how to set the tab order in an application. ANSWER: Each control’s TabIndex property contains a number, beginning with 0, that represents the order in which the control was added to the form. The TabIndex values determine the tab order, which is the order in which each control receives the focus when the user either presses the Tab key or employs an access key while an application is running. To set the tab order: (1.) Click View on the menu bar, and then click Tab Order. The current TabIndex values appear in blue boxes on the form. (A picture box does not have a TabIndex property.) Click the blue box on the control that should have the TabIndex property of 0. The number in the box changes to 0 and the box’s color changes to white. (2.) Click the blue box on the control that should have the TabIndex property of 1. The number in the box changes to 1. (3.) Continue in this manner to set the TabIndex values for the remaining controls. Be sure to set the values in numerical order. If you make a mistake, press the Esc key to remove the TabIndex boxes from the form, and then repeat Steps 1 through 3.

53. What is an access key? Why should access keys be set in a Windows application? ANSWER: An access key is an underlined letter in an object’s identifying label or caption. It allows the user to select an object using the Alt key in combination with a letter or number. Access keys are not case sensitive. In an interface, you should assign access keys to each control that can accept user input, such as text boxes and buttons (such as a text box) or respond to the user’s actions (such as a button). Access keys are important because they allow people with certain physical disabilities to interact with the application’s interface.

Page 12


Name:

Class:

Date:

Chapter 02 9e 54. Describe four GUI design tips that follow the Windows standards for the use of graphics, fonts, and color. ANSWER: Any four can be used for the answer: 1. Use graphics sparingly. Make sure they are small and not distracting to the user. 2. Use only one font type (usually Segoe UI) for all of the text in the interface. 3. Use no more than two different font sizes in the interface. 4. Avoid use of italics and underlining. 5. Limit use of bold text to titles, headings, and key items that you want to emphasize. 6. Use black, white, and gray when building an interface. Only add color if there is a good reason to do so. 7. Use white, off-white, or light gray for the background. Use black for text. 8. Avoid using a dark color for the background or a light color for text. 9. Limit the number of colors in an interface to three. Make sure colors are complementary. 10. Never use any color as the only means of identification for an element in the interface.

55. What do the TabIndex values determine for the controls in an interface? What is the standard tab order for an interface’s controls? ANSWER: The TabIndex values determine the tab order of the controls, which is the order in which each control receives the focus when the user either presses the Tab key or employs an access key while an application is running. The TabIndex values begin with zero, and each subsequent control will receive the focus based on its TabIndex value. The standard tab order for controls in an interface is determined by whether or not a control accepts user input. Any control that accepts user input should be first; all other controls follow. If a control that accepts user input is identified by a label control, the TabIndex value assigned to each text box’s identifying label should be one number less than the value assigned to the text box itself.

Page 13


Name:

Class:

Date:

Chapter 03 9e Indicate whether the statement is true or false. 1. Most times you will use the Dim statement to declare a variable within the procedure that needs it. a. True b. False ANSWER: True 2. A variable is a computer memory location where a programmer can permanently store an item of data while an application is running. a. True b. False ANSWER: False 3. A variable declared in the declarations section of a form is called a procedure-level variable. a. True b. False ANSWER: False 4. The value stored in a named constant cannot be changed while the application is running. a. True b. False ANSWER: True 5. A Boolean variable is initialized to the value True if no initial value is stated when the variable is declared. a. True b. False ANSWER: False 6. Calculations involving Decimal variables are not subject to the small rounding errors that may occur when using Double variables. a. True b. False ANSWER: True 7. The Double.TryParse and Decimal.TryParse methods can convert a string that contains leading or trailing spaces. a. True b. False ANSWER: True

Page 1


Name:

Class:

Date:

Chapter 03 9e 8. Procedure-level variables are typically declared at the end of a procedure. a. True b. False ANSWER: False 9. A variable declared using one of the numeric data types is automatically initialized to the number 0. a. True b. False ANSWER: True 10. You can eliminate the problems that occur as a result of implicit type conversions by entering the Option Explicit On statement above the Public Class clause in the Code Editor window. a. True b. False ANSWER: False 11. The main memory of a computer is called random access memory or, more simply, RAM. a. True b. False ANSWER: True Indicate the answer choice that best completes the statement or answers the question. 12. Which statement should be used to declare a class-level variable? a. Private Dim dblHeight As Double b. Dim dblHeight As Double c. Class dblHeight As Double d. Private dblHeight As Double ANSWER: d 13. A named constant is created using the __________ statement. a. Fixed b. Const c. ConstantFixed d. Perm ANSWER: b

Page 2


Name:

Class:

Date:

Chapter 03 9e 14. You can use __________ to override the arithmetic order of precedence. a. parentheses b. brackets c. braces d. asterisks ANSWER: a 15. In the mathematical expression 12 / 6 / 2, the answer is ____. a. 1 b. 2 c. 3 d. 4 ANSWER: a 16. If Option Strict is set to On, which statement will assign the contents of the txtLateFee control to a Decimal variable named decLateFee? a. TryParse.Decimal(txtLateFee.Text, decLateFee) b. Decimal.TryParse(txtLateFee.Text, decLateFee) c. decLateFee = Decimal.Convert(txtLateFee.Text) d. decLateFee = txtLateFee.Text ANSWER: b 17. In the mathematical expression 4 * 3 + 15 / 3 - 6, which operation is performed last? a. + b. c. * d. / ANSWER: b

Page 3


Name:

Class:

Date:

Chapter 03 9e Case-Based Critical Thinking Questions Case 1: PetPals You have been hired by PetPals Veterinary Clinic to modify its Bill Calculator application. Upon reviewing the application, you notice that all of the controls have their default names. You also notice that the Calculate button’s code uses the properties of controls in the calculation statements. 18. Two procedures in the PetPals Clinic application need access to the same variable. You can accomplish this by declaring the variable using the __________ keyword in the form’s declarations section. a. Const b. Share c. Private d. Val ANSWER: c 19. In the mathematical expression 4 * 3 + 15 / 3 - 6, which operation is performed first? a. + b. c. * d. / ANSWER: c 20. A control’s __________ event occurs when a change is made to the contents of a control’s Text property. a. CodeChanged b. TextChanged c. ChangedText d. TextModified ANSWER: b 21. The ___________ symbol in a flowchart represents tasks such as ending the application and making calculations. a. oval b. rectangle c. diamond d. parallelogram ANSWER: b

Page 4


Name:

Class:

Date:

Chapter 03 9e 22. The ___________ symbol in a flowchart represents input tasks and output tasks. a. oval b. rectangle c. diamond d. parallelogram ANSWER: d 23. Aside from letters and numbers, a variable name in Visual Basic can only contain the _________ character. a. ampersand (&) b. percent sign (%) c. exclamation mark (!) d. underscore (_) ANSWER: d 24. Short English-like phrases written to represent the steps a program must take to solve a particular problem are called ___________. a. flowcharts b. pseudocode c. object code d. macro code ANSWER: b 25. String variables are automatically initialized using __________. a. spaces b. the keyword Nothing c. the word “Nothing” d. 0 ANSWER: b 26. Which data type can store a number containing a decimal place? a. Double b. Boolean c. String d. Integer ANSWER: a

Page 5


Name:

Class:

Date:

Chapter 03 9e 27. When a button is selected, the computer processes the code contained in the button’s __________ event procedure. a. Submit b. Press c. On d. Click ANSWER: d 28. The __________ symbol indicates the beginning and end of a flowchart. a. oval b. rectangle c. diamond d. parallelogram ANSWER: a 29. Programmers can create __________, which are memory locations inside the computer, to temporarily store data while an application is running. a. characters b. variables c. integers d. strings ANSWER: b Case-Based Critical Thinking Questions Case 1: PetPals You have been hired by PetPals Veterinary Clinic to modify its Bill Calculator application. Upon reviewing the application, you notice that all of the controls have their default names. You also notice that the Calculate button’s code uses the properties of controls in the calculation statements. 30. The total amount a customer owes for all of the services performed during an office visit may contain a decimal place. What data type is best for a variable that will store this value? a. String b. Integer c. Fraction d. Double ANSWER: d

Page 6


Name:

Class:

Date:

Chapter 03 9e 31. Every numeric data type in Visual Basic has a __________ method that can be used to convert a string to that particular data type. a. Convert b. Format c. TryParse d. Number ANSWER: c 32. A memory variable that stores a Double data type requires __________ bytes of storage. a. 2 b. 4 c. 6 d. 8 ANSWER: d 33. Which statement declares a Double variable named dblAverage? a. Dim dblAverage As Double b. Dim As Double dblAverage c. Const dblAverage As Constant d. Dim dblAverage As String ANSWER: a 34. You declare a class-level variable using the __________ keyword. a. Class b. Mod c. Private d. Static ANSWER: c

Page 7


Name:

Class:

Date:

Chapter 03 9e Case-Based Critical Thinking Questions Case 1: PetPals You have been hired by PetPals Veterinary Clinic to modify its Bill Calculator application. Upon reviewing the application, you notice that all of the controls have their default names. You also notice that the Calculate button’s code uses the properties of controls in the calculation statements. 35. Which statement assigns the contents of the dblTax variable, formatted with a dollar sign and two decimal places, to the lblTax control? a. lblTax.Text = dblTax.ToString("Dollar") b. lblTax.Text = dblTax.ToString("C", "2") c. lblTax.Text = dblTax.ToString("C2") d. lblTax.Text = dblTax.ToCurrency("2C") ANSWER: c 36. Specifying the number of decimal places and the special characters to display in a number is called _________. a. formatting b. concatenating c. declaring d. parsing ANSWER: a 37. Which statement formats the contents of the dblPay variable with a dollar sign and no decimal places? a. lblPay.Text = dblPay.ToString("C2") b. lblPay.Text = dblPay.ToString(C0) c. lblPay.Text = dblPay.ToCurrency("C0") d. lblPay.Text = dblPay.ToString("C0") ANSWER: d 38. Which symbol is used to represent exponentiation (raising a number to a power) in a calculation? a. ^ b. < c. > d. \ ANSWER: a

Page 8


Name:

Class:

Date:

Chapter 03 9e 39. Which symbol is used in code to assign a value to an existing variable? a. ˜ b. ^ c. < d. = ANSWER: d 40. Each data type is a class from which a variable can be __________. a. instantiated b. inferred c. copied d. implied ANSWER: a Essay 41. A local gym needs an application to apply a 10% discount for all new members who present a coupon during enrollment. Write the statements to declare a variable to record whether a customer has a coupon, and to assign the discount rate. The discount rate will not change while the application is running. ANSWER: Dim blnCoupon As Boolean Const decDISCOUNT As Decimal = .1D (or Const dblDISCOUNT As Double = .1)

42. Explain why the use of class-level variables should be minimized during run time. Why does this restriction not apply to class-level named constants? ANSWER: The use of class-level variables should be minimized because it can lead to errors that are difficult to locate in your code. Class-level named constants, however, do not have the same problem because their values cannot be changed during run time.

Page 9


Name:

Class:

Date:

Chapter 03 9e 43. A procedure in an application needs to store data used to calculate the total price of purchasing tires. The price of the tires will contain a decimal place. The number of tires will always be a whole number. Write the appropriate Dim statements to declare the variables. Make sure to use appropriate naming conventions. ANSWER: Dim decPrice As Decimal (or Dim dblPrice As Double) Dim intTires As Integer

44. What is a static variable? How is it different from a class-level variable? ANSWER: A static variable is a procedure-level variable that remains in memory and also retains its value even when its declaring procedure ends. Like a class-level variable, a static variable is not removed from the computer’s main memory until the application ends. Unlike a class-level variable, a static variable can be used only by the procedure in which it is declared.

45. Define the term “flowchart.” Define each of the three flowchart symbols and discuss how each is used within a flowchart. ANSWER: A flowchart is a diagram that uses standardized symbols to show the steps a procedure must follow to reach its goal. Symbols include: 1. The start/stop symbol is an oval symbol; it indicates the beginning and end, respectively, of the flowchart. 2. The process symbol is a rectangle; it is used to represent tasks such as calculations. 3. The input/output symbol is a parallelogram; it is used to represent input tasks and output tasks.

Page 10


Name:

Class:

Date:

Chapter 03 9e 46. A procedure in an application needs to store student data. The student first name, student last name, student GPA, and whether or not the student is registered all need to be stored. Write the appropriate Dim statements to declare the variables. Make sure to use appropriate naming conventions. ANSWER: Dim strFirstName As String Dim strLastName As String Dim decGpa As Decimal (or Dim dblGpa As Double) Dim blnRegistered As Boolean

47. The decBalance variable contains the number 1368.52. Write the assignment statement to display the value with a dollar sign, a thousand separator, and two decimal places in the lblBalance control. ANSWER: lblBalance.Text = decBalance.ToString("C2")

48. Explain the scope and lifetime of variables. How are a variable’s scope and lifetime determined? ANSWER: Every variable has a scope and a lifetime. A variable’s scope indicates where the variable can be used in an application’s code. A variable’s lifetime indicates how long the variable remains in the computer’s internal memory. A variable’s scope and lifetime are determined by where you declare the variable (where you enter the variable’s declaration statement).

Page 11


Name:

Class:

Date:

Chapter 03 9e 49. An application allows a user to enter a salary amount and a bonus rate; both will be used in a calculation. The salary amount entered in the txtSalary control will always be a whole number, and the bonus rate entered in the txtBonusRate control may contain a decimal place. Write the appropriate Dim statements to declare the variables. Write the related statements needed to convert the strings entered by the user into numeric data types. ANSWER: Dim intSalary As Integer Dim decBonusRate As Decimal (or Dim dblBonusRate As Double) Integer.TryParse(txtSalary.Text, intSalary) Decimal.TryParse(txtBonusRate.Text, decBonusRate) [or Double.TryParse(txtBonusRate.Text, dblBonusRate) ]

50. A procedure in an application needs to store tax rate data. The county of residence and the tax rate need to be stored. Write the appropriate Dim statements to declare the variables. Write an assignment statement that assigns .08 to the tax rate variable. ANSWER: Dim strCounty As String Dim decTaxRate As Decimal (or Dim dblTaxRate As Double) decTaxRate = .08D (or dblTaxRate = .08)

51. An application allows a user to enter an item price and a quantity to be used in a calculation. The item price entered in the txtItemPrice control may contain a decimal place, and the quantity entered in the txtQuantity control will always be a whole number. Write the appropriate Dim statements to declare the variables. Write the related statements needed to convert the strings entered by the user into numeric data types. ANSWER: Dim decItemPrice As Decimal (or Dim dblItemPrice As Double) Dim intQuantity As Integer Decimal.TryParse(txtItemPrice.Text, decItemPrice) [or Double.TryParse(txtItemPrice.Text, dblItemPrice) ] Integer.TryParse(txtQuantity.Text, intQuantity)

Page 12


Name:

Class:

Date:

Chapter 03 9e 52. Write a statement that displays the decRate variable’s value, multiplied by 100 and formatted with a percent sign and one decimal place, in the lblRate control. ANSWER: lblRate.Text = decRate.ToString("P1")

53. What type of numeric data can the Decimal and Double variable data types store? Explain the differences between these two data types and problems that can occur with their use. ANSWER: These data types can both store numbers containing a decimal place. The differences between them are in the range of numbers each type can store, and the amount of memory each type needs to store the numbers. Calculations involving Decimal variables are not subject to the small rounding errors that may occur when using Double variables because the Decimal data type can store numbers with many more significant digits. In most cases, small rounding errors do not create any problems in an application, but the Decimal data type is best to use for applications using complex equations dealing with money.

Case-Based Critical Thinking Questions Case 1: PetPals You have been hired by PetPals Veterinary Clinic to modify its Bill Calculator application. Upon reviewing the application, you notice that all of the controls have their default names. You also notice that the Calculate button’s code uses the properties of controls in the calculation statements. 54. Describe three modifications you should make to this application. ANSWER: Meaningful names should be given to controls that will either be coded or referred to in code. Variables for all input items that will be used in a calculation should be declared, as well as variables to store the results of calculations. The three Option statements should be entered in the Code Editor window.

Page 13


Name:

Class:

Date:

Chapter 03 9e Essay 55. The decRate variable contains the number .03. Write the assignment statement to display the value as 3% in the lblRate control. ANSWER: lblRate.Text = decRate.ToString("P0")

Page 14


Name:

Class:

Date:

Chapter 04 9e Indicate whether the statement is true or false. 1. When the code for a selection structure in Visual Basic runs, the code that follows the Else clause will be executed when the condition is true. a. True b. False ANSWER: False 2. Comparison operators are always evaluated after arithmetic operators in a conditional expression. a. True b. False ANSWER: True 3. You can use the arithmetic assignment operators to abbreviate an assignment statement that contains an arithmetic operator. a. True b. False ANSWER: True 4. A programmer must phrase a selection structure’s condition so that it results in either a true or a false answer only. a. True b. False ANSWER: True 5. The AndAlso operator does not always evaluate the second condition. a. True b. False ANSWER: True 6. Before using a string in a comparison, you can use either the ToUpper method or the ToLower method to convert the string to uppercase or lowercase, respectively, and then use the converted string in the comparison. a. True b. False ANSWER: True 7. When you select a radio button, its Checked property changes from True to False, invoking its CheckedChanged event. a. True b. False ANSWER: False Page 1


Name:

Class:

Date:

Chapter 04 9e 8. The expression 12 > 0 AndAlso 12 < 10 * 2 evaluates to True. a. True b. False ANSWER: True 9. Some procedures require a selection structure that can choose from several different alternatives. Such selection structures are referred to as multiple-alternative selection structures. a. True b. False ANSWER: True 10. You can include an identifying label on a group box by setting the group box’s Identity property. a. True b. False ANSWER: False 11. Every text box’s KeyPress event procedure needs to be coded. a. True b. False ANSWER: False 12. Radio buttons allow you to limit the user to only one choice from a group of two or more related but mutually exclusive options. a. True b. False ANSWER: True 13. A check box’s CheckedChanged event occurs when the value in its Checked property changes. a. True b. False ANSWER: True 14. The Not operator would make a True statement False, but would not make a False statement True. a. True b. False ANSWER: False

Page 2


Name:

Class:

Date:

Chapter 04 9e 15. A single-alternative selection structure requires one or more actions to be taken only when its condition is true. a. True b. False ANSWER: True Indicate the answer choice that best completes the statement or answers the question. 16. Consider the expression 3 * 2 ^ 2 < 16 + 5 AndAlso 100 / 10 * 2 > 15 - 3. Which operation is performed first? a. ^ b. / c. * d. + ANSWER: a 17. To specify a range of values in a Select Case statement’s Case clause, use the _______ keyword when you know only one end of the range. a. To b. From c. Of d. Is ANSWER: d 18. When a check box is selected, its __________ property contains the Boolean value True; otherwise, it contains the Boolean value False. a. Selected b. Clicked c. Checked d. Ticked ANSWER: c

Page 3


Name:

Class:

Date:

Chapter 04 9e

Case-Based Critical Thinking Questions

Case 1: Jack of All Trades

You’ve been asked to design an application that will process the transactions for Jack of All Trades, which rents small power equipment to commercial and residential customers. The strCustomer variable will be used to determine whether a customer is commercial (C) or residential (R). Commercial customers receive a 10% discount if they are members of the Rental Rewards Program. Residential customers receive a 5% discount if they are members. The strMember variable will be used to determine whether the customer is (Y) or is not (N) a member of the Rental Rewards Program. 19. The message provided when a customer is not a current member of the Rental Rewards Program is “Enroll this customer in the Rental Rewards Program?” The clerk can click “Yes” to begin the application process, or “No” to enter a note that the customer has declined the offer. What type of selection structure is used to accomplish this? a. single-alternative selection structure b. dual-alternative selection structure c. yes/no selection structure d. decline/accept selection structure ANSWER: b 20. The Backspace key is represented by the __________ constant. a. ControlChars.Back b. Control.BackSpace c. ControlChars.Backspace d. ControlChars.Backspc ANSWER: a 21. Which condition will evaluate to True when the intPackages variable contains the value 100? a. If intPackages = 100 Then b. If intPackages <> 0 Then c. If intPackages > 1 Then d. The conditions in all of the other choices would evaluate to True. ANSWER: d

Page 4


Name:

Class:

Date:

Chapter 04 9e 22. The _________ symbol in a flowchart represents the condition in a selection structure. a. oval b. rectangle c. diamond d. parallelogram ANSWER: c 23. You can use a(n) __________ control to visually separate related controls from other controls on the form. a. radio button b. check box c. group box d. icon area ANSWER: c 24. To specify a range of values in a Select Case statement’s Case clause, use the _______ keyword when you know both the upper and lower values in the range. a. To b. From c. Of d. Is ANSWER: a 25. A text box’s __________ event occurs each time the user presses a key while the control has the focus. a. PressEnter b. KeyEnter c. KeyPress d. FocusPress ANSWER: c 26. Which statement assigns the contents of the txtGrade control, in uppercase, to the strGrade variable? a. If strGrade = txtGrade.Text.ToUpper Then b. strGrade.ToUpper = txtGrade.Text c. strGrade = txtGrade.Text.ToUpper d. txtGrade.Text.ToUpper = strGrade ANSWER: c

Page 5


Name:

Class:

Date:

Chapter 04 9e 27. What is the value of the expression 9 * 2 - 8 > 5 + 2 / 2? a. 10 b. 6 c. False d. True ANSWER: d 28. Logical operators are sometimes referred to as __________ operators. a. relational b. arithmetic c. comparison d. Boolean ANSWER: d 29. Which is the “not equal to” operator in Visual Basic? a. > b. <> c. >= d. <= ANSWER: b 30. To prevent a text box from accepting inappropriate characters, you first use the e parameter’s __________ property to determine the key that the user pressed. a. KeyStruck b. KeyEnter c. KeyChar d. KeyPress ANSWER: c 31. Which operator is evaluated last in the expression 9 * 2 - 8 > 5 + 2 / 2? a. b. + c. > d. * ANSWER: c

Page 6


Name:

Class:

Date:

Chapter 04 9e 32. A __________ represents information that is passed to an event procedure when the event occurs. a. solution b. parameter c. condition d. statement ANSWER: b 33. If the intInventory variable contains the value 28, the condition in the If intInventory <= 25 Then clause will evaluate to ____. a. Yes b. No c. True d. False ANSWER: d Case-Based Critical Thinking Questions

Case 1: Jack of All Trades

You’ve been asked to design an application that will process the transactions for Jack of All Trades, which rents small power equipment to commercial and residential customers. The strCustomer variable will be used to determine whether a customer is commercial (C) or residential (R). Commercial customers receive a 10% discount if they are members of the Rental Rewards Program. Residential customers receive a 5% discount if they are members. The strMember variable will be used to determine whether the customer is (Y) or is not (N) a member of the Rental Rewards Program. 34. You meet with the manager of Jack of All Trades and she tells you that she would like the clerks to ask customers whether they want their receipt printed, emailed, texted, or any combination of these choices. Based on this feedback, you decide to use ____________ for the receipt choices in the interface. a. radio buttons b. check boxes c. text boxes d. labels ANSWER: b

Page 7


Name:

Class:

Date:

Chapter 04 9e 35. Consider the expression 3 * 2 ^ 2 < 16 + 5 AndAlso 100 / 10 * 2 > 15 - 3. Which operation is performed last? a. ^ b. < c. > d. AndAlso ANSWER: d 36. In which order should operators always be evaluated? a. arithmetic, logical, comparison b. arithmetic, comparison, logical c. logical, arithmetic, comparison d. logical, comparison, arithmetic ANSWER: b 37. If the intQuantity and decPrice variables contain the numbers 3 and 15.75, respectively, the condition in the If intQuantity > 0 AndAlso intQuantity < 10 OrElse decPrice > 20 clause will evaluate to __________. a. True b. False c. Yes d. No ANSWER: a 38. The dblMiles variable contains the number 575 before the code below is processed. What value will be in the variable after the code is processed? If dblMiles >= 500 Then dblMiles = dblMiles * 0.45 Else dblMiles = dblMiles * 0.25 End If a. 0 b. 143.75 c. 225 d. 258.75 ANSWER: d

Page 8


Name:

Class:

Date:

Chapter 04 9e 39. Except for the ____ operator, all of the logical operators allow you to combine two or more subconditions into one compound condition. a. AndAlso b. OrElse c. Xor d. Not ANSWER: d 40. Which operator is evaluated first in the expression 9 * 2 - 8 > 5 + 2 / 2? a. b. + c. > d. * ANSWER: d 41. Consider the expression 3 * 2 ^ 2 < 16 + 5 AndAlso 100 / 10 * 2 > 15 - 3. Which operation is performed second? a. ^ b. / c. * d. + ANSWER: c

Page 9


Name:

Class:

Date:

Chapter 04 9e

Case-Based Critical Thinking Questions

Case 1: Jack of All Trades

You’ve been asked to design an application that will process the transactions for Jack of All Trades, which rents small power equipment to commercial and residential customers. The strCustomer variable will be used to determine whether a customer is commercial (C) or residential (R). Commercial customers receive a 10% discount if they are members of the Rental Rewards Program. Residential customers receive a 5% discount if they are members. The strMember variable will be used to determine whether the customer is (Y) or is not (N) a member of the Rental Rewards Program. 42. Which If clause would evaluate to True and apply the 10% discount for a commercial customer who is a member of the Rental Rewards Program? a. If strCustomer <> "C" AndAlso strMember <> "Y" b. If strCustomer = "C" AndAlso strMember = "Y" c. If strCustomer <> "R" OrElse strMember = "Y" d. If strCustomer = "C" OrElse strMember = "Y" ANSWER: b 43. Comparison operators are also referred to as __________ operators. a. relational b. arithmetic c. logical d. Boolean ANSWER: a

Page 10


Name:

Class:

Date:

Chapter 04 9e

Case-Based Critical Thinking Questions

Case 1: Jack of All Trades

You’ve been asked to design an application that will process the transactions for Jack of All Trades, which rents small power equipment to commercial and residential customers. The strCustomer variable will be used to determine whether a customer is commercial (C) or residential (R). Commercial customers receive a 10% discount if they are members of the Rental Rewards Program. Residential customers receive a 5% discount if they are members. The strMember variable will be used to determine whether the customer is (Y) or is not (N) a member of the Rental Rewards Program. 44. The application needs to display a message that reminds the clerk to ask customers to join the Rental Rewards Program when they check out. This message should only display if the customer is not currently in the program. Which If clause would evaluate to True and display the reminder message for the clerk? a. If strMember <> "Y" Then b. If strMember = "Y" Then c. If strMember = "N" Then d. Both If strMember <> "Y" Then and If strMember = "N" Then. ANSWER: d 45. When coding the KeyPress event procedure, use the e parameter’s __________ property to cancel the key if it is an inappropriate one. a. Check b. KeyEnter c. KeyChar d. Handled ANSWER: d

Page 11


Name:

Class:

Date:

Chapter 04 9e 46. An application needs to display a message indicating whether or not a student has been accepted to a college. The message should be either “Accepted” or “Not Accepted.” A student must meet two conditions to be accepted: he or she must have an SAT score of 1750 or higher along with a GPA of 3.3 or higher. Rewrite the following If statement to correct all errors. If intSAT >= 1750 OrElse dblGpa >= 3.3 Than lblMessage.Text = "Accepted" Else lblMessage.Text = "Not Accepted" End If ANSWER: If intSAT >= 1750 AndAlso dblGpa >= 3.3 Then lblMessage.Text = "Accepted" Else lblMessage.Text = "Not Accepted" End If

47. Write a statement that temporarily converts the contents of the txtStatus control’s Text property to uppercase and stores the result in the strStatus variable. ANSWER: strStatus = txtStatus.Text.ToUpper

48. Describe nested selection structures. ANSWER: Both paths in a selection structure can include instructions that declare variables, perform calculations, and so on; both can also include other selection structures. When either a selection structure’s true path or its false path contains another selection structure, the inner selection structure is referred to as a nested selection structure because it is contained (nested) entirely within the outer selection structure.

Page 12


Name:

Class:

Date:

Chapter 04 9e 49. Write an If clause to determine whether the dblTemp variable contains a number that is within the range of 65 through 75, inclusive. ANSWER: If dblTemp >= 65 AndAlso dblTemp <= 75 Then

50. Explain why procedures need to use selection structures. ANSWER: Many times, a procedure will need to use the selection structure. This structure tells the computer that it needs to make a decision before it can select the next instruction to process. The decision is based on a condition specified at the beginning of the selection structure, and the next instruction to process is based on the result of that decision.

51. An application needs to calculate a discount for customers who are either preferred customers or senior citizens. Preferred customers have a discount code of “P.” Senior citizens have a discount code of “S.” The discount code is stored in uppercase in the strCode variable. Write an If clause that will evaluate to True so that the discount is calculated for the appropriate customers. ANSWER: If strCode = "P" OrElse strCode = "S" Then

Page 13


Name:

Class:

Date:

Chapter 04 9e 52. Write a selection structure whose true path calculates and displays (in the lblGross control) an employee’s weekly gross pay when the hours worked are in the range of 0 through 40, inclusive. The hours worked, pay rate, and total wages are stored in Double variables named dblHours, dblRate, and dblGross, respectively. Display the gross pay with a dollar sign and two decimal places. When the hours worked are not in the appropriate range, the selection structure’s false path should display the string “N/A” in the lblGross control. ANSWER: If dblHours >= 0 AndAlso dblHours <= 40 Then dblGross = dblHours * dblRate lblGross.Text = dblGross.ToString("C2") Else lblGross.Text = "N/A" EndIf

53. Provide at least three examples of items that can be included in an If…Then…Else statement’s condition. ANSWER: An If . . . Then . . . Else statement’s condition can contain variables, named constants, literals, properties, methods, keywords, arithmetic operators, comparison operators, and logical operators.

54. Write an If clause that will determine whether the strColor variable contains either the string “RED” or the string “BLUE”. ANSWER: If strColor.ToUpper = "RED" OrElse strColor.ToUpper = "BLUE" Then

Page 14


Name:

Class:

Date:

Chapter 04 9e 55. Write an If...Then...Else statement that displays the string “Balance Due” in the lblMessage control when the dblBalance variable contains a number that is greater than 0; otherwise, display the string “Thank you for your payment.” in the control. ANSWER: If dblBalance > 0 Then lblMessage.Text = "Balance Due" Else lblMessage.Text = "Thank you for your payment." End If

Essay 56. What is a selection structure? What is the difference between a single-alternative and dual-alternative selection structure? ANSWER: A selection structure is one of the three basic control structures. This structure tells the computer that it needs to make a decision before it can select the next instruction to process. The decision is based on a condition specified at the beginning of the selection structure, and the next instruction to process is based on the result of that decision. A single-alternative selection structure requires one or more actions to be taken only when its condition evaluates to True. A dual-alternative selection structure requires one set of instructions to be followed only when the condition is true and a different set of instructions only when it is false.

57. An application needs to display the message “Please add water” when the amount of water has fallen below the safe limit. Rewrite the following If statement to correct all errors. If intWaterLimit < intWaterAmount Then lblWarning = "Please add water" End If ANSWER: If intWaterAmount < intWaterLimit Then lblWarning.Text = "Please add water" End If

Page 15


Name:

Class:

Date:

Chapter 05 9e Indicate whether the statement is true or false. 1. In a posttest loop, the “5” in the following condition specifies when to continue: Loop While intNum <= 5 a. True b. False ANSWER: True 2. At times, you might need to use the Items collection’s Add method (rather than the String Collection Editor) to add items to a list box. a. True b. False ANSWER: True 3. The startValue, endValue, and stepValue items in the For clause control the number of times the loop body is processed. a. True b. False ANSWER: True 4. In a Do...Loop statement, a condition can be phrased as either a looping condition or a loop enter condition. a. True b. False ANSWER: False 5. Accumulators are usually initialized to 0, whereas counters are initialized to either 0 or 1. a. True b. False ANSWER: True 6. You can make a list box any size you want, but you should follow the Windows standard. a. True b. False ANSWER: True 7. In a Do...Loop statement, the keyword While indicates that the loop instructions should be processed while the condition is false. a. True b. False ANSWER: False

Page 1


Name:

Class:

Date:

Chapter 05 9e 8. Like the condition in a selection structure, the condition in a loop must evaluate to either True or False. a. True b. False ANSWER: True 9. A loop that has no way to end is called an infinite loop. a. True b. False ANSWER: True 10. A counter is always incremented by a constant value. a. True b. False ANSWER: True 11. In a pretest loop, the evaluation of the condition occurs after the instructions within the loop are processed. a. True b. False ANSWER: False 12. When you declare a variable in the For clause, the variable has block scope and can be used only within the For...Next loop. a. True b. False ANSWER: True 13. The condition in a loop can appear at either the top or the bottom of the loop. a. True b. False ANSWER: True 14. Programmers use the repetition structure when they need the computer to repeatedly process one or more program instructions. a. True b. False ANSWER: True

Page 2


Name:

Class:

Date:

Chapter 05 9e Indicate the answer choice that best completes the statement or answers the question. 15. The loop created by the For...Next statement is a __________ loop. a. posttest b. pretest c. selection d. sequential ANSWER: b 16. Your supervisor wants you to change the Do...Loop in the previous problem to a For...Next loop. He would like the message to appear only three times. Which For clause should you use? a. For intCounter As Integer = 1 To 4 b. For intCounter As Integer = 1 To 3 c. For intCounter As Integer = 0 To 3 d. For intCounter = 0 To 3 ANSWER: b 17. You use the ____ operator to concatenate strings. a. @ b. % c. & d. # ANSWER: c 18. The ControlChars.NewLine constant instructs the computer to ___________. a. advance the insertion point to the next line in a control b. insert spaces on the next line in a control c. insert spaces on the current line in a control d. advance the insertion point to the next line in the Code Editor window ANSWER: a 19. What term is used for the process of adding increments of a negative number? a. decrementing b. initializing c. deprocessing d. negating ANSWER: a

Page 3


Name:

Class:

Date:

Chapter 05 9e 20. Like the condition in a selection structure, a loop’s condition in a flowchart is represented by a(n) __________. a. diamond b. rectangle c. oval d. parallelogram ANSWER: a 21. A(n) __________ error occurs when the value assigned to a memory location is too large for the location’s data type. a. full b. spill c. rip d. overflow ANSWER: d 22. According to the Windows standard, a list box should display a minimum of __________ item(s) at a time. a. two b. three c. four d. five ANSWER: b 23. A numeric variable used to add together each employee’s weekly gross pay is referred to as a(n) __________. a. counter b. updater c. incrementer d. accumulator ANSWER: d 24. Each time either the user or a statement selects an item in a list box, the list box’s SelectedValueChanged and __________ events occur. a. SelectedItemChanged b. SelectionChanged c. SelectedIndexChanged d. ItemChanged ANSWER: c

Page 4


Name:

Class:

Date:

Chapter 05 9e 25. The instructions in which type of loop will always be processed at least once? a. pretest b. posttest c. sequence d. selection ANSWER: b 26. If the stepValue is omitted when coding a For...Next statement, a stepValue of __________ is used when the statement is executed. a. −1 b. 0 c. 0.1 d. 1 ANSWER: d 27. A default button is identified by setting the form’s __________ property. a. AcceptButton b. DefaultButton c. SelectedButton d. CancelButton ANSWER: a 28. What term is used to describe assigning a beginning value to a counter or an accumulator? a. introducing b. initializing c. incrementing d. updating ANSWER: b 29. You can use either the SelectedItem property or the __________ property to select the default list box item from code. a. Selection b. SelectedIndex c. ItemChoice d. Items ANSWER: b

Page 5


Name:

Class:

Date:

Chapter 05 9e 30. Which type of loop would you use to process loop instructions a precise number of times? a. infinite b. sorted c. endless d. counter-controlled ANSWER: d Case-Based Critical Thinking Questions Case 1: XYZ Solutions You have just started working for XYZ Solutions as a programmer. Your first assignment is to review and correct various blocks of code so that you can become familiar with the company’s programs. 31. The following code in an XYZ Solutions program is not working properly. The code should display the intCounter variable’s value, but only when the value is less than or equal to 15. What mistake did the previous programmer make? Dim intCounter As Integer intCounter = 1 Do Until intCounter <= 15 lblMsg.Text = lblMsg.Text & intCounter.ToString & ControlChars.NewLine intCounter += 1 Loop a. The counter variable should be initialized to 0. b. The While keyword should be used instead of the Until keyword. c. The counter variable should be decremented. d. intCounter += 1 should be changed to intCounter = intCounter + 1. ANSWER: b 32. The number of choices the user can select from a list box is controlled by the list box’s ____ property. a. Selection b. Display c. Control d. SelectionMode ANSWER: d

Page 6


Name:

Class:

Date:

Chapter 05 9e 33. You changed the Do clause to the correct For clause in the previous problem. You also changed the Loop keyword to the Next keyword for the For...Next loop. What else needs to be changed about the Do loop? a. The Dim statement that declares and initializes the intCounter variable needs to be removed. b. The intCounter += 1 statement, which updates the intCounter variable within the loop, needs to be removed. c. You need to add a stepValue to the For clause because the default stepValue is 0. d. Both a and b. ANSWER: d 34. Visual Basic’s built-in __________ class contains many methods that your applications can use to perform financial calculations. a. Core b. Duo c. Armor d. Financial ANSWER: d 35. In a nested repetition structure, one loop, referred to as the __________ loop, is placed entirely within another loop, called the __________ loop. a. inner, outer b. primary, secondary c. minor, major d. dependent, independent ANSWER: a 36. Which statement adds the number stored in the decPrice variable to the number stored in the decSubtotal variable, and then assigns the result to the decSubtotal variable? a. decSubtotal =+ decPrice b. decPrice =+ decSubtotal c. decSubtotal += decPrice d. decPrice += decSubtotal ANSWER: c 37. You can use a __________ to display a list of items from which the user can select zero or more items. a. list box b. radio button group c. label group d. text box group ANSWER: a

Page 7


Name:

Class:

Date:

Chapter 05 9e 38. A unique number called a(n) __________ identifies each item in a collection. a. counter b. index c. accumulator d. tracker ANSWER: b 39. The strFirstName and strLastName variables contain the strings “Jane” and “Jones,” respectively. Which statement will display the string “Jones, Jane” (the last name, a comma, a space, and the first name) in the lblFullName control? a. lblFullName.Text = strLastName, & strFirstName b. lblFullNameText = strLastName & ", " strFirstName c. lblFullName.Text = strLastName & ", " & strFirstName d. lblFullName.Text = strLastName, x strFirstName ANSWER: c 40. You can stop an infinite loop by clicking Debug on the menu bar, and then clicking the __________ Debugging option. a. Stop b. Cancel c. Abort d. End ANSWER: a 41. A ____ structure is also referred to as a loop. a. selection b. sequence c. repetition d. core ANSWER: c 42. If the stepValue in a For...Next statement is a positive number, the loop ends when the counter’s value is __________ the endValue. a. less than b. greater than c. less than or equal to d. greater than or equal to ANSWER: b

Page 8


Name:

Class:

Date:

Chapter 05 9e 43. An application translates English words into French words and displays the results as a message in a label control. The strEnglish variable contains the string “apple.” The strFrench variable contains the string “pomme.” Write an assignment statement to display the string “The French word for apple is pomme.” in the lblMessage control. ANSWER: lblMessage.Text = "The French word for " & strEnglish & " is " & strFrench & "."

44. Write the assignment statements needed to increment the intCount variable by 1 and update the decBalance variable by the value stored in the decOrderAmount variable. ANSWER: intCount = intCount + 1 decBalance = decBalance + decOrderAmount OR intCount += 1 decBalance += decOrderAmount

45. Write a pretest loop that adds together the integers 2, 4, 6, 8, 10, 12, 14, 16, 18, and 20. Use the intNum variable to keep track of the integers. Store the result in the intResult variable (which contains the number 0). Use the For...Next statement. ANSWER: For intNum As Integer = 2 To 20 Step 2 intResult += intNum Next intNum

Page 9


Name:

Class:

Date:

Chapter 05 9e Essay 46. Explain the difference between a looping condition and a loop exit condition. ANSWER: A looping condition indicates when the computer should continue looping through the instructions. A loop exit condition tells the computer when to exit (or stop) the loop. Every looping condition has an opposing loop exit condition; one is the opposite of the other.

47. Describe the Sorted property of a list box. ANSWER: The Sorted property specifies whether the items in the list should appear in the order they are entered or in sorted order. When sorted, items in a list box appear in dictionary order based on their leftmost characters. This means that numbers appear before letters, and a lowercase letter appears before its uppercase equivalent.

48. Write a counter-controlled loop that displays the integers 5, 10, 15, 20, 25, and 30 in the lstMinutes control. Use the For…Next statement. ANSWER: For intMinutes As Integer = 5 To 30 Step 5 lstMinutes.Items.Add(intMinutes.ToString) Next intMinutes

49. What is a counter-controlled loop and when is it used in a program? What statement provides the most efficient way to write a counter-controlled loop? ANSWER: A counter-controlled loop is a loop whose processing is controlled by a counter. You use a countercontrolled loop when you want the computer to process the loop instructions a precise number of times. The For...Next statement is the most efficient way to write a counter-controlled loop.

Page 10


Name:

Class:

Date:

Chapter 05 9e 50. What is an accumulator? What does it mean to initialize and update an accumulator in a program? ANSWER: An accumulator is a numeric variable used for accumulating (adding together) something, such as a total dollar amount. You initialize an accumulator to assign a beginning value to it, and an accumulator is usually initialized to the number 0. You update an accumulator by either adding a number to (called incrementing) or subtracting a number from (called decrementing) the value stored in the accumulator. An accumulator is usually updated by an amount that varies. It is updated each time the loop instructions are processed.

51. Write two different Do...Loop clauses that stop the loop when the value in the intAmount variable is less than or equal to the value in the intLimit variable. Use the Until keyword in the first clause, and use the While keyword in the second clause. ANSWER: Do Until intAmount <= intLimit Do While intAmount > intLimit

52. Explain the difference between a pretest loop and a posttest loop. ANSWER: In a pretest loop, the condition appears at the beginning of the loop. The condition will be evaluated before the instructions within the loop are processed. Depending on the result of the evaluation, the instructions in a pretest loop may never be processed. In a posttest loop, the condition appears at the end of the loop. The condition will be evaluated after the instructions within the loop are processed. The instructions within a posttest loop will always be processed at least once.

53. Explain the difference between using the keywords While and Until within a Do...Loop statement. ANSWER: The keyword While is used in a looping condition to specify that the loop body should be processed while (as long as) the condition is true. The keyword Until is used in a looping condition to specify that the loop body should be processed until the condition becomes true, at which time the loop should stop.

Page 11


Name:

Class:

Date:

Chapter 05 9e 54. What is a list box? Provide two of the Windows standards for its use on a form. ANSWER: A list box displays a list of items from which the user can select zero items, one item, or multiple items. The Windows standard is to display a minimum of three items and a maximum of eight items at a time. Use a label control to provide keyboard access to the list box. List box items are either arranged by use, with the most used entries appearing first in the list, or sorted in ascending order.

55. What happens when you declare a counter variable in the For clause versus when you declare a counter variable in a Dim statement? ANSWER: When you declare a counter variable in the For clause, the variable has block scope and can be used only within the For…Next loop. When you declare a counter variable in a Dim statement, the variable has procedure scope and can be used within the entire procedure.

56. Write a pretest loop that adds together the integers from 1 to 50, inclusive. Use the intNumber variable (which contains the number 1) to keep track of the integers. Store the result in the intResult variable (which contains the number 0). Use the Do...Loop statement and the While keyword. ANSWER: Do While intNumber <= 50 intResult += intNumber intNumber += 1 Loop

Page 12


Name:

Class:

Date:

Chapter 05 9e 57. What is a counter? What does it mean to initialize and update a counter in a program? ANSWER: A counter is a numeric variable used for counting something, such as the number of employees paid in a week. You initialize a counter to assign a beginning value to it, and a counter is usually initialized to the number 0. You update a counter by either adding a number to (called incrementing) or subtracting a number from (called decrementing) the value stored in the counter. A counter is always updated by a constant number, and it is updated each time the loop instructions are processed.

Page 13


Name:

Class:

Date:

Chapter 06 9e Indicate whether the statement is true or false. 1. A function’s header includes the As dataType section, which specifies the data type of the value the function will return. a. True b. False ANSWER: True 2. A Function procedure does not return a value after performing its assigned task. a. True b. False ANSWER: False 3. An event procedure is a Function procedure that is associated with a specific object and event. a. True b. False ANSWER: False 4. The Math.Round method can be used with a single argument to round amounts to two decimal places. a. True b. False ANSWER: False 5. The number of arguments listed in the calling (invoking) statement’s argumentList should agree with the number of parameters listed in the parameterList in the procedure header. a. True b. False ANSWER: True 6. By default, an event procedure’s name is composed of the object’s name followed by an underscore and the event’s name. a. True b. False ANSWER: True 7. You can determine whether a variable is being passed by value or by reference by looking at the statement that calls (invokes) the procedure. a. True b. False ANSWER: False

Page 1


Name:

Class:

Date:

Chapter 06 9e 8. The names of the arguments in a statement that calls (or invokes) a procedure need to be identical to the names of the corresponding parameters. a. True b. False ANSWER: False 9. Each parameter stores an item of data that it receives from the calling statement’s argumentList. a. True b. False ANSWER: False 10. An independent Sub procedure is processed only when a statement in your code calls it. a. True b. False ANSWER: True 11. An argument in a calling statement can be a literal, a named constant, a keyword, or a variable. a. True b. False ANSWER: True Indicate the answer choice that best completes the statement or answers the question. 12. Instead of passing a copy of a variable’s value to a procedure, you can pass the variable’s __________, which is its location in the computer’s main memory. a. label b. parameter c. dataType d. address ANSWER: d 13. When using __________, you capitalize the first letter in the procedure name and the first letter of each subsequent word in the name. a. procedure case b. camel case c. object case d. Pascal case ANSWER: d

Page 2


Name:

Class:

Date:

Chapter 06 9e 14. In most cases, the last statement within a function is a(n)_________-. a. End expression b. Return statement c. As expression d. PassBack statement ANSWER: b 15. Usually, the statement that invokes a function will assign the function’s return value to a(n) ____. a. address b. argument c. variable d. parameter ANSWER: c 16. Which is a valid Return statement? a. dblNumber Return b. Return dblNumber ByRef c. Return ByRef dblNumber d. Return dblNumber ANSWER: d 17. Which statement invokes the DisplayMessage Sub procedure? a. DisplayMessage() b. DisplayMessage(strItemName, decItemPrice) c. DisplayMessage(decItemPrice, strItemName) d. DisplayMessage(strItemName, decItemPrice) As String ANSWER: b 18. In a __________ combo box, the text portion is not editable. a. Text b. Simple c. DropDown d. DropDownList ANSWER: d

Page 3


Name:

Class:

Date:

Chapter 06 9e 19. An application needs to calculate the total amount a customer owes, including sales tax. You decide to simplify the code by putting the sales tax calculation in a function. The returned value from the function should be added to the subtotal amount, and the result should be stored in the decTotal variable. Which statement will invoke the GetSalesTax function and return a value that can be used when calculating the total amount owed? a. decTotal = decSubtotal + GetSalesTax() b. decSubtotal + GetSalesTax(decSubtotal) c. decTotal = decSubtotal + GetSalesTax(decSubtotal) d. decTotal = decSubtotal + GetSalesTax(decSubtotal As Decimal) ANSWER: c Case-Based Critical Thinking Questions Case 1: MTN Outdoor You have just started working for MTN Outdoor as a programmer. Your first assignment is to review and correct various code to use Sub procedures and/or functions. 20. An application calculates an ending inventory amount based on a beginning inventory amount, sales, and returns. You need to create a function to calculate the ending inventory using three passed Integer variables: intBegin, intSales, and intReturns. Which procedure header should be used? a. Private Function GetEndInventory(ByVal intBegin, ByVal intSales, ByVal intReturns) As Integer b. Private Function GetEndInventory(ByVal intBegin As Integer, ByVal intSales As Integer, ByVal intReturns As Integer) c. Private Function GetEndInventory(ByVal intBegin As Integer, ByVal intSales As Integer, ByVal intReturns As Integer, ByRef intEnd As Integer) As Integer d. Private Function GetEndInventory(ByVal intBegin As Integer, ByVal intSales As Integer, ByVal intReturns As Integer) As Integer ANSWER: d 21. A form’s __________ procedure is often used to verify that the user wants to exit the application. a. Click event b. FormClosing event c. Add event d. Button event ANSWER: b

Page 4


Name:

Class:

Date:

Chapter 06 9e 22. Which statement displays the value returned by the GetNewPrice function? a. dblNewPrice = GetNewPrice(dblCurrentPrice) b. lblNewPrice.Text = GetNewPrice(dblCurrentPrice).ToString("C2") c. GetNewPrice(dblCurrentPrice) d. dblTotalDue = intQuantity * GetNewPrice(dblCurrentPrice) ANSWER: b 23. As you do with list boxes, you use the Items collection’s __________ method to add an item to a combo box. a. Include b. Add c. New d. Append ANSWER: b 24. The expression Math.Round(287.876, 2) yields a value of __________. a. 287.87 b. 287.88 c. 288.00 d. 290.00 ANSWER: b 25. When you pass a variable by __________, the computer passes only a copy of the variable’s value to the receiving procedure. a. reference b. parameter c. dataType d. value ANSWER: d 26. You can associate a procedure with more than one object and event as long as each event contains the same __________ in its procedure header. a. events b. arguments c. constraints d. parameters ANSWER: d

Page 5


Name:

Class:

Date:

Chapter 06 9e 27. Which statement invokes the GetEndInventory function and assigns the function’s return value to the intEnd variable? a. GetEndInventory(intBegInv, intItemsSold, intReturned) b. intEnd = GetEndInventory(intBegInv, intReturned, intItemsSold,) c. intEnd = GetEndInventory(intBegInv, intItemsSold, intReturned) d. intEnd = GetEndInventory() ANSWER: c 28. A(n) __________ is not connected to any object or event, and it is processed only when a statement in your code calls (or invokes) it. a. dependent Sub procedure b. independent Sub procedure c. invoker procedure d. unconnected procedure ANSWER: b 29. An application allows a user to scan a bar code of an item to determine the item price. A message that contains the item name and the item price should display. You need to create a Sub procedure to display the message. Which procedure header should be used? a. Private Sub DisplayMessage(ByVal strItem As String, ByVal decPrice As Decimal) b. Private Sub DisplayMessage(ByVal strItem As String, ByVal decPrice As Decimal) As String c. Private Sub DisplayMessage(ByRef strItem As String, ByRef decPrice As Decimal) d. Private Sub DisplayMessage(ByVal strItem As String, ByRef decPrice As Decimal) ANSWER: a 30. Like the first item in a list box, the first item in a combo box has an index of __________. a. 0 b. 1 c. 2 d. 3 ANSWER: a

Page 6


Name:

Class:

Date:

Chapter 06 9e 31. For a combo box’s access key to work correctly, you must set its identifying label’s TabIndex property to a value that is __________ the combo box’s TabIndex value. a. identical to b. one number less than c. one number more than d. greater than or equal to ANSWER: b 32. An independent Sub procedure’s header usually begins with the keyword __________, which indicates that the procedure can be used only within the class that defines it. a. Is b. To c. Private d. Return ANSWER: c 33. A combo box’s __________ property contains the value that appears in the text portion of the control. a. Add b. Sorted c. Text d. List ANSWER: c 34. Which statement will determine the number of items in the list portion of the combo box named cboDepartment? a. cboDepartment.Count.Items b. cboDepartment.Items.Count c. cboDepartment.Count d. cboDepartment.List.Count ANSWER: b 35. If the digits argument is omitted, the Math.Round method returns a(n) __________. a. zero b. exception c. error d. integer ANSWER: d

Page 7


Name:

Class:

Date:

Chapter 06 9e 36. How many styles of combo boxes are available in Visual Basic? a. two b. three c. four d. five ANSWER: b 37. To sort the items in the list portion of a combo box, you use the combo box’s __________ property. a. Sorted b. Ascending c. Descending d. TabIndex ANSWER: a 38. A ___________ box is similar to a list box in that it allows the user to select from a list of choices. a. text b. message c. combo d. dialog ANSWER: c 39. Which statement assigns the value returned by the GetNewPrice function to a variable? a. dblNewPrice = GetNewPrice(dblCurrentPrice) b. lblNewPrice.Text = GetNewPrice(dblCurrentPrice).ToString c. GetNewPrice(dblCurrentPrice) d. GetNewPrice(dblCurrentPrice) = dblNewPrice ANSWER: a 40. The default combo box style in Visual Basic is __________. a. Text b. Simple c. DropDown d. DropDownList ANSWER: c

Page 8


Name:

Class:

Date:

Chapter 06 9e 41. It is a common practice to begin a procedure’s name with a(n) __________. a. noun b. verb c. adjective d. adverb ANSWER: b 42. Write the code for a Sub procedure named InitializeVariables. The Sub procedure will assign the number 0 to the intTotalCars, intTotalTrucks, and intTotalSuvs variables. Then write the code to call (invoke) the procedure. The calling statement will need to pass the following variables to the InitializeVariables procedure: intCars, intTrucks, and intSuvs. Use the names intTotalCars, intTotalTrucks, and intTotalSuvs for the parameter names. ANSWER: Private Sub InitializeVariables(ByRef intTotalCars As Integer, ByRef intTotalTrucks As Integer, ByRef intTotalSuvs as Integer) intTotalCars = 0 intTotalTrucks = 0 intTotalSuvs = 0 End Sub InitializeVariables(intCars, intTrucks, intSuvs)

Page 9


Name:

Class:

Date:

Chapter 06 9e 43. What are three of the four reasons that programmers use independent Sub procedures? ANSWER: 1. Avoid duplicating code: When different sections of a program need to perform the same task, you can enter the code in a procedure and then have each section call (invoke) the procedure to perform its task when needed. 2. Modify in only one place: If the task performed by an independent Sub procedure subsequently changes, you need to make the modification in only the procedure rather than in all of the sections that use the procedure. 3. Make procedures easier to code and understand: If an event procedure performs many tasks, you can prevent the procedure’s code from getting unwieldy and difficult to understand by assigning some of the tasks to one or more independent Sub procedures. Doing this makes the event procedure easier to code because it allows you to concentrate on one small piece of the code at a time. 4. Allow a team of programmers to code the application: Independent Sub procedures are used extensively in large and complex applications, which typically are written by a team of programmers. The team will break up the application’s code into small and manageable tasks, and then assign some of the tasks to different team members to be coded as independent Sub procedures. Doing this allows more than one programmer to work on the application at the same time, decreasing the time it takes to complete the application.

44. What is a combo box? List the three styles of combo boxes available in Visual Basic. ANSWER: A combo box is similar to a list box in that it offers the user a list of choices from which to select. However, unlike a list box, the list in a combo box can be hidden. Also unlike a list box, a combo box contains a text field that may or may not be editable by the user. The three styles of combo boxes are: 1. Simple 2. DropDown 3. DropDownList

45. When will the TextChanged event occur for a combo box? Which style allows the user to edit the text of the combo box? ANSWER: When the value in the text portion of a combo box changes, the combo box’s TextChanged event occurs. The user can edit the text of a Simple or DropDown style combo box.

Page 10


Name:

Class:

Date:

Chapter 06 9e 46. Write the code to add Freshman, Sophomore, Junior, and Senior to a combo box named cboClass. Use the SelectedItem property to make Freshman the default item. ANSWER: cboClass.Items.Add("Freshman") cboClass.Items.Add("Sophomore") cboClass.Items.Add("Junior") cboClass.Items.Add("Senior") cboClass.SelectedItem = "Freshman"

47. Explain the difference between passing a variable by value and passing it by reference. ANSWER: When you pass a variable by value, the computer passes a copy of the variable’s contents to the receiving procedure. The procedure cannot change the value stored inside the variable because it does not have access to the variable’s memory location. When you pass a variable by reference, you are passing the variable’s memory location in the computer’s internal memory. This method gives the receiving procedure access to the variable being passed. You pass a variable by reference when you want the receiving procedure to change the contents of the variable.

48. What is the Math.Round method? Provide the method’s syntax and define the arguments. ANSWER: The Math.Round method returns a number rounded to a specific number of decimal places. The syntax for the method is: Math.Round(value[, digits]) In the syntax, value is a numeric expression, and digits (which is optional) is an integer indicating how many places to the right of the decimal point are included in the rounding.

Page 11


Name:

Class:

Date:

Chapter 06 9e 49. Write the code for a function named GetMajor. The function should receive a code from the calling statement and then return the associated college major. A code of 1 is Business, code 2 is Computer Science, code 3 is Communications, and code 4 is Nursing. If the code is not 1, 2, 3, or 4, the function should return the message “Invalid code.” Then write a statement to invoke the GetMajor function, passing it a copy of the value stored in the intMajorCode variable and assigning the function’s return value to the strCurrentMajor variable. ANSWER: Private Function GetMajor(ByVal intCode As Integer) As String Dim strMajor As String Select Case intCode Case 1 strMajor = "Business" Case 2 strMajor = "Computer Science" Case 3 strMajor = "Communications" Case 4 strMajor = "Nursing" Case Else strMajor = "Invalid code" End Select Return strMajor End Function strCurrentMajor = GetMajor(intMajorCode)

50. How do the parameterList of a procedure header and the argumentList of a calling (invoking) statement relate to each other? ANSWER: Each parameter in the parameterList stores an item of data to be used by the procedure. The data are passed to the procedure through the calling (invoking) statement’s argumentList. The number, data type, and order (position) of the arguments in the argumentList should agree with the number, data type, and order (position) of the parameters in the parameterList. The names of the arguments do not need to be identical to the names of their corresponding parameters. As a matter of fact, for clarity, it is best to use different names.

Page 12


Name:

Class:

Date:

Chapter 06 9e 51. Write the code for a Sub procedure named CalculateAverage that receives four Decimal variables (the first three by value and the last one by reference). The procedure should use the first three variables to calculate the average and then store the result in the fourth variable. ANSWER: Private Sub CalculateAverage(ByVal decNum1 As Decimal, ByVal decNum2 As Decimal, ByVal decNum3 As Decimal, ByRef decNum4 As Decimal) decNum4 = (decNum1 + decNum2 + decNum3) / 3 End Sub

52. The cboLevel control is a DropDown combo box, which means its text portion is editable. Explain how to verify that the text portion will accept only numbers from 1 through 4. ANSWER: Click the text portion of the Level box and then verify that the text portion will accept only numbers from 1 through 4 and the Backspace key.

53. When a user chooses to type the level number in the text portion of the cboLevel control rather than select it from the list, the text portion should accept only one character. Explain how to modify the combo box to accept only one character. ANSWER: If a user chooses to type the level number in the text portion of the cboLevel control rather than select it from the list, the text portion should accept only one character. Change the cboLevel control’s MaxLength property to 1.

Page 13


Name:

Class:

Date:

Chapter 06 9e 54. Write the code for a function named CalculateBonus. The function receives a copy of the values stored in two Decimal variables, which represent the salary and bonus rate. Use decSalary and decRate as the parameter names. The function should calculate the bonus amount by multiplying the salary by the bonus rate, and then return the result. Then write the appropriate statement to invoke the function, passing it the decEarnings and decBonusRate variables. Assign the function’s return value to the decBonus variable. ANSWER: Private Function CalculateBonus(ByVal decSalary As Decimal, ByVal decRate As Decimal) As Decimal Return decSalary * decRate End Function decBonus = CalculateBonus(decEarnings, decBonusRate)

55. What is the difference between a Sub procedure and a Function procedure? ANSWER: Both Sub procedures and Function procedures are processed only when called (invoked) from code. The difference between a Sub procedure and a Function procedure is that a Function procedure returns a value after performing its assigned task, whereas a Sub procedure does not return a value.

Essay 56. Write the code for a Sub procedure named CalculateBonus. The procedure receives three Decimal variables representing the salary, bonus rate, and bonus amount. The procedure should calculate ANSWER: Private Sub CalculateBonus(ByVal decSalary As Decimal, ByVal decBonusRate As Decimal, ByRef decBonusAmount As Decimal) decBonusAmount = decSalary * decBonusRate End Sub

Page 14


Name:

Class:

Date:

Chapter 06 9e 57. Write the code for a Sub procedure named DisplayAuto, which displays a message containing the two values passed to it: an automobile make and model. Use strMake and strModel as the parameters. Display the “You own a make model.” message in a message box. Then write the statement to invoke the procedure, passing it the contents of the strBrand and strType variables, respectively. ANSWER: Private Sub DisplayAuto(ByVal strMake As String, ByVal strModel As String) MessageBox.Show("You own a " & strMake & " " & strModel & ".") End Sub DisplayAuto(strBrand, strType)

58. At times, an application may need to communicate with the user during run time. Explain how this task is accomplished in Visual Basic. ANSWER: At times, an application may need to communicate with the user during run time. You can accomplish this task by using Visual Basic’s MessageBox.Show method to display a message box. The message box contains text, one or more buttons, and an icon.

Page 15


Name:

Class:

Date:

Chapter 07 9e Indicate whether the statement is true or false. 1. You can use a string’s Value property to determine the number of characters it stores. a. True b. False ANSWER: False 2. If an application expects the user to enter a seven-digit phone number or a five-digit ZIP code, the application’s code should verify that the user entered the required number of characters. a. True b. False ANSWER: True 3. You deactivate a control by setting its Enabled property to False, and you activate it by setting its Enabled property to True. a. True b. False ANSWER: True 4. To generate random numbers, you first need to create a Random object to represent the pseudo-random number generator. a. True b. False ANSWER: True 5. A check digit is used on a credit card number, a bank account number, a product’s UPC (Universal Product Code), and a book’s ISBN (International Standard Book Number). a. True b. False ANSWER: True 6. A literal type character forces a literal constant to assume a data type other than the one its form indicates. a. True b. False ANSWER: False 7. The most common control used to enter a password is a label control. a. True b. False ANSWER: False

Page 1


Name:

Class:

Date:

Chapter 07 9e 8. The Remove method is used to remove characters only from the end of a string. a. True b. False ANSWER: False 9. The Remove method removes characters from the original string. a. True b. False ANSWER: False 10. Visual Basic provides the Replace method for replacing a sequence of characters in a string with another sequence of characters. a. True b. False ANSWER: True 11. When processing the PadLeft and PadRight methods, the computer makes a temporary copy of the string in memory, and then inserts the characters in the copy only. a. True b. False ANSWER: True 12. The PasswordChar property hides the user’s entry by displaying a replacement character, such as an asterisk, in place of the character the user entered. a. True b. False ANSWER: True 13. Each character in a character array, or string, has a unique index that represents its position in the string. a. True b. False ANSWER: True

Page 2


Name:

Class:

Date:

Chapter 07 9e Indicate the answer choice that best completes the statement or answers the question. 14. If the strState variable contains the string "North Dakota", what will the Substring method return in the following expression: strState.Substring(1,2)? a. No b. or c. r d. o ANSWER: b 15. The strPhone variable should contain only numbers and no dashes (-). An error message should display if there is a dash anywhere in the variable. Which If clause conditions will evaluate to True when the variable contains a dash? a. If strPhone.Contains("-") = True Then b. If strPhone.Contains("-") = False Then c. If strPhone Like "-" Then d. If strPhone.Contains(#######) = True Then ANSWER: a 16. The __________ method returns an integer that represents the subString argument’s starting position within the string. a. Insert b. IndexOf c. Contains d. Substring ANSWER: b 17. The txtSalary control contains a dollar sign followed by the number 750. Which statement will assign only the number 750 to the strSalary variable? a. strSalary = txtSalary.Text.TrimStart("$"c) b. strSalary = txtSalary.Text.TrimLeft("$"c) c. strSalary = txtSalary.Text.TrimEnd("$"c) d. strSalary = txtSalary.Text.TrimRight("$"c) ANSWER: a

Page 3


Name:

Class:

Date:

Chapter 07 9e 18. You can use the __________ method to search a string to determine whether it contains a specific sequence of characters. a. Contains b. Insert c. Substring d. SearchFor ANSWER: a 19. The strPassword variable contains eight characters. Which If clause can be used to verify that the password contains six letters followed by two numbers? a. If strPassword.ToUpper = "[A-Z][A-Z][A-Z][A-Z][A-Z][A-Z]##" Then b. If strPassword.ToUpper Like "[A-Z][A-Z][A-Z][A-Z][A-Z][A-Z]##" Then c. If strPassword.ToUpper Matches "[A-Z][A-Z][A-Z][A-Z][A-Z][A-Z]##" Then d. If strPassword.ToUpper Like "??????##" Then ANSWER: b 20. Visual Basic provides the __________ method for accessing any number of characters contained in a string. a. IndexOf b. Insert c. Contains d. Substring ANSWER: d 21. Which is often added to either the beginning or the end of a number to validate the number’s authenticity? a. security digit b. token digit c. verification digit d. check digit ANSWER: d 22. Which object is used to represent the pseudo-random number generator in Visual Basic? a. Random b. Pseudo c. Generator d. Number ANSWER: a

Page 4


Name:

Class:

Date:

Chapter 07 9e 23. How many characters will be removed from the string below? Dim myString as String = "ABCDEFGH" myString = myString.Remove(2, 3) a. one b. two c. three d. four ANSWER: c 24. The Remove method in the following code will remove which characters from the myString variable? Dim myString as String = "ABCDEFGH" myString = myString.Remove(2, 3) a. CD b. BCD c. CDE d. DE ANSWER: c 25. The __________ operator evaluates to True when the string matches the pattern; otherwise, it evaluates to False. a. Like b. Match c. Pattern d. Insert ANSWER: a 26. The __________ method performs a case-sensitive search that returns the Boolean value True when the subString is contained anywhere in the string. a. Insert b. IndexOf c. Contains d. Substring ANSWER: c 27. The syntax of the method that can be used to move the focus to a control during run time is __________. a. object.GetFocus() b. object.SetFocus() c. object.Focus() d. object.FocusThis() ANSWER: c Page 5


Name:

Class:

Date:

Chapter 07 9e Case-Based Critical Thinking Questions Case 1: Human Resources Application An application used by the human resources (HR) department needs to be improved. You need to use various string manipulation properties and methods to ensure that all of the data entered by a user is accurate and stored correctly.

28. Each employee is assigned an employee code, such as F01234, which is stored in the strEmpCode variable. The first character is a letter that indicates the employee’s employment status (F for full-time, P for part-time). The next two characters are numbers that indicate the employee’s department number. The last three characters are numbers representing a unique value for each individual employee. Which of the following statements assigns the employee’s department to the strDept variable? a. strDept = strEmpCode.Substring(0, 1) b. strDept = strEmpCode.Substring(1) c. strDept = strEmpCode.Substring(0, 2) d. strDept = strEmpCode.Substring(1, 2) ANSWER: d 29. The __________ method pads the string on the right, which inserts the padded characters at the end of the string and left-aligns the characters within the string. a. PadEnd b. PadRight c. Padding d. PadAll ANSWER: b 30. If you need to remove characters from only the beginning of a string, you use the __________ method. a. TakeOut b. Delete c. Trim d. TrimStart ANSWER: d 31. To remove characters from only the end of a string, use the __________ method. a. Trim b. TrimBack c. TrimEnd d. TrimRight ANSWER: c Page 6


Name:

Class:

Date:

Chapter 07 9e 32. Which If clause can be used to verify that the strState variable contains a two-letter state ID? a. If strState.ToUpper = "[A-Z][A-Z]" Then b. If strState.ToUpper Matches "[A-Z][A-Z]" Then c. If strState.ToUpper Like "[a-z][a-z]" Then d. If strState.ToUpper Like "[A-Z][A-Z]" Then ANSWER: d 33. The method that removes space or other characters from both ends of a string is the __________ method. a. Trim b. TrimAll c. TrimEnd d. DoubleTrim ANSWER: a 34. Assume that a text box named txtPhoneNumber appears on a form and contains the phone number 414-5555555. What value will the following statement assign to the intNumChars variable: intNumChars = txtPhoneNumber.Length? a. 10 b. 12 c. 18 d. 20 ANSWER: b 35. The __________ allows you to use pattern-matching characters to determine whether one string is equal to another string. a. Insert method b. Like operator c. Contains method d. Match operator ANSWER: b 36. The application needs to process benefits for full-time employees only. Which expression evaluates to True when a full-time employee’s code is stored in the strEmpCode variable? The code contains one letter (either P or F) followed by five numbers. a. strEmpCode.ToUpper Like "[A-Z]#####" b. strEmpCode.ToUpper Like "F####" c. strEmpCode.ToUpper Like "F*" d. strEmpCode.ToUpper Like "F?" ANSWER: c

Page 7


Name:

Class:

Date:

Chapter 07 9e 37. Which is the correct syntax for the Insert method? a. insert.String(startIndex, value) b. insert.String(value, startIndex) c. string.Insert(value, startIndex) d. string.Insert(startIndex, value) ANSWER: d 38. If the strMsg variable contains the string "Happy New Year", what will the IndexOf method return in the following expression: strMsg.IndexOf("New")? a. -1 b. 2 c. 6 d. 7 ANSWER: c 39. The users of the HR application have entered some employee social security numbers (SSNs) with dashes (such as 222-33-4444) and some without dashes (such as 222334444). You need to remove all of the dashes from any SSN that contains dashes. The SSNs are always stored in a variable named strSocial. You will use the __________ method to edit the code so that only numeric characters are stored in the strSocial variable. a. Replace b. Delete c. Trim d. Substring ANSWER: a 40. The __________ method inserts the padded characters at the beginning of a string, which right-aligns the characters within the string. a. PadStart b. PadRight c. PadBegin d. PadLeft ANSWER: d 41. The first argument in the Insert method’s syntax is an integer that specifies a character’s position in a string. The integer is called the character’s _________. a. charPos b. index c. charLoc d. position ANSWER: b Page 8


Name:

Class:

Date:

Chapter 07 9e 42. The HR department has decided to change the finance department number from 04 to 09. If the strEmpCode variable contains the code for a finance department employee, which statement correctly changes the contents of the variable? a. strEmpCode = strEmpCode.Replace("04", "09") b. strEmpCode = strEmpCode.Replace("09", "04") c. strEmpCode = strEmpCode.Remove(1, 2) strEmpCode = strEmpCode.Insert(1, "09") d. strEmpCode = strEmpCode.Remove(0, 2) strEmpCode = strEmpCode.Insert(0, "09") ANSWER: c 43. You can use a control’s __________ method to move the focus to the control during run time. a. Focus b. GoTo c. HighLight d. MoveTo ANSWER: a 44. A text box’s __________ property specifies the maximum number of characters the text box will accept. a. MaxChars b. MaxString c. MaxText d. MaxLength ANSWER: d 45. To insert characters within a string, you use the __________ method. a. Add b. Insert c. Append d. IndexOf ANSWER: b

Page 9


Name:

Class:

Date:

Chapter 07 9e 46. Compare the Contains method and the IndexOf method, both of which determine whether a string contains a specific sequence of characters. ANSWER: Both methods perform a case-sensitive search. The Contains method returns the Boolean value True when the substring is contained anywhere in the string; otherwise, it returns the Boolean value False. The IndexOf method returns an integer: either -1 or a number that is greater than or equal to 0. The -1 indicates that the substring is not contained in the string. A number other than -1 is the character index of the subString’s starting position in the string.

47. Describe the PadLeft method and the PadRight method. ANSWER: The PadLeft method pads the string on the left, which means it inserts the padded characters at the beginning of the string, thereby right-aligning the characters within the string. The PadRight method pads the string on the right, which means it inserts the padded characters at the end of the string and left-aligns the characters within the string.

48. The strSerialNum variable contains the string "DRY259614". Write the Visual Basic statement that assigns the string "259614" from the strSerialNum variable to the strProductCode variable. ANSWER: strProductCode = strSerialNum.Substring(3, 6) OR strProductCode = strSerialNum.Substring(3)

49. Write the Visual Basic statements needed to format decNetPay with two decimal places, pad the formatted variable at the beginning with asterisks until its length is 12, and then insert a dollar sign ($) as the first character. Assign the result to the strNetPayFormat variable. ANSWER: strNetPayFormat = decNetPay.ToString("N2") strNetPayFormat = strNetPayFormat.PadLeft(12, "*"c) strNetPayFormat = strNetPayFormat.Insert(0, "$")

Page 10


Name:

Class:

Date:

Chapter 07 9e 50. The strCityState variable contains the string "AtlantaGA". Write the Visual Basic statements that assign the string "Atlanta" from the strCityState variable to the strCity variable, and assign the string "GA" to the strState variable. ANSWER: strCity = strCityState.Substring(0, 7) strState = strCityState.Substring(7) OR strCity = strCityState.Substring(0, 7) strState = strCityState.Substring(7, 2)

51. Write the Visual Basic statement that inserts “RVI” at the beginning of the string stored in the strPolicyNum variable and assigns it to the strPolicyNum variable. strPolicyNum = "576892" ANSWER: strPolicyNum = strPolicyNum.Insert(0, "RVI")

52. Explain the procedure for allowing a text box to accept a maximum of five characters, with each character entered appearing as an asterisk (*). ANSWER: To limit a text box entry to a maximum of five characters, you need to set the text box’s MaxLength property to the number 5. To have each entered character appear as an asterisk, you need to set the text box’s PasswordChar property to the * character.

Essay 53. Write the Visual Basic statement to assign the number of characters in the txtSsn control’s Text property to the intSSNNumChar variable. ANSWER: intSSNNumChar = txtSsn.Text.Length

Page 11


Name:

Class:

Date:

Chapter 07 9e 54. Write an If clause whose condition evaluates to True when a dash (-) appears anywhere within the strItemNum variable. Use the Like operator. ANSWER: If strItemNum Like "*-*" Then

55. Write a Visual Basic statement that removes the last four digits of the credit card number stored in the strCCNum variable and assigns the modified number to the strCCWithoutLastFour variable. strCCNum = "4456778996352852" ANSWER: strCCWithoutLastFour = strCCNum.Remove(12, 4)

Page 12


Name:

Class:

Date:

Chapter 08 9e Indicate whether the statement is true or false. 1. An advantage of using the For Each…Next statement to process an array is that your code does not need to keep track of the array subscripts or even know the number of array elements. a. True b. False ANSWER: True 2. If a one-dimensional array contains five elements, its Length property contains the number 5 but its highest subscript is 3. a. True b. False ANSWER: False 3. In addition to using the Do…Loop and For…Next statements to code a loop, you can also use the For Each… Next statement. a. True b. False ANSWER: True 4. All of the data in an array must have the same data type. a. True b. False ANSWER: True 5. The variables in an array are stored in consecutive locations in the computer’s main memory. a. True b. False ANSWER: True 6. It is uncommon for programmers to associate the items in a list box with the values stored in an array. a. True b. False ANSWER: False 7. One-dimensional arrays are often used to accumulate related values; these arrays are commonly referred to as accumulator arrays. a. True b. False ANSWER: True

Page 1


Name:

Class:

Date:

Chapter 08 9e 8. You usually declare an array using one of the following keywords: Dim, Private, or Static. a. True b. False ANSWER: True 9. In a one-dimensional array, one variable is distinguished from another using a unique number called an element. a. True b. False ANSWER: False 10. A class-level array may be appropriate if two procedures need access to the same array. a. True b. False ANSWER: True 11. A two-dimensional array resembles a table in that the variables (elements) are in rows and columns. a. True b. False ANSWER: True 12. Each variable in an array has a different name and data type. a. True b. False ANSWER: False 13. Storing data in an array decreases the efficiency of your code. a. True b. False ANSWER: False 14. A simple variable is unrelated to any other variable in memory. a. True b. False ANSWER: True

Page 2


Name:

Class:

Date:

Chapter 08 9e Indicate the answer choice that best completes the statement or answers the question. 15. The syntax __________ assigns either the value entered in the txtSales control (converted to Decimal) or the number 0 to the third element in the decSales array. a. Decimal.TryParse(txtSales.Text, decSales(3)) b. Decimal.TryParse(txtSales.Text, decSales(0)) c. Decimal.TryParse(txtSales.Text, decSales(2)) d. TryParse(txtSales.Text, decSales(1)) ANSWER: c 16. The strRoom and strRate arrays are parallel arrays. If Deluxe is stored in the third element in the strRoom array, where is its rate (115) stored? a. strRate(0) b. strRate(1) c. strRate(2) d. strRate(3) ANSWER: c 17. Consider the following array: Dim intNumbers(,) As Integer = {{1,2},{3,4},{4,5},{6,7},{8,9}} What is the highest row subscript for the intNumbers array? a. 2 b. 3 c. 4 d. 5 ANSWER: c 18. You can use a one-dimensional array’s ________ property to determine the number of elements in the array. a. ElementNumber b. ElementLength c. Length d. StringSize ANSWER: c 19. An array’s __________ method returns an integer that indicates the highest subscript in the specified dimension of the array. a. Sort b. Reverse c. TryParse d. GetUpperBound ANSWER: d Page 3


Name:

Class:

Date:

Chapter 08 9e 20. Which expression refers to the element located in the first row, first column in a two-dimensional array named strProducts? a. strProducts(0, 0) b. strProducts{0, 1} c. strProducts(1, 1) d. strProducts[0, 0] ANSWER: a 21. The following statement will declare a one-dimensional String array. What is the subscript for the first element? Dim strLakes(5) As String a. 0 b. 1 c. 5 d. 6 ANSWER: a 22. If the first row in the array contains Sunday as the day of the week, which statement assigns the daily special of lasagna to Tuesday? a. strDailySpecial(3, 2) = "lasagna" b. strDailySpecial(3, 2) = "lasagna" c. strDailySpecial(2, 1) = "lasagna" d. strDailySpecial(3, 1) = "lasagna" ANSWER: c 23. Based on the statement below, which If clause condition will evaluate to True when the intSub variable contains any valid subscript for the array but evaluate to False otherwise? Dim strColors() As String = {"red", "green", "blue"} a. If intSub > 0 AndAlso intSub < 2 Then b. If intSub >= 0 AndAlso intSub <= 2 Then c. If intSub > 0 AndAlso intSub < 3 Then d. If intSub >= 0 AndAlso intSub <= 3 Then ANSWER: b 24. Assigning initial values to an array is often referred to as __________. a. sorting the array b. populating the array c. assigning the value d. rounding a value ANSWER: b

Page 4


Name:

Class:

Date:

Chapter 08 9e 25. Two or more arrays whose elements are related by their positions in the arrays are referred to as __________ arrays. a. parallel b. two-dimensional c. accumulator d. positional ANSWER: a 26. Which statement assigns the string “Paris” to the element located in the first row, second column in the strCities array? a. strCities(1, 1) = "Paris" b. strCities(0, 1) = "Paris" c. strCities(0, 0) = "Paris" d. strCities(1, 0) = "Paris" ANSWER: b 27. Based on the code below, intScores(3, 1) is initialized to __________. Dim intScores(,) As Integer = {{75, 90}, {9, 25}, {23, 56}, {6, 12}} a. 6 b. 12 c. 23 d. 56 ANSWER: b 28. An array is defined as follows: Dim intNumbers(3) As Integer How many elements does the array have? a. one b. two c. three d. four ANSWER: d 29. The following statement will declare an array that has __________ elements. Dim intAreas(5) As Integer a. four b. five c. six d. seven ANSWER: c Page 5


Name:

Class:

Date:

Chapter 08 9e 30. An array called strState() is declared as follows: Dim strState() As String = {"Ohio", "Michigan", "California", "Arizona"} What is the value of the subscript used to reference “Arizona”? a. 1 b. 2 c. 3 d. 4 ANSWER: c 31. Daily “Chef’s Specials” are stored using two parallel one-dimensional arrays. The days of the week are stored in the strDays array, with Sunday as the first element. The daily special for each day is stored in a parallel array named strSpecial. Which statement assigns Friday’s special, which is rigatoni, to the appropriate element? a. strSpecial(0) = "rigatoni" b. strSpecial(1) = "rigatoni" c. strSpecial(6) = "rigatoni" d. strSpecial(5) = "rigatoni" ANSWER: d 32. Based on the code below, intScores(2, 0) is initialized to __________. Dim intScores(,) As Integer = {{75, 90}, {9, 25}, {23, 56}, {6, 12}} a. 25 b. 23 c. 56 d. 75 ANSWER: b Case-Based Critical Thinking Questions Case 1: Tony’s Pizza & Pasta Tony’s Pizza & Pasta restaurant uses an application to update and display menu items and the related price information. 33. Which statement declares a class-level one-dimensional array named strToppings that has 14 elements to store the 14 available pizza toppings? (The statement will be entered in the form class’s declarations section.) a. Declare strToppings(13) As String b. Private strToppings(13) As String c. Dim strToppings(14) As String d. Private strToppings(14) As String ANSWER: b

Page 6


Name:

Class:

Date:

Chapter 08 9e 34. You have decided that the daily “Chef’s Specials” need to be stored in a two-dimensional array rather than two parallel one-dimensional arrays. When entered in a procedure, which of the following statements declares a procedure-level array named strDailySpecial? The number of rows is based on the number of days in the week. Each row will store the name of the day (for example, Sunday) and the name of that day’s special. a. Dim strDailySpecial(6, 1) As String b. Dim strDailySpecial(7, 2) As String c. Dim strDailySpecial(1, 6) As String d. Dim strDailySpecial(2, 7) As String ANSWER: a 35. Which block of code will process its loop body for each element in the strToppings array, which contains 14 elements with subscripts of 0 through 13? a. Dim intSub As Integer Dim intHighSub As Integer = strToppings.GetUpperBound(0) Do While intSub >= intHighSub MessageBox.Show(strToppings(intSub)) intSub +=1 Loop b. Dim intSub As Integer Dim intHighSub As Integer = strToppings.GetUpperBound(0) For intHighSub = 0 To intSub MessageBox.Show(strToppings(intHighSub)) Next intHighSub c. Dim intSub As Integer Dim intHighSub As Integer = strToppings.GetUpperBound(0) For intHighSub = 0 To intSub MessageBox.Show(strToppings(intHighSub)) Next intHighSub d. Dim intHighSub As Integer = strToppings.GetUpperBound(0) For intSub As Integer = 1 To intHighSub MessageBox.Show(strToppings(intSub)) Next intSub ANSWER: c 36. Which loop allows you to traverse an array without having to specify the highest array subscript? a. Do...Loop b. For...Next c. For Each...Next d. Repeat...All ANSWER: c Page 7


Name:

Class:

Date:

Chapter 08 9e 37. Based on the code below, intScores(2, 1) is initialized to __________. Dim intScores(,) As Integer = {{75, 90}, {9, 25}, {23, 56}, {6, 12}} a. 25 b. 23 c. 56 d. 75 ANSWER: c 38. Based on the code below, intScores(3, 0) is initialized to __________. Dim intScores(,) As Integer = {{75, 90}, {9, 25}, {23, 56}, {6, 12}} a. 6 b. 12 c. 23 d. 56 ANSWER: a 39. Based on the code below, intScores(1, 1) is initialized to __________. Dim intScores(,) As Integer = {{75, 90}, {9, 25}, {23, 56}, {6, 12}} a. 9 b. 25 c. 75 d. 90 ANSWER: b 40. Based on the code below, intScores(0, 0) is initialized to __________. Dim intScores(,) As Integer = {{75, 90}, {9, 25}, {23, 56}, {6, 12}} a. 9 b. 25 c. 75 d. 90 ANSWER: c 41. A(n) __________ is a group of variables that have the same name and data type, and are related in some way. a. subscript b. series c. array d. scalar ANSWER: c

Page 8


Name:

Class:

Date:

Chapter 08 9e 42. When initializing an array in its declaration statement, the initialValues portion of the statement is enclosed in __________. a. [ ] b. { } c. () d. <> ANSWER: b 43. To arrange the values in a one-dimensional array in ascending order, you use the __________ method. a. Array.Arrange b. Array.Ascending c. Array.Sort d. Array.ArrangeAsc ANSWER: c 44. The statement __________ assigns the string “Madrid” to the first element in the strCities array. a. strCities(0) = Madrid b. strCities(0) = "Madrid" c. strCities(1) = Madrid d. strCities(0) = {"Madrid"} ANSWER: b 45. If a one-dimensional array contains five elements, its highest subscript is __________. a. 4 b. 5 c. 6 d. 7 ANSWER: a 46. Which statement assigns the number 20 to the second element in a one-dimensional Integer array named intNumbers? a. intNumbers(2) = 20 b. intNumbers(1) = 20 c. intNumbers(2) = {20} d. intNumbers(1) = {20} ANSWER: b

Page 9


Name:

Class:

Date:

Chapter 08 9e 47. Describe two advantages to using arrays to store data. ANSWER: 1. It’s easier and more efficient to treat related variables in an application as a group. 2. After the data is entered into an array, which is typically done at the beginning of a program, the program can use the data as many times as necessary without having to enter the data again.

48. The following array is declared and initialized: Dim dblMilesPerTrip() As Double = {542, 28, 79.5, 322.6, 114} Write the statements to total the values in the array. Use the For Each…Next statement. ANSWER: Dim dblTotal As Double For Each dblMiles As Double In dblMilesPerTrip dblTotal = dblTotal + dblMiles Next dblMiles You can also use dblTotal += dblMiles rather than dblTotal = dblTotal + dblMiles.

49. The following array is declared and initialized: Dim dblMilesPerTrip() As Double = {542, 28, 79.5, 322.6, 114} Write the statements to sort the values in the array in descending order. ANSWER: Array.Sort(dblMilesPerTrip) Array.Reverse(dblMilesPerTrip)

50. Write the statement that assigns the length of the one-dimensional strBooks array to the intNumElements variable. Then write the statement that assigns the highest subscript in the array to the intHighestSub variable. ANSWER: intNumElements = strBooks.Length intHighestSub = strBooks.GetUpperBound(0)

Page 10


Name:

Class:

Date:

Chapter 08 9e 51. Write the statement to declare a six-element class-level array named strAnimal, and initialize the array with the following values: dog, cat, mouse, bird, snake, and fish. ANSWER: Private strAnimal() As String = {"dog", "cat", "mouse", "bird", "snake", "fish"}

52. Write the statement to declare a four-element procedure-level array named intNum with each element initialized to 0. Then write the statements necessary to add the number 5 to each element in the intNum array. ANSWER: Dim intNum(3) As Integer For intSubscript As Integer = 0 To 3 intNum(intSubscript) += 5 Next intSubscript OR Dim intNum() As Integer = {0, 0, 0, 0} For intSubscript As Integer = 0 To 3 intNum(intSubscript) += 5 Next intSubscript

53. How do the elements in parallel one-dimensional arrays relate to each other? ANSWER: Parallel one-dimensional arrays are two or more arrays whose elements are related by their subscripts (positions) in the arrays. The arrays are parallel because each element in the first array corresponds to the elements located in the same position in the second (and subsequent) array.

Page 11


Name:

Class:

Date:

Chapter 08 9e 54. Write the statement to declare a seven-element procedure-level array named strItemCode with each element initialized to the keyword Nothing. ANSWER: Dim strItemCode(6) As String OR Dim strItemCode() As String = {Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}

55. Write the statements to traverse the one-dimensional strCategory array and display each element’s value in a list box named lstCategory. Use a For Each...Next statement. ANSWER: For Each strCategoryElement As String In strCategory lstCategory.Items.Add(strCategoryElement) Next strCategoryElement

Essay 56. Explain the difference between a simple variable and an array. ANSWER: A simple variable is one that is unrelated to any other variable in memory. An array is a group of related variables that have the same name and data type, and are stored in consecutive memory locations in the computer’s internal memory.

Page 12


Name:

Class:

Date:

Chapter 08 9e 57. Write the statements to traverse the one-dimensional strCategory array and display each element’s value in a list box named lstCategory. Use a Do...Loop statement. ANSWER: Dim intHighestSub As Integer = strCategory.GetUpperBound(0) Dim intSub As Integer Do While intSub <= intHighestSub lstCategory.Items.Add(strCategory(intSub)) intSub = intSub + 1 Loop You can also use intSub += 1 rather than intSub = intSub + 1.

58. Write the statement to declare a five-element procedure-level array named decGpa, and initialize the array with the following values: 2.58, 3.85, 3.6, 1.45, and 2.75. Then write a statement to assign the number 2.55 to the last element in the array. ANSWER: Dim decGpa() As Decimal = {2.58, 3.85, 3.6, 1.45, 2.75} decGpa(4) = 2.55

59. Write the statement to declare a twelve-row, two-column procedure-level array named strLocations, with each element automatically initialized to Nothing. ANSWER: Dim strLocations(11, 1) As String

Page 13


Name:

Class:

Date:

Chapter 09 9e Indicate whether the statement is true or false. 1. Menu title captions should be one word only, with only the first letter capitalized. a. True b. False ANSWER: True 2. In addition to getting data from the keyboard and sending data to the computer screen, an application can also get data from and send data to a file on a disk. a. True b. False ANSWER: True 3. All menu titles in an application can share a single access key. a. True b. False ANSWER: False 4. Files to which information is written are called input files. a. True b. False ANSWER: False 5. When inside an application, you can press Alt+f to open the File menu and then tap the letter x to select the Exit option, which ends the application. a. True b. False ANSWER: True 6. When working in Visual Basic’s designer window to modify a menu, you click Table to add a separator bar (horizontal line). a. True b. False ANSWER: False 7. Although you can create many levels of submenus, it is best to use only one level in your application because including too many layers of submenus can confuse the user. a. True b. False ANSWER: True

Page 1


Name:

Class:

Date:

Chapter 09 9e 8. Ctrl+C and Ctrl+S are used as shortcut keys for the Copy command on an Edit menu and the Save command on a File menu, respectively. a. True b. False ANSWER: True 9. A sales report, a memo, and an employee list are examples of text stored in a sequential access file. a. True b. False ANSWER: True 10. You should assign shortcut keys to every menu item. a. True b. False ANSWER: False 11. The most commonly used properties for a menu element are the Name and Text properties. a. True b. False ANSWER: True 12. The Peek method looks ahead into the file to determine whether the file contains another character to read. a. True b. False ANSWER: True 13. The characters in most input and output files are both read and written in consecutive order, one character at a time, beginning with the first character and ending with the last character. a. True b. False ANSWER: True 14. The Integer.TryParse method can be used to convert an amount read from a sequential access file to the Integer data type. a. True b. False ANSWER: True

Page 2


Name:

Class:

Date:

Chapter 09 9e 15. The ReadToEnd method reads the next line of text in a sequential access file. a. True b. False ANSWER: False Indicate the answer choice that best completes the statement or answers the question. Case-Based Critical Thinking Questions Case 1: Frames Unlimited Frames Unlimited is a wholesaler that specializes in picture frames. The company stores its product information (each item’s number, name, size, and price) in a sequential access file named pictureFrame.txt. 16. The outFile variable stores a StreamWriter object and is associated with the pictureFrame57.txt file. Which statement will close the file, ensuring that the data is saved and making the file available for use elsewhere in the application? a. outFile.Save() b. outFile.CloseFile() c. outFile.Close() d. outFile.CloseAll() ANSWER: c 17. Which of the following opens the employee.txt file for output, creates a StreamWriter object, and assigns the object to the outFile variable? a. outFile = File.CreateText("F:\employee.txt") b. outFile = IO.File.CreateText("F:\employee.txt") c. outFile = File.CreateText("F:\") d. outFile = IO.File.Create("F:\employee.txt") ANSWER: b 18. The purpose of a(n) ____ is to visually group together related items on a menu or submenu. a. separator bar b. list separator c. ellipsis d. menu bar ANSWER: a

Page 3


Name:

Class:

Date:

Chapter 09 9e 19. Which statement is true? a. A menu title’s shortcut keys are assigned in its ShortcutKeys property. b. The Text property stores the menu element’s caption, which is the text that the user sees when working with the menu. c. Access keys allow the user to select a menu item without opening the menu. d. Menu title captions should be more than one word, with all letters capitalized. ANSWER: b 20. Which keys appear to the right of a menu item and allow the user to select an item without opening the menu? a. shortcut b. access c. menu d. caption ANSWER: a 21. Programmers use the ____ property of a menu element to refer to the menu element in code. a. Text b. Name c. Description d. Title ANSWER: b 22. Which statement will write the text “Programming” (without the quotes) to a sequential access file? a. outFile.Write("Programming") b. outFile.Append("Programming") c. outFile.Write{"Programming"} d. outFile.Add["Programming"] ANSWER: a 23. Each menu element is considered a(n) ____ and has a set of properties associated with it. a. class b. character c. object d. string ANSWER: c

Page 4


Name:

Class:

Date:

Chapter 09 9e 24. You can use a list box’s __________ property to sort (organize) the data contained in a sequential access file. a. Alphabetic b. Grouped c. Sorted d. Ordered ANSWER: c 25. The syntax used to declare a StreamWriter variable is ____. a. {Dim|Private} streamWriterVariableName IO.StreamWriter b. {Dim|Private} streamWriterVariableName As IN.StreamWriter c. {Dim|Private} streamWriterVariableName As IO.StreamWriter d. {Dim|Private} streamWriterVariableName As StreamWriter ANSWER: c 26. You can use the ____ method to open a sequential access file for output. a. CreateText b. StreamWriter c. OpenText d. AppendText ANSWER: a 27. Which If clause should be used before opening the pictureFrame.txt input file? a. If IO.File.Exist("pictureFrame.txt") Then b. If IO.File.Exists("pictureFrame.txt") Then c. If IO.File("pictureFrame.txt").Exists Then d. If IO.FileExists("pictureFrame.txt") Then ANSWER: b 28. You can use the ____ method to open a sequential access file for append. a. CreateText b. StreamWriter c. OpenText d. AppendText ANSWER: d

Page 5


Name:

Class:

Date:

Chapter 09 9e 29. Which is the correct declaration statement for a procedure-level variable named inInventory that will be used to read data from a sequential access file? a. Dim inInventory As IO.StreamReader b. Dim inInventory As IO.ReadStream c. Dim inInventory As IO.File.StreamReader d. Dim inInventory As File.ReadStream ANSWER: a 30. After opening a file for input, you can use the ____ method to read the next line of text from the file. a. ReadLine b. CharRead c. ReadTextFile d. TextRead ANSWER: a 31. The ____ method returns the number -1 (a negative 1) when a sequential access file (opened for input) does not contain another character to read. a. Character b. Peek c. Input d. ReadLine ANSWER: b 32. The ____ method writes a newline character after the data in a sequential access file. a. WriteLine b. ReadLine c. Write d. LineChar ANSWER: a 33. Files that are read by the computer are called ____ files. a. storage b. serial c. input d. output ANSWER: c

Page 6


Name:

Class:

Date:

Chapter 09 9e 34. In Visual Basic, you use a(n) ____ to write a stream of characters to a sequential access file. a. CreateText method b. StreamReader object c. StreamWriter object d. AppendText method ANSWER: c 35. Which If clause can be used to determine whether the inventory.txt file exists? a. If IO.File.Exists(inventory.txt) Then b. If IO.Exists("inventory.txt") Then c. If FileExists("inventory.txt") Then d. If IO.File.Exists("inventory.txt") Then ANSWER: d 36. In Visual Basic, you use a ____ control to add one or more menus to a Windows form. a. menu b. title strip c. menu strip d. tool strip ANSWER: c 37. Which statement declares a variable that can be used to open an input file? a. Dim inFile As IO.FileReader b. Dim inFile As IO.StreamReader c. Dim inFile As IO.StreamWriter d. Dim inFile As IO.CharReader ANSWER: b 38. Which statement will read data from a sequential access file? a. inFile.ReadData b. inFile.Peek c. inFile.ReadWrite d. inFile.ReadLine ANSWER: d

Page 7


Name:

Class:

Date:

Chapter 09 9e 39. You should use the ____ method to close a sequential access file as soon as you are finished using it. a. Exit b. Close c. End d. Quit ANSWER: b 40. You need to create a report using the pictureFrame.txt sequential access file. The report should contain a list of all picture frames with a size of 5×7. The report will be saved to another sequential access file named pictureFrame57.txt. Your first step is to ____. a. determine whether the pictureFrame.txt file exists b. open the pictureFrame57.txt file for output using the CreateText method c. declare a StreamReader variable for the input file d. open the pictureFrame.txt file for input using the OpenText method ANSWER: c 41. In Visual Basic, you use a ____ object to read a stream of characters from a sequential access file. a. StreamWriter b. FileReader c. CharReader d. StreamReader ANSWER: d 42. After declaring a StreamReader variable, you can use the ____ method to open a sequential access file for input; doing this automatically creates a StreamReader object. a. OpenText b. AppendText c. CreateText d. None of the other choices is correct. ANSWER: a 43. Which statement will close the sequential access file associated with the outFile variable? a. outFile.End() b. outFile.Quit() c. outFile.Exit() d. outFile.Close() ANSWER: d

Page 8


Name:

Class:

Date:

Chapter 09 9e 44. Which If clause can be used to determine whether the accounts.txt file exists? a. If IO.Exists.File("accounts.txt") Then b. If IO.File.Exists("accounts.txt") Then c. If IO.File("accounts.txt") Then d. If IO.Exists("accounts.txt") Then ANSWER: b 45. Write a declaration statement for a procedure-level variable named outFestival that can store a StreamWriter object. ANSWER: Dim outFestival As IO.StreamWriter

46. Write an If clause that determines whether the sequential access file named contacts.txt exists. If the file exists, open the file, assigning it to a StreamReader variable named inFile. If the file does not exist, display the message “File not found” in a Label control called lblMessage. ANSWER: If IO.File.Exists("contacts.txt") Then inFile = IO.File.OpenText("contacts.txt") Else lblMessage.Text = "File not found" End If

47. Explain the difference between the CreateText method and the AppendText method. ANSWER: You use the CreateText method to open a file for output and use the AppendText method to open it for append. When a file is opened for output, the computer creates a new, empty file to which data can be written. If the file already exists, the computer erases the contents of the file before writing any data to it. When a file is opened for append, on the other hand, new data is written after any existing data in the file. If the file does not exist, the computer creates the file for you. The CreateText and AppendText methods automatically create a StreamWriter object to represent the file in the application.

Page 9


Name:

Class:

Date:

Chapter 09 9e 48. Write the statement to declare a class-level StreamWriter variable named outFile. Also write the code to do the following: open a file named welcome.txt for output, write the string "Hello" (without the quotes) followed by a newline character to the file, and then close the file. ANSWER: Private outFile As IO.StreamWriter outFile = IO.File.CreateText("welcome.txt") outFile.WriteLine("Hello") outFile.Close()

49. Write the statement that would write two columns of text to an output file associated with a StreamWriter variable named outFile. The first column, which contains the data stored in the strStudentID variable, must contain nine characters and be left-aligned in the column. The second column contains the data stored in the strLastName variable. ANSWER: outFile.WriteLine(strStudentID.PadRight(9) & strLastName)

50. Write a statement to declare a procedure-level StreamReader variable named inFile. Also write the code to do the following: verify that the "welcome.txt" file exists and, if it does exist, open the file, read the entire file (all at once) into the txtContents control’s Text property, and then close the file. ANSWER: Dim inFile As IO.StreamReader If IO.File.Exists("welcome.txt") Then inFile = IO.File.OpenText("welcome.txt") txtContents.Text = inFile.ReadToEnd inFile.close() End If

Page 10


Name:

Class:

Date:

Chapter 09 9e 51. Describe menu standards that should be followed when including a menu in an application. ANSWER: Menu title captions should be one word with only the first letter capitalized. Each menu title should have a unique access key. Menu item captions can be from one to three words. Use book title capitalization and assign a unique access key to each menu item on the same menu. Assign unique shortcut keys to commonly used menu items. If a menu item requires additional information from the user, place an ellipsis (...) at the end of the item’s caption, which is entered in the item’s Text property. Follow the Windows standards for the placement of menu titles and items. Use a separator bar to separate groups of related menu items.

52. Write the code to declare a procedure-level variable named outFile that can be used to write data to a sequential access file. Then write the statement to open a sequential access file named customers.txt for output. ANSWER: Dim outFile As IO.StreamWriter outFile = IO.File.CreateText("customers.txt")

53. What is the difference between a menu item’s access key and its shortcut key? ANSWER: The access key allows the user to select the item by pressing the access key. A menu item’s access key can be used only when the menu is open. The shortcut keys appear to the right of a menu item. A menu item’s shortcut key can be used without opening the menu.

54. Write the code to declare a procedure-level variable named outFile that can be used to write data to a sequential access file. Then write the statement to open a sequential access file named samples.txt, allowing new data to be written to the file after any existing data in the file. ANSWER: Dim outFile As IO.StreamWriter outFile = IO.File.AppendText("samples.txt")

Page 11


Name:

Class:

Date:

Chapter 09 9e 55. Write the code to declare a variable named inFile that can be used to read data from a sequential access file. Then write the statement to open a sequential access file named samples.txt for input. ANSWER: Dim inFile As IO.StreamReader inFile = IO.File.OpenText("samples.txt")

56. A sequential access file contains customer names, with each name written on a separate line in the file. Write a Do...Loop statement that reads each customer’s name from the file, one name at a time, and displays each name on a separate line in a text box named txtCustomers. Process the loop until the end of the file has been reached. The file is associated with a StreamReader variable named inFile. ANSWER: Do Until inFile.Peek = -1 txtCustomers.Text = txtCustomers.Text & inFile.ReadLine & ControlChars.NewLine Loop OR Do While inFile.Peek <> -1 txtCustomers.Text = txtCustomers.Text & inFile.ReadLine & ControlChars.NewLine Loop

57. question type="essay"> 57. Describe what the MenuStrip tool does. ANSWER: The MenuStrip tool instantiates a menu strip control, which allows you to add one or more menus to a Windows form. Each menu contains a menu title, which appears on the menu bar at the top of the form.

Page 12


Name:

Class:

Date:

Chapter 09 9e Essay 58. What is the difference between an input file and an output file? ANSWER: Files that are read by the computer are called input files because an application uses the data in these files as input. Files to which data are written are called output files because these files store the output produced by an application.

Page 13


Name:

Class:

Date:

Chapter 10 9e Indicate whether the statement is true or false. 1. The convention is to use Pascal case for class names. a. True b. False ANSWER: True 2. A class is anything that can be seen, touched, or used; in other words, a class is nearly any thing. a. True b. False ANSWER: False 3. A class itself is an object. a. True b. False ANSWER: False 4. Constructors never return a value, so they are always function procedures. a. True b. False ANSWER: False 5. A one-dimensional array’s Length property is an example of a ReadOnly property. a. True b. False ANSWER: True 6. A parameterized constructor allows an application to specify the object’s initial values. a. True b. False ANSWER: True 7. An application must use a Public property procedure to refer to a Private member variable in a class. a. True b. False ANSWER: True

Page 1


Name:

Class:

Date:

Chapter 10 9e 8. A good class is one that is created for one specific application. a. True b. False ANSWER: False 9. When an application uses the class to instantiate an object, the Private member variables will be visible to the application. a. True b. False ANSWER: False 10. An application can use a Private property procedure to refer to the Private variables in a class. a. True b. False ANSWER: False 11. A class can have multiple default constructors. a. True b. False ANSWER: False 12. You can overload any of the methods contained in a class. a. True b. False ANSWER: True Indicate the answer choice that best completes the statement or answers the question. 13. The Class statement ends with the keyword(s) ____. a. Class b. Exit Class c. End Class d. Next Class ANSWER: c

Page 2


Name:

Class:

Date:

Chapter 10 9e 14. A(n) ____ is a class method whose sole purpose is to initialize the class’s Private variables. a. signature b. constructor c. Get block d. event ANSWER: b 15. The Chaussure application needs to use the Shoe class, which creates an object that represents a standard shoe. You have copied the Shoe.vb class file to the Chaussure Project folder. What do you need to do next to allow the application to access the file’s contents? a. Click Project on the menu bar and then click Add Existing Item. b. Click Add on the menu bar and then click Class. c. Click Project on the menu bar and then click Add Class. d. Click Class on the menu bar and then click Add. ANSWER: a 16. A class’s Public Discount property is made ReadOnly. The class’s Public DetermineDiscount method stores the appropriate discount amount in the Private variable associated with the property. Which of the following is true about this ReadOnly property? a. The property will contain a Set block of code in its Property procedure. b. If an application uses the class to instantiate an object, the application can use the object to assign a value to the Discount property. c. An application that uses the class to instantiate an object will only be able to retrieve (read) the Discount property’s value. d. Only the DetermineDiscount method can retrieve (read) the Discount property’s value. ANSWER: c 17. The Tree class contains a Public method named GetCategory. The method is a function. An application instantiates a Tree object and assigns it to a variable named park. Which of the following can be used by the application to invoke the GetCategory method, assigning its return value to the strCategory variable? a. strCategory = Tree.GetCategory b. strCategory = park.GetCategory c. strCategory = GetCategory.park d. strCategory = GetCategory(Tree.park) ANSWER: b

Page 3


Name:

Class:

Date:

Chapter 10 9e 18. Visual Basic’s auto-implemented property feature enables you to ____. a. make the property ReadOnly b. add validation code to the Set block c. make the property WriteOnly d. specify the property of a class in one line of code ANSWER: d 19. A Property procedure’s header begins with the keywords ____, where keywords in brackets are optional. a. Public [ReadOnly | WriteOnly] Property b. Private [ReadOnly | WriteOnly] Property c. Start [ReadOnly | WriteOnly] Property d. Dim [ReadOnly | WriteOnly] Property ANSWER: a 20. A _____ is a pattern that the computer follows when instantiating (creating) an object. a. constructor b. property c. class d. structure ANSWER: c 21. How many default constructors can a class have? a. none b. only one c. one or more, but fewer than three d. as many as it needs ANSWER: b 22. A constructor that has no parameters is called the ____ constructor. a. empty b. default c. parameterized d. Set ANSWER: b

Page 4


Name:

Class:

Date:

Chapter 10 9e 23. Constructors that contain parameters are called ____ constructors. a. filled b. default c. information d. parameterized ANSWER: d 24. Every object has ____, which are the characteristics that describe the object. a. events b. methods c. attributes d. behaviors ANSWER: c 25. Which of the following instantiates a Product object and assigns it to the bookcase variable? a. Dim bookcase As Product b. Dim bookcase As New Product c. Dim Product As bookcase d. Dim bookcase As String ANSWER: b 26. How many parameterized constructors can a class have? a. none b. only one c. one or more, but fewer than three d. as many as it needs ANSWER: d 27. A method name combined with its optional parameterList is called the method’s ____. a. signature b. event c. attribute d. behavior ANSWER: a

Page 5


Name:

Class:

Date:

Chapter 10 9e 28. When two or more methods have the same name but different parameters, the methods are referred to as ____ methods. a. uniform b. parallel c. overloaded d. interchangeable ANSWER: c 29. You create a Public property using a ____. a. Sub procedure b. Function procedure c. Property procedure d. Set block ANSWER: c 30. In a Property procedure, the code contained in the ____ block allows an application to retrieve the contents of the Private variable associated with the property. a. Set b. Assign c. New d. Get ANSWER: d Case-Based Critical Thinking Questions

Case 1: Chaussure.com

Chaussure.com is an online shoe retailer. The applications for the web site are developed using classes and object-oriented programming techniques. 31. Which is a valid example of an object? a. a Place Order button in an application b. a credit card receipt c. a text box to enter the credit card number in an application d. all of the above ANSWER: d

Page 6


Name:

Class:

Date:

Chapter 10 9e 32. The purpose of a(n) ____ in OOP is to encapsulate all of the attributes and behaviors of the object it instantiates. a. event b. class c. method d. attribute ANSWER: b 33. Only items declared using the keyword Public will be _________ the application. a. kept private from b. required by c. written to d. exposed to ANSWER: d 34. A Property procedure’s dataType must match the data type of ____ associated with the Property procedure. a. all constructors b. all variables c. the Public variable d. the Private variable ANSWER: d 35. Overloaded methods have __________. a. the same name and the same parameters b. different names and the same parameters c. the same name and different parameters d. different names and different parameters ANSWER: c 36. Which statement creates a class-level variable to represent a TimeCard object? a. Instantiate hoursInfo As TimeCard b. Class hoursInfo As TimeCard c. Create hoursInfo As TimeCard d. Private hoursInfo As TimeCard ANSWER: d

Page 7


Name:

Class:

Date:

Chapter 10 9e 37. A(n) ____ property gets its value from the class itself, rather than from an application that uses the class to instantiate an object. a. WriteOnly b. ReadOnly c. AssignOnly d. ClassOnly ANSWER: b 38. The code in a Property procedure’s ____ allows an application to assign a value to the Private variable associated with the property. a. Get block b. Assign block c. Set block d. Value block ANSWER: c 39. The names of methods should begin with a(n) ____. a. verb b. noun c. adjective d. preposition ANSWER: a 40. The Library class contains an auto-implemented property named TaxRate. Which is the correct way for the default constructor to assign the number 0 to the variable associated with the property? a. Library.TaxRate = 0 b. _TaxRate = 0 c. TaxRate = 0 d. TaxRate.Library = 0 ANSWER: b 41. ____ is useful when two or more methods require different parameters to perform essentially the same task. a. Instantiation b. Overloading c. Encapsulation d. Reiterating ANSWER: b

Page 8


Name:

Class:

Date:

Chapter 10 9e 42. ____ are the actions to which an object can respond. a. Attributes b. Events c. Behaviors d. Methods ANSWER: b 43. ____ are the operations (actions) that the object is capable of performing. a. Events b. Attributes c. Behaviors d. Methods ANSWER: d 44. If you create an auto-implemented property named State, Visual Basic will create a hidden Private variable named ____. a. State b. _State c. STATE d. state_ ANSWER: b 45. How does a ReadOnly property get its value? ANSWER: A ReadOnly property gets its value from the class itself rather than from the application. The ReadOnly keyword in a Property procedure’s header indicates that the property’s value can only be retrieved (read) by an application; the application cannot set (write to) the property.

Page 9


Name:

Class:

Date:

Chapter 10 9e 46. Explain the difference between the Public and Private members of a class. ANSWER: The Public members declared in a class can be accessed by any application that contains an instance of the class. The Public members are exposed to the application, whereas the Private members are hidden from the application. The Private members are not visible to applications that contain an instance of the class. A class’s Private members can be used only by instructions within the class itself. If an application needs to access a Private member variable in a class, it must use a Public property provided by the class.

47. When is a Class statement used? ANSWER: You define a class using the Class statement, which you enter in a class file. Although it is not a requirement, the convention is to use Pascal case for the class name. The names of Visual Basic classes follow this naming convention.

48. What are classes and objects? How are they used in object-oriented programming? ANSWER: An object is anything that can be seen, touched, or used. It is nearly any thing. A class is a pattern that the computer uses to create the object. Every object in an object-oriented program is created from a class. Each object is then referred to as an instance of the class. The class itself is not an object; only an instance of a class is an object.

49. What is typically contained in the attributes section of a Class statement? ANSWER: The attributes section of a Class statement typically contains the declaration statements for one or more variables, referred to as member variables. Each member variable represents an attribute of the object that the class will create.

Page 10


Name:

Class:

Date:

Chapter 10 9e 50. Define the term “encapsulates.” Specifically, how is it used in object-oriented programming? ANSWER: The term “encapsulates” means to enclose in a capsule. In the context of OOP, the “capsule” is a class. The class encapsulates all of the attributes and behaviors of the object it instantiates.

Essay 51. Define the term object-oriented programming language. ANSWER: Visual Basic is an object-oriented programming language, which is a language that allows the programmer to use objects in an application’s interface and also in its code. In object-oriented programming, or OOP, an object is anything that can be seen, touched, or used. In other words, an object is nearly any thing.

52. Every object has attributes and behaviors. Describe each of these, including the two types of behaviors an object can have. ANSWER: The attributes of an object are the characteristics that describe the object. They are also called properties. Every object also has behaviors. The two types of behaviors are methods and events. Methods are the operations (actions) that the object is capable of performing. Events are the actions to which an object can respond, such as a Click event for a button object.

53. What is a constructor? ANSWER: A constructor is a class method, always named New, whose sole purpose is to initialize the Private variables declared in the class. Constructors never return a value, so they are always Sub procedures rather than functions.

Page 11


Name:

Class:

Date:

Chapter 10 9e 54. Explain the difference between a default constructor and a parameterized constructor. ANSWER: A default constructor is a constructor that has no parameters. A parameterized constructor contains one or more parameters.

55. What is an auto-implemented property and what does it automatically create? ANSWER: An auto-implemented property enables you to specify the property of a class in one line of code. Visual Basic then automatically creates a hidden Private variable that it associates with the property. It also automatically creates hidden Get and Set blocks. The Private variable’s name will be the same as the property’s name, but it will be preceded by an underscore.

Page 12


Name:

Class:

Date:

Chapter 11 9e Indicate whether the statement is true or false. 1. The Data Source Configuration Wizard allows you to specify the data you want to access from the file. a. True b. False ANSWER: True 2. Each column in a table represents a record and each row represents a field. a. True b. False ANSWER: False 3. You can drag the vertical lines in the column headers to adjust a column’s width. a. True b. False ANSWER: True 4. Most databases are created and manipulated using relational database management systems. a. True b. False ANSWER: True 5. Visual Basic’s String data type is associated with two SQL Server data types: char(n) and varchar(n). a. True b. False ANSWER: True 6. A data form typically does not provide text boxes for entering data; they must be added manually. a. True b. False ANSWER: False 7. The computer can retrieve data stored in a relational format both quickly and easily, but the data must be displayed in a specific order. a. True b. False ANSWER: False

Page 1


Name:

Class:

Date:

Chapter 11 9e 8. When you drag an object from a dataset in the Data Sources window to an empty area on the form, the computer creates a control and automatically binds the object to it. a. True b. False ANSWER: True 9. A field that is a primary key should never be empty. a. True b. False ANSWER: True 10. When you drag an object from a dataset in the Data Sources window to an existing control, the computer does not create a new control; rather, it merely binds the object to the existing control. a. True b. False ANSWER: True 11. A relational database can contain one or more tables. a. True b. False ANSWER: True 12. If a table object’s control type is changed from DataGridView to Details, the computer automatically provides appropriate controls. a. True b. False ANSWER: True 13. If you do not take deliberate steps in your code to handle exceptions, Visual Basic “handles” them for you. a. True b. False ANSWER: True 14. A database file contained in a project is referred to as a logic database file. a. True b. False ANSWER: False

Page 2


Name:

Class:

Date:

Chapter 11 9e 15. To bind label and text box controls, you use the DataBindings/Text property. a. True b. False ANSWER: True Indicate the answer choice that best completes the statement or answers the question. 16. You are responsible for connecting the database that contains the tblCustomer table to an application. You must first use the Data Source Configuration Wizard to ____. a. select the table and/or fields to include in the dataset b. add the database file as a new data source c. preview the contents of the dataset d. bind the controls to the dataset ANSWER: b 17. Which method determines whether the field contains the NULL value? a. CheckfieldNull b. IsfieldNull c. VerifyfieldNull d. CorefieldFull ANSWER: b 18. The ____ object provides the connection between the DataSet and the bound controls on the form. a. TableAdapter b. DataGridView c. BindingSource d. BindingNavigator ANSWER: c 19. Which data type would you use for the InvoicePaid field in the tblCustomer table? a. char(1) b. varchar(10) c. char(A-F) d. varchar(A-F) ANSWER: a

Page 3


Name:

Class:

Date:

Chapter 11 9e 20. When an error occurs in a procedure’s code during run time, programmers say that the procedure ____. a. "dumped an exception" b. "ran into an exception" c. "threw an exception" d. "stopped with an exception" ANSWER: c 21. The ____ statement is used for exception handling in a procedure. a. Try…Catch b. Catch...Error c. Try...Exception d. Handle...Exception ANSWER: a 22. A(n) ____ is an electronic file that contains an organized collection of related information. a. field b. computer database c. dataset d. exception ANSWER: b 23. A field that typically refers to a primary key in another table is called a ____. a. exception b. foreign key c. primary key d. cell ANSWER: b 24. In a DataGridView control, you can format a bound column’s data using the column’s ____ property. a. AutoSizeColumnsMode b. DefaultCellStyle c. BindingNavigator d. StyleFormat ANSWER: b

Page 4


Name:

Class:

Date:

Chapter 11 9e 25. The combination of related fields creates a(n) ____. a. object b. dataset c. record d. exception ANSWER: c 26. The ____ object is responsible for retrieving the appropriate information from the database and storing it in the DataSet. a. TableAdapter b. BoundControl c. BindingSource d. DataGridView ANSWER: a 27. The intersection of a row and a column in a DataGridView control is called a ______. a. cell b. table c. record d. key ANSWER: a 28. You can use the ____ Wizard to connect an application to a database file. a. Data Source b. Database Configuration c. Data Source Configuration d. Data Set ANSWER: c 29. The Query Builder dialog box creates queries using a language called ____. a. BSL (Basic Structured Language) b. SQL (Structured Query Language) c. DQL (Dataset Query Language) d. QBL (Query Builder Language) ANSWER: b

Page 5


Name:

Class:

Date:

Chapter 11 9e 30. To create a DataGridView control on the form, you would click on the ____ object in the Data Sources window and drag it to the form. a. CustomerNum b. InvoiceNum c. tblCustomer d. You cannot click on and drag an object to create a DataGridVView control. ANSWER: c 31. The field used to link a child table to a parent table is known as the ____. a. record b. foreign key c. cell d. primary key ANSWER: b 32. You need to make sure the user of the application can add records to, but not delete records from, the dataset. Which of the following needs to be performed? a. The Enable Adding check box on the DataGridView control’s task list must be selected. b. The Disable Deleting check box on the DataGridView control’s task list must be selected. c. The Enable Deleting check box on the DataGridView control’s task list must be selected. d. Both the Enable Adding check box and the Disable Deleting check box on the DataGridView control’s task list must be selected. ANSWER: a 33. When an exception occurs in the Try block's code, a description of the exception is stored in the ____________ of the Catch block’s ex parameter. a. Error property b. Exception property c. Message property d. Try property ANSWER: c 34. The ____ can be used to save any changes made to the data contained in the DataSet to the database. a. TableAdapterManager b. SaveDataSet c. BindingSource d. DataGridView ANSWER: a

Page 6


Name:

Class:

Date:

Chapter 11 9e 35. A group of related records is called a ____. a. table b. field c. datagrid d. primary key ANSWER: a 36. The way Visual Basic saves changes to a local database file is determined by the file’s ____ property. a. Do Not Copy b. Copy Always c. Copy If Newer d. Copy to Output Directory ANSWER: d 37. If a user is not allowed to add a record, you should deselect the ____ check box on the DataGridView control’s task list. a. Enable Adding b. Enable Deleting c. Edit Items d. AddNewItem ANSWER: a 38. The BindingSource object provides the connection between the DataSet and the ____ on the form. a. database b. bound controls c. TableAdapter d. BindingNavigator ANSWER: b

Page 7


Name:

Class:

Date:

Chapter 11 9e Case-Based Critical Thinking Questions Case 1: MaidToOrder The database for a cleaning service company contains a table named tblCustomer. The table contains five fields pertaining to customer invoices. The InvoiceNum, CustomerNum, and InvoicePaid fields contain text. The InvoiceDate field contains dates. The InvoiceAmt field contains numbers that might be used in a calculation. InvoiceNum 631 632 633 634 635 636 637 638

CustomerNum 13020 15411 10002 13104 12124 13328 10206 10334

InvoiceDate 01/15/2013 01/20/2013 01/23/2013 01/23/2013 01/26/2013 02/02/2013 02/02/2013 02/07/2013

InvoiceAmt 200.00 685.00 75.00 150.00 75.00 350.00 175.00 450.00

InvoicePaid Y Y N N Y Y N Y

39. Given the data in the tblCustomer table, which data type would you use for the InvoiceAmt field a. char(3, 2) b. char(5, 2) c. decimal(3, 2) d. decimal(5, 2) ANSWER: d 40. A ____ is a single item of information about a person, place, or thing. a. table b. record c. dataset d. field ANSWER: d 41. Which is not true regarding the Query Builder dialog box? a. The table and its related fields are displayed in the Diagram pane. b. The SQL statement appears in the Query pane. c. The information retrieved by the query appears in the Results pane. d. You must click the Execute Query button for the query to run. ANSWER: b

Page 8


Name:

Class:

Date:

Chapter 11 9e 42. After you click the Execute Query button in the Query Builder dialog box, the information retrieved by the query is displayed in the ____ pane of the dialog box. a. Diagram b. SQL c. Data d. Results ANSWER: d 43. Most databases are created and manipulated using RDBMSs, and are called _____ because the information in them can be associated in different ways. a. relational databases b. objects c. bound controls d. datasets ANSWER: a 44. The TableAdapter object connects the ____ . a. database to the DataSet object b. database to the BindingSource object c. DataSet object to the bound controls d. field to the row ANSWER: a 45. Connecting a field object from a dataset to a control on a form is called ____. a. linking b. attaching c. wrapping d. binding ANSWER: d 46. When an application is running, you can use the ____ control to move from one record to the next in the dataset, as well as to add or delete a record and save any changes made to the dataset. a. DataSet b. BindingNavigator c. TableAdapter d. BindingSource ANSWER: b

Page 9


Name:

Class:

Date:

Chapter 11 9e 47. What is the BindingNavigator control? How is it used? ANSWER: When an application is running, you can use the BindingNavigator control to move from one record to the next in a dataset, as well as to add or delete a record and save any changes made to the dataset.

48. Explain what a data form is. What are its advantages over a DataGridView control? ANSWER: A data form typically provides text boxes for entering data, and it allows the user to enter or display one complete row of information without scrolling horizontally.

49. Relational databases contain multiple tables that relate to each other in some way. How are primary and foreign keys used in such a database? ANSWER: Most tables have a primary key, which is a field that uniquely identifies each record in the table. When two tables are related, a common field relates the tables to each other. The common field will exist in both tables. The common field in the first table is the primary key in that table, and it is used to uniquely identify each record in the table. The common field in the second table is referred to as the foreign key because it links the record back to the first table.

50. What are the advantages to storing data in a relational database? ANSWER: The computer can retrieve data stored in a relational format quickly and easily. The data can be displayed in any order. You can control the amount of information you want to view from a relational database by limiting the number of fields and records to only those that meet a specified criteria.

Page 10


Name:

Class:

Date:

Chapter 11 9e 51. List and describe the values that can be assigned to a file’s Copy to Output Directory property. ANSWER: Do not copy: The file in the project folder is not copied to the bin\Debug folder when the application is started. Copy always: The file in the project folder is copied to the bin\Debug folder each time the application is started. Copy if newer: When an application is started, the computer compares the date on the file in the project folder with the date on the file in the bin\Debug folder. The file from the project folder is copied to the bin\Debug folder only when its date is newer.

Essay 52. Define the following three terms: record, field, and table. Provide examples of each term when you are defining them. ANSWER: A field is a single item of information about a person, place, or thing, such as a name, a salary amount, or a Social Security number. A record is a group of related fields that contain all of the necessary data about a specific person, place, or thing. An individual student is an example of one record. A group of related records is a table. A student table in a database would contain all of the data stored for each student at a college. Each student record in the student table contains the same fields, such as student ID, first name, last name, and so forth.

53. What is the DataGridView control and how is it used? ANSWER: The DataGridView control is one of the most popular controls for displaying table data because it allows you to view a great deal of information at the same time. The control displays the data in a row and column format, similar to a spreadsheet. Each row represents a record and each column represents a field.

Page 11


Name:

Class:

Date:

Chapter 11 9e 54. Explain the easiest way you can bind an object in a dataset to an existing control on a form. ANSWER: The easiest way to do this is by dragging the object from the Data Sources window to the control. However, you also can click the control and then set one or more properties in the Properties window. The appropriate property (or properties) to set depends on the control you are binding.

55. Define BindingSource object. ANSWER: The BindingSource object provides the connection between the DataSet and the bound controls on the form.

Page 12


Name:

Class:

Date:

Chapter 12 9e Indicate whether the statement is true or false. 1. The default order of the ORDER BY clause is descending. a. True b. False ANSWER: False 2. The statement SELECT YearWon, Title, ProductionCo FROM tblMovies WHERE YearWon >= 2006 selects three fields from records for the year 2006 and later. a. True b. False ANSWER: True 3. You save a query that contains the SELECT statement by associating the query with one or more methods. a. True b. False ANSWER: True 4. Most of the time, you will know in advance the values to include in the criteria of a query. a. True b. False ANSWER: False 5. You can use the SELECT statement to add a calculated field to a dataset. a. True b. False ANSWER: True 6. The keywords SELECT, FROM, and WHERE in a SELECT statement must be capitalized. a. True b. False ANSWER: False 7. You click the Execute Query button to run a query. a. True b. False ANSWER: True

Page 1


Name:

Class:

Date:

Chapter 12 9e 8. The statement SELECT YearWon FROM tblMovies WHERE Title = 'Chicago' selects the Chicago field from the YearWon record. a. True b. False ANSWER: False 9. In the Properties window, you click the plus box next to the (Data Bindings) property, then click (Advanced), and then click the … (ellipsis) button to open the Formatting and Advanced Binding dialog box. a. True b. False ANSWER: True 10. The Query Builder places the WHERE clause’s condition in parentheses because the parentheses are required in a SELECT statement. a. True b. False ANSWER: False 11. For an application to use a query during run time, you need to save the query and then invoke it from code. a. True b. False ANSWER: True 12. You use the SQL QUERY statement to query a database. a. True b. False ANSWER: False 13. The WHERE statement is the most commonly used statement in SQL. a. True b. False ANSWER: False Indicate the answer choice that best completes the statement or answers the question. 14. When the LIKE operator is used in a WHERE clause, the _____ wildcard represents zero or more characters. a. % b. & c. * d. @ ANSWER: a Page 2


Name:

Class:

Date:

Chapter 12 9e 15. When you don’t know the specific value to include in the criterion, you use a ____ query. a. limited b. tagged c. unfilled d. parameter ANSWER: d 16. Which SELECT statement will select the ItemNum and ItemDesc fields from the Items table? a. SELECT ItemNum OR ItemDesc FROM Items b. SELECT ItemNum AND ItemDesc FROM Items c. SELECT ItemNum, ItemDesc IN Items d. SELECT ItemNum, ItemDesc FROM Items ANSWER: d 17. The parameter marker in a parameter query is a(n) ____ followed by a field name. a. @ b. * c. & d. % ANSWER: a 18. You use the SELECT statement’s ____ clause, which contains a condition, to limit the records you want to access. a. ORDER BY b. WHERE c. WHICH d. ACCESS ANSWER: b 19. In the Query Builder’s Diagram pane, which of the following indicates that a field is a primary key? a. the field’s name is boldfaced b. the field’s name is italicized c. a funnel symbol appears next to the field’s name d. an asterisk appears next to the field’s name ANSWER: a

Page 3


Name:

Class:

Date:

Chapter 12 9e 20. The NatBookAwards table contains four fields: Title, Author, Category, and Year. Which statement will select the names of the authors for a certain year? a. SELECT Author FROM NatBookAwards WHERE Year = @Year b. SELECT Author @NatBookAwards WHERE Year = @Year c. SELECT Author FROM NatBookAwards IF Year = @Year d. SELECT Author FROM @NatBookAwards WHERE Year = Year ANSWER: a 21. In the Query Builder’s Grid pane, the Price field’s Filter column contains the following: >= @Price. What will the corresponding SQL be in the SQL pane? a. WHERE (>= Price) b. WHERE (Price >= @Price) c. WHERE (Price >= Price) d. WHERE (Price >= !Price) ANSWER: b

Page 4


Name:

Class:

Date:

Chapter 12 9e Case-Based Critical Thinking Questions Case 1: LuvUrPet The database for a pet supply company includes the following table, named tblCollar, that contains product data for pet collars. The ItemDesc and Color fields contain text. The ItemNum, Price, and Quantity fields contain numbers. ItemNum 2358 2693 3547 3855 3764 5782 5785 5787

ItemDesc leather studded collar leather collar striped collar striped collar striped collar solid collar solid collar solid collar

Color

Price

Quantity

black

30.00

35

brown red blue green pink red blue

25.00 20.00 15.00 15.00 12.00 12.00 10.00

25 75 42 48 36 10 15

22. Which statement would select the ItemDesc and Price fields from tblCollar for all records whose ItemDesc field begins with the word “leather” followed by zero or more characters? a. SELECT ItemDesc, Price FROM tblCollar WHERE ItemDesc LIKE 'leather %' b. SELECT ItemDesc, Price FROM tblCollar WHERE ItemDesc LIKE 'leather @' c. SELECT ItemDesc, Price FROM tblCollar WHERE ItemDesc LIKE 'leather *' d. SELECT ItemDesc, Price FROM tblCollar WHERE ItemDesc LIKE 'leather #' ANSWER: a 23. Which is not true regarding parameter queries? a. A parameter query contains a parameter marker in place of a specific value. b. The WHERE clause of a parameter query can contain more than one parameter marker for the same field. c. A parameter query will not allow a user to retrieve different records at different times. d. The parameter marker typically used in SQL is the @ (at) symbol followed by the name of the field you are querying. ANSWER: c

Page 5


Name:

Class:

Date:

Chapter 12 9e 24. An application should query the tblCollar table using the price entered by the user during run time. Which WHERE clause would allow a user to select the records for collars with a price of 15 or more? a. WHERE Price = 15 b. WHERE Price LIKE 15 c. WHERE Price >= @Price d. WHERE Price < @Price ANSWER: c 25. A SQL ____ function returns a single value from a group of values. a. aggregate b. calculate c. parameter d. WHERE ANSWER: a 26. The ____ provides an easy way of saving a query by associating it with one or more methods. a. Query Configuration Wizard b. TableAdapter Modification Wizard c. TableAdapter Dataset Configuration Wizard d. TableAdapter Query Configuration Wizard ANSWER: d 27. In the Query Builder’s Diagram pane, which symbol indicates that a field is used to filter records? a. question mark b. funnel c. equal sign d. asterisk ANSWER: b 28. You can invoke a query during run time by entering its associated ____ method in a procedure’s code. a. Finish b. Select c. Fill d. Order ANSWER: c

Page 6


Name:

Class:

Date:

Chapter 12 9e 29. A table called SciFiBooks contains the following fields: Title, Author, and Year (for year published). Which is a parameter query that will return the records for the books published during a year that a user enters? a. SELECT Title, Author, Year FROM SciFiBooks WHERE Year = @Year b. SELECT Title, Author, Year IN SciFiBooks WHERE Year = Year c. SELECT Title FROM SciFiBooks WHERE Year = Year d. SELECT Year FROM SciFiBooks WHERE Year = @Year ANSWER: a 30. A(n) __________ field is one whose values are the result of a calculation involving one or more of the dataset’s existing fields. a. invoked b. calculated c. fill d. search ANSWER: b 31. An auto dealer’s tblTrucks table has two text fields named Make and Model, and two numeric fields named Year and ListPrice. In the TableAdapter Configuration Wizard, which of the following statements adds the numbers in the ListPrice field to give a total value for the dealer’s truck inventory? a. SELECT SUM(ListPrice) AS TotalValue b. SELECT AGGREGATE(ListPrice) FROM tblTrucks c. SELECT SUM(ListPrice) AS TotalValue FROM tblTrucks d. SELECT (ListPrice) FROM tblTrucks ANSWER: c 32. In a SELECT statement, the WHERE clause’s LIKE operator can be combined with either of which two wildcards? a. % and _ b. % and & c. _ and & d. & and * ANSWER: a

Page 7


Name:

Class:

Date:

Chapter 12 9e 33. Which statement selects the Title and ProductionCo fields from records whose title begins with the word “The” followed by a space and zero or more characters, and then sorts the records in descending order by the ProductionCo field? a. SELECT Title, ProductionCo FROM Movies WHERE Title LIKE 'The %' ORDER BY ProductionCo b. SELECT Title, ProductionCo FROM Movies WHERE Title LIKE 'The %' ORDER BY ProductionCo DESC c. SELECT Title, ProductionCo FROM Movies WHERE Title LIKE 'The *' ORDER BY ProductionCo DESC d. SELECT Title, ProductionCo FROM Movies ORDER BY ProductionCo DESC ANSWER: b 34. Which SELECT statement will select the ProdNum field from the Products table, and then sort the records in descending order by the Price field? a. SELECT ProdNum FROM Products SORT Price DESC b. SELECT ProdNum FROM Products ORDER BY Price DESC c. SELECT ProdNum FROM Products WHERE Price DESC d. SELECT ProdNum FROM Products ORDER BY ProdNum DESC ANSWER: b 35. Which WHERE clause would allow a user to select the records for collars within a specific price range (for example, records whose price is from $10 through $20)? The user will enter both prices during run time. a. WHERE Price >= @Price1 AND Price <= @Price2 b. WHERE Price >= @Price1 OR Price <= @Price2 c. WHERE Price <= 10 AND Price >= 20 d. WHERE Price >= 10 OR Price <= 20 ANSWER: a

Page 8


Name:

Class:

Date:

Chapter 12 9e 36. The tblStudent table contains nine fields, one of which is the StudentID field. A user can type in any StudentID to select a particular student. Which statement would allow the user to select the data for any StudentID number? a. SELECT * FROM tblStudent WHERE StudentID = StudentID b. SELECT * FROM tblStudent IF StudentID = @StudentID c. SELECT * FROM tblStudent WHERE StudentID = 'StudentID' d. SELECT * FROM tblStudent WHERE StudentID = @StudentID ANSWER: d 37. A ____ is a query that uses the parameter marker in place of the criterion’s value. a. substitute query b. parameter query c. limited query d. replaceable query ANSWER: b 38. The SELECT statement’s ____ clause is used to arrange (sort) the selected records in either ascending or descending order by one or more fields. a. SORTBY b. WHERE c. ORDER BY d. ARRANGE ANSWER: c 39. AVG, COUNT, and SUM are __________ functions in SQL. a. autonomous b. divider c. solitary d. aggregate ANSWER: d 40. The LIKE operator also be used with the _____ wildcard, which represents one character. a. * b. = c. + d. _ ANSWER: d Page 9


Name:

Class:

Date:

Chapter 12 9e 41. When it is used to save a query, the TableAdapter Query Configuration Wizard generates a(n) __________ statement and Fill and Get methods. a. END b. WHERE c. GO d. SELECT ANSWER: d 42. Write a SELECT statement to select the records for bicycles for which there are at least five available. ANSWER: SELECT ItemNum, ItemName, Color, Price, Quantity FROM tblBicycle WHERE Quantity >= 5

43. What function does the Query Builder perform? ANSWER: The Query Builder dialog box can construct query statements for you. It contains four panes: Diagram, Grid, SQL, and Results.

Page 10


Name:

Class:

Date:

Chapter 12 9e Members The tblMembers table contains six fields. The MemberID, LastName, FirstName, JoinDate, and MemberType fields contain text. The Fee field contains numbers. The MemberType field contains one of the following letters: F for Family membership, A for one Adult membership, Y for one Youth membership, and S for one Senior membership. 44. Write a SQL SELECT statement that selects all of the fields and records in the table. Sort the records in ascending order by the MemberType field. ANSWER: SELECT MemberID, LastName, FirstName, JoinDate, MemberType, Fee FROM tblMembers ORDER BY MemberType

45. What is a parameter query and how is it used? ANSWER: A parameter query is a query that uses the parameter marker in place of the criterion’s value. The parameter marker typically used in SQL is the @ symbol followed by the name of the field you are querying.

46. Write a SELECT statement to select the records for all red bicycles. Order the bicycles in descending order by quantity. ANSWER: SELECT ItemNum, ItemName, Color, Price, Quantity FROM tblBicycle WHERE Color = 'Red' ORDER BY Quantity DESC

Page 11


Name:

Class:

Date:

Chapter 12 9e 47. What steps must be taken to allow an application to use a query during run time? ANSWER: For an application to use a query during run time, you will need to save the query and then invoke it from code. You save a query that contains the SELECT statement by associating the query with one or more methods. The TableAdapter Query Configuration Wizard provides an easy way to perform this task.

48. Write a SQL SELECT statement that selects the MemberID, LastName, and FirstName fields for all family members. Sort the records by the LastName field. ANSWER: SELECT MemberID, LastName, FirstName FROM tblMembers WHERE MemberType = 'F' ORDER BY LastName

49. Write a SQL SELECT statement that allows the user to provide a specific MemberID during run time. The query should select all fields. ANSWER: SELECT MemberID, LastName, FirstName, JoinDate, MemberType, Fee FROM tblMembers WHERE MemberID = @MemberID

50. Write a SQL SELECT statement that selects only the records for the Senior members. Select all of the fields. ANSWER: SELECT MemberID, LastName, FirstName, JoinDate, MemberType, Fee FROM tblMembers WHERE MemberType = 'S'

Page 12


Name:

Class:

Date:

Chapter 12 9e 51. What is the purpose of the LIKE operator in a SELECT statement’s WHERE clause? What wildcard characters can it be combined with? ANSWER: The LIKE operator uses a wildcard character to compare text values. The % wildcard represents zero or more characters. The _ (underscore) wildcard represents one character.

52. Write a SELECT statement to select the records for all bicycles with a price greater than $450. Arrange the bicycles in descending order by price. ANSWER: SELECT ItemNum, ItemName, Color, Price, Quantity FROM tblBicycle WHERE Price > 450 ORDER BY Price DESC

53. Write a SQL SELECT statement that selects the MemberID, LastName, and FirstName fields for members having a last name that begins with the letter J. ANSWER: SELECT MemberID, LastName, FirstName FROM tblMembers WHERE LastName LIKE 'J%'

Page 13


Name:

Class:

Date:

Chapter 12 9e Writing SELECT Statements The tblBicycle table contains five fields: ItemNum, ItemName, Color, Price, and Quantity. The Price and Quantity fields are numeric; all other fields are text. The dataset name is BicycleDataSet.

54. Write a SELECT statement to select all of the records for blue bicycles. ANSWER: SELECT ItemNum, ItemName, Color, Price, Quantity FROM tblBicycle WHERE Color = 'Blue'

Essay 55. What is SQL and how is it used? ANSWER: SQL is Structured Query Language. It is a set of statements that allow you to access and manipulate data stored in a database management system. The statements are used to store, retrieve, update, delete, and sort data.

56. Write a SQL SELECT statement that allows the user to select the members with a fee greater than or equal to the fee amount provided by the user. The query should select the MemberID, LastName, FirstName, and Fee fields. ANSWER: SELECT MemberID, LastName, FirstName, Fee FROM tblMembers WHERE Fee >= @Fee

Page 14


Name:

Class:

Date:

Chapter 12 9e 57. Write a SQL SELECT statement that selects the MemberID, LastName, JoinDate, and MemberType fields from all of the records. ANSWER: SELECT MemberID, LastName, JoinDate, MemberType FROM tblMembers

Page 15


Name:

Class:

Date:

Chapter 13 9e Indicate whether the statement is true or false. 1. Not all ASP pages contain HTML (Hypertext Markup Language) tags. a. True b. False ANSWER: False 2. Visual Basic provides templates for creating web applications. a. True b. False ANSWER: True 3. A client computer is one that requests information from a web server. a. True b. False ANSWER: True 4. When adding a table to a web page, use the Insert Table dialog box to set the number of rows and columns in the table. a. True b. False ANSWER: True 5. To change the name that appears on each page of a web site’s tab in a browser window, you need to change the <title> tag in the Site.Master page. a. True b. False ANSWER: True 6. The ASP.NET Web Application template includes Site.Master, Default.aspx, About.aspx, and Contact.aspx files. a. True b. False ANSWER: True 7. HTML tags tell the client’s browser how to render the page on the computer screen. a. True b. False ANSWER: True

Page 1


Name:

Class:

Date:

Chapter 13 9e 8. One drawback of dynamic web pages is that they are not interactive. a. True b. False ANSWER: False 9. Web controls have a Name property. a. True b. False ANSWER: False 10. When a user clicks a button on a web page, a postback occurs and the button’s Click event procedure is automatically sent to the server for processing. a. True b. False ANSWER: True Indicate the answer choice that best completes the statement or answers the question. 11. A web page that can accept information from the user and also retrieve information for the user is called a(n) ____ web page. a. static b. active c. dynamic d. updating ANSWER: c 12. Which of the template files that Visual Basic provides for web applications provides contact information? a. About.aspx b. Contact.aspx c. Email.aspx d. Info.aspx ANSWER: b 13. When a user clicks a button on the web page, the page and data are submitted to the server for processing. This event is referred to as a ____. a. refresh b. postback c. recall d. post ANSWER: b Page 2


Name:

Class:

Date:

Chapter 13 9e 14. Which is a valid filename for a web page? a. Default.vb b. Default.aspx c. Default.aspx.vb d. Default.wp.vb ANSWER: b 15. The purpose of the ____ tool is to compare an entry with a constant value or the property stored in a control. a. CompareValidator b. RegularExpressionValidator c. RequiredFieldValidator d. CustomValidator ANSWER: a 16. Which of the template files that Visual Basic provides for web applications serves as the home page? a. Home.aspx b. Default.aspx c. Index.aspx d. website.aspx ANSWER: b 17. If you want to verify that the prescription number, first name, and last name text boxes contain data, use the ____ tool. a. CompareValidator b. RangeValidator c. RequiredFieldValidator d. TextFieldValidator ANSWER: c

Page 3


Name:

Class:

Date:

Chapter 13 9e Case-Based Critical Thinking Questions Case 1: healthgoods.com Healthgoods is a retail pharmacy store. You have been hired to develop an application for healthgoods.com, the current company web site. The new application will allow customers to order prescription refills online using the company’s web site. 18. The current web site contains static web pages only. You will be adding a dynamic web page that allows users to enter information related to their prescriptions. Which of the files provided by Visual Basic will you use to ensure that all of the pages on the site have a consistent look? a. About.aspx b. Site.Master c. Default.aspx d. Contact.aspx ANSWER: b 19. When a client computer’s browser sends a request for an ASP page, the web server locates the page and then sends the appropriate ____ instructions to the client. a. Visual Basic b. HMLT c. system d. HTML ANSWER: d 20. Which of the following is true? a. A web server interprets and executes a web page’s HTML. b. Microsoft Edge and Google Chrome are examples of web browsers. c. A Submit button on a web page sends the page and its data to the client computer for processing. d. A dynamic web page is a document whose purpose is merely to display information. ANSWER: b 21. A ____ computer requests information from a web server. a. worker b. client c. service d. root ANSWER: b

Page 4


Name:

Class:

Date:

Chapter 13 9e 22. The web consists of documents called ____ that are stored on web servers. a. URLs b. browsers c. clients d. web pages ANSWER: d 23. If you want to verify that the customer entered a prescription number in the correct format, use the ___________ tool. a. RangeValidator b. RequiredFieldValidator c. CustomValidator d. RegularExpressionValidator ANSWER: d 24. A ____ is a computer that contains special software that “serves up” web pages in response to requests from client computers. a. web server b. page service c. web browser d. static server ANSWER: a 25. ____ web pages contain code that tells the objects on the web page how to respond to the user’s actions. a. Dynamic b. Static c. Header d. Progressive ANSWER: a 26. The properties of the RequiredFieldValidator tool include ____. a. ControlToValidate, ErrorMessage, and ClientValidationFunction b. ControlToValidate and ErrorMessage c. ControlToValidate, ErrorMessage, MinimumValue, MaximumValue, and Type d. ErrorMessage, MinimumValue, MaximumValue, and Type ANSWER: b

Page 5


Name:

Class:

Date:

Chapter 13 9e 27. In the context of web pages, ASP stands for ____. a. advanced script page b. active server page c. active storage page d. active solution page ANSWER: b 28. The purpose of the ____ tool is to verify that an entry matches a specific pattern. a. CompareValidator b. RegularExpressionValidator c. RequiredFieldValidator d. RangeValidator ANSWER: b 29. A file named Movies.aspx.vb would be referred to as a ____ file, because it contains code that supports the Movies.aspx web page. a. server-code b. client-code c. code-behind d. backup-code ANSWER: c 30. The purpose of the ____ tool is to verify that an entry passes the specified validation logic. a. CompareValidator b. RegularExpressionValidator c. RequiredFieldValidator d. CustomValidator ANSWER: d 31. A(n) ____ web page contains controls with which the user can interact. a. HTML b. static c. ASP d. dynamic ANSWER: d

Page 6


Name:

Class:

Date:

Chapter 13 9e 32. You can change a line of text into a comment by selecting the line and then clicking the ____ button. a. Comment out the selected lines b. CommentThis c. ChangeToComment d. Comment ANSWER: a 33. Which of the template files that Visual Basic provides for web applications contains information about the website? a. Info.aspx b. Source.aspx c. FAQ.aspx d. About.aspx ANSWER: d 34. When one of the pharmacy’s web pages is open in a browser window, the pharmacy’s name should appear on the window’s tab. This is done by changing the Site.Master pages's ____ tag to Healthgoods Pharmacy. a. <title> b. <name> c. <application> d. <heading> ANSWER: a 35. Which of the template files that Visual Basic provides for web applications creates a consistent layout for the pages in the application? a. Template.master b. Site.Master c. Template.aspx d. Site.aspx ANSWER: b 36. Before submitting their order, the user will enter the prescription number, first name, last name, and date to pick up the filled prescription. Which controls do you need to provide on the web page? a. text boxes only b. labels only c. a button and labels only d. text boxes, labels, and a button ANSWER: d

Page 7


Name:

Class:

Date:

Chapter 13 9e 37. The purpose of the ____ tool is to verify that an entry is within the specified minimum and maximum values. a. CompareValidator b. RegularExpressionValidator c. RequiredFieldValidator d. RangeValidator ANSWER: d 38. HTML stands for ____. a. Hidden Text Markup Language b. Hypertext Markup Language c. Hypotext Markup Language d. None of the other choices is correct. ANSWER: b 39. When you are displaying a web page, the ____ view shows the HTML and ASP tags that tell a browser how to render the web page. a. Design b. Source c. HTML d. Code ANSWER: b 40. The Visual Basic toolbox provides several tools for validating user input on a web page, such as the RequiredFieldValidator control. The tools are referred to as ____ tools. a. summary b. range c. validation d. display ANSWER: c 41. The purpose of the ____ tool is to verify that a control contains data. a. CompareValidator b. RegularExpressionValidator c. RequiredFieldValidator d. RangeValidator ANSWER: c

Page 8


Name:

Class:

Date:

Chapter 13 9e 42. You can add an image to a web page using the ____ tool in the toolbox. a. Canvas b. Paint c. Layer d. Image ANSWER: d 43. What is the advantage of starting a web application without using the debugging option? ANSWER: You can start a web application either with or without the debugging option. The advantage of starting a web application without debugging is that you will not need to remember to stop the application each time you close the browser window after starting the application.

44. How can you use the Visual Basic IDE to verify what a web site application looks like in different browsers? ANSWER: It is very easy to change browsers from within the Visual Basic IDE. You just need to click the list arrow on the Standard toolbar’s Start <browser> button. The name on the button will be the name of your default browser. You then select the desired browser from the list of browsers available on your computer. When you start a web application, the web pages will appear in the selected browser window. You can also use the Browse With option to add, remove, or set the default browser. Of course, to add a browser, you must have downloaded the browser onto your computer and also installed it.

45. Write the statement that displays the words “ABC Company” as a heading on a web page. ANSWER: <h1>ABC Company</h1>

Page 9


Name:

Class:

Date:

Chapter 13 9e 46. How do you close an application? ANSWER: Click File on the menu bar and then click Close Solution.

47. List the six validator tools available in the Validation section of the toolbox that are used for validating user input. ANSWER: 1. CompareValidator 2. CustomValidator 3. RangeValidator 4. RegularExpressionValidator 5. RequiredFieldValidator 6. ValidationSummary

48. Describe what happens when a user clicks the Submit button on a web page. ANSWER: When a user clicks the Submit button on a web page, the page and data are submitted to the server for processing. Using web terminology, the information is “posted back” to the server for processing; this event is referred to as a postback. When the server receives the information, it executes the Visual Basic code associated with the web page. It then sends back the appropriate HTML, which now includes the result of processing the code and data, to the client for rendering in the browser window.

49. Describe the differences among the RangeValidator, the CompareValidator, and the CustomValidator controls. ANSWER: The RangeValidator control validates that an entry is within the specified minimum and maximum values. The CompareValidator control compares an entry with a constant or with a control’s property. The CustomValidator control verifies that an entry passes the specified validation logic.

Page 10


Name:

Class:

Date:

Chapter 13 9e 50. Describe the four-step process involved in a client computer accessing a dynamic ASP page on a web server. ANSWER: 1. The client computer requests an ASP page from the web server. 2. The web server returns the HTML instructions to the client to render the web page on the computer screen. 3. The user clicks a button on the web page displayed on the client computer to submit the page and data to the web server for processing. 4. When the server receives the data, it executes the code associated with the web page. It then sends back the appropriate HTML to the client for rendering in the browser window.

51. Describe the difference between the Design view and the Source view of a web page in the IDE. ANSWER: When creating web pages using Visual Studio, you use both Design and Source views to create the pages. Design view is used to add text and controls to the web page, and to format those controls. The Source view shows the HTML and ASP tags that tell the browser how to render the web page. These tags are automatically generated for you as you are creating the web page in Design view.

52. List the two methods for starting a web application in Visual Studio without the debugging option. What happens when a web application is started? ANSWER: 1. Press Ctrl+F5. 2. Click the Start Without Debugging option on the Debug menu. When you start a web application in Visual Studio, the computer creates a temporary web server that allows you to view your web page in a browser.

53. Write a statement that sets the text of a Label control called lblWeight to the value stored in a Double variable called dblWeight using the default format. ANSWER: lblWeight.Text = dblWeight.ToString()

Page 11


Name:

Class:

Date:

Chapter 13 9e 54. Describe ASP. ANSWER: ASP stands for “active server page” and refers to the type of web page created by the ASP technology. All ASP pages contain HTML (Hypertext Markup Language) tags that tell the client’s browser how to render the page on the computer screen. For example, the instruction <h1>Hello</h1> uses the opening <h1> tag and its closing </h1> tag to display the word “Hello” as a heading on the page. Many ASP pages also contain ASP tags that specify the controls to include on the page. In addition to the HTML and ASP tags, dynamic ASP pages contain code that tells the objects on the page how to respond to the user’s actions.

55. What two properties should you specify for the RequiredFieldValidator? ANSWER: 1. ControlToValidate 2. ErrorMessage

56. How do you change the page title of an existing web page? ANSWER: Display the page’s .aspx file in Source view. In the first line, change the page title.

Essay 57. What is the difference between a static web page and a dynamic web page? ANSWER: A static web page is a document whose purpose is merely to display information to the viewer. Static web pages are not interactive. A dynamic web page is interactive in that it can accept information from the user and also retrieve information for the user.

Page 12


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.