VB
VB
COPYRIGHT:
All rights reserved.
THE AUTHORS
These notes remain the intellectual property of the authors. Copyright assigned to FET-colleges and to the DoE to duplicate the document in hard copy format only. Any other reproduction method is prohibited. No changes or alterations, in any way, are permitted. Suggestions and comments may be e-mailed to:
[email protected]
April 2008
ii
PREFACE
The following notes were developed to cover the missing outcomes from the amended Subject and Assessment Guidelines of December 2007 (NCV-document) for the subject INTRODUCTION TO SYSTEMS DEVELOPMENT. These notes are intended to be used as a source to cover the newly included subject outcomes for Topic 4. The nature of this document and subject reflect and exhibit cross curricular content. Therefore many concepts covered in the notes will also address some of the subject outcomes of other topics in the NCV-document, i.e. Topic Topic Topic Topic Topic Topic Topic Topic 2, 2, 2, 3, 3, 5, 5, 5, SO3, SO4, SO4, SO1, SO1, SO1, SO1, SO1, LO1 LO1 LO2 LO1 LO3 LO1 LO2 LO3
The notes reflect the interpretation of the authors regarding Topic 4 of the NCVdocument. It remains the responsibility of the lecturer to ensure that all subject outcomes in the NCV-document are covered. The notes focus on the basic principles of problem solving and programming as directed from each of the subject outcomes. Each of these major subject outcomes for Topic 4 is covered. These outcomes include Describe the term problem solving Produce and document an algorithm Produce and document pseudocode for a given problem Produce and implement alternate design methods to document a specification or solution for a given problem Demonstrate an understanding of computer data types Implement a program language to solve a given problem
Various problems have been supplied and the subsequent steps to develop solutions have been provided and discussed in detail. The authors followed a stepby-step approach from problem to solution, including the following Identifying appropriate input and output variables Algorithm design, as supplied in the IPO-chart Detailed algorithm in pseudocode Selection of appropriate data types for variables Selection of relevant components and designing a user interface
iii
Program implementation in Visual Basic.NET which includes o Form design o Coding Testing and debugging the program with suitable test data
Solutions include sequence, selection and/or iteration control structures. The authors are aware that the technique of implementing input boxes in the examples pertaining to loops is not entirely used in industry or as a norm. However, due to the nature of this document and the level of complexity involved, input boxes used in a loop to capture data illustrate the concept sufficiently. In later levels of problem solving, loops and iteration structures could be illustrated in conjunction with topics such as arrays, file processing, string manipulation, animation etc. The primary design method used in these notes is that of pseudocode. Alternative methods are discussed in Appendix A, where a clear example of each method is provided. It is the responsibility of the lecturer to ensure that these alternative methods are also covered as part of your lesson planning. A student that is able to develop proper pseudocode should experience no difficulty in drawing a flowchart or a Nassi Shneiderman diagram. Visual Basic.NET was chosen as a programming language to implement the solutions because it consists of a set of tools and technologies to assist in the easy development and creation of Windows based applications. In this language, the procedure header for every button click event is a very lengthy statement such as Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click Therefore, in every program example, the authors have made use of the ellipse as a method to save space and to fit the procedure header onto one line. Private Sub btnClear_Click(. . .) Handles btnClear.Click The notes contain various questions and exercises for you to test and apply your knowledge and they are all identified by one of the following icons:
Questions
Authors: HG Erasmus, CM Pretorius Copyright Reserved
This icon will be followed by short questions that are suitable for class discussions. Sometimes these questions are used to refresh your memory on previous chapters and other times questions about the newly discussed content.
iv
Exercises
This icon will be followed by exercises that the student must solve on paper. This could possibly lead to class discussions at a later stage, but students must first think about the problems and solve it on paper by applying the knowledge they have learned.
Practical
This icon precedes practical assignments that must be solved in Visual Basic.NET. Some of these assignments may already have been planned in previous exercises, but others must be planned and designed from scratch. All of these solutions must be tested with test data.
We hope that these notes will kindle your enthusiasm for problems solving and programming and motivate you to work hard in achieving your goals to become a developer in the IT-Field. These notes will equip you to solve any basic computer related problem and to write the corresponding program solution in VB.NET. Remember, the control structures forms the foundation for most program solutions. Enjoy your journey in exploring ways of solving problems by making use of the basic control structures!
Success is the natural consequence of consistently applying the basic fundamentals. Jim Rohn
TABLE OF CONTENT
CHAPTER
1 Understanding problems and how to solve them by using a computer Introduction to Visual Basic.NET (Visual Studio 2005) General concepts and arithmetic Creating a user interface with basic controls Write algorithms and programs in sequential steps The selection control structure part 1 The selection control structure part 2 Iteration using a fixed count loop Iteration using the do-loop
PAGE
1
2 3 4 5 6 7 8 9
APPENDIX
A B Tools for planning programs Unified Modelling Language 249 270 275
BIBLIOGRAPHY
vi
OUTCOMES
When you have studied this chapter you should be able to: read a problem and analyse it in order to understand exactly what it is that must be solved, understand how a computer processes data, name the steps to be taken to find an excellent, efficient and working solution for any problem, know what an algorithm is and how it can be applied to solve a simple problem
An everyday example will be: I need to go to school. Write down the steps to take from waking up in the morning until I am at school.
This problem statement is very simple and once I have read it, I understand what is asked. But now I need to write down the steps: 1. 2. 3. 4. 5. 6. 7. 8. Wake up. Get out of bed. Wash. Put on clothes. Prepare something to eat. Eat. Take my bag. Go to school.
These are the basic steps. It is possible to include more steps to ensure that nothing is left out and it is also possible to omit certain steps e.g. prepare something to eat, because my mother prepared food; or I do not eat in the mornings. But on the other hand, it is not possible to go to school before waking up, getting out of bed, or putting on clothes! Some of the steps can also be swapped. You may eat your food before getting dressed. But very important, your steps must always be in a logical order! These steps are called an algorithm that can be defined as a set of sequential instructions to solve a problem.
Calculate the floor area of the board room. The length of the room is 7 meters and the width is 4 meters. The problem statement must include enough information to enable the programmer to solve the problem. But, if some data (values) are missing, it must be of such a kind that the user will be able to supply the missing data. Example: The sum of 2 numbers must be calculated. The problem statement does not supply the values of the numbers, but the algorithm can ask the user to supply the value of the numbers. The most important aspect of solving a problem by using a computer is to write an algorithm to solve it. An algorithm is a set of steps that must be written in such a way that is it unambiguous and precise. The computer cannot think for itself - you as the programmer must tell the computer exactly what to do. You may never assume that the computer will do something if you have not explicitly included the specific step.
Input
Processing
Output
or
Data
Processing
Information
Figure 1-1
Each of the figures above clearly indicates that the algorithm must receive data (input) that must be processed to render meaningful results (output or information). In other words: Input is processed to render meaningful output. Data is processed to render meaningful information.
Example: The manager of a company asks a student to do some part time work for which he will be paid per hour. The student will have to know how many hours he has to work at what rate of pay before he can calculate the final amount he will receive. In this case the input (data) to this algorithm will be the hours and the hourly rate of pay. The input (data) must be processed to give the output (information) i.e. the amount the student will receive. It is clear that the input (data) is meaningless unless it is processed, because if the student knows how much he will receive per hour, but does not know how many hours he will work, the pay cannot be calculated! On the other hand, if the student has worked for 20 hours but the manager does not tell him how much he will receive per hour, it is also meaningless. Now it is possible to formulate the following: Unprocessed data is meaningless. Information is processed data. Output is processed data or processed input
2.
3.
4.
Example: Problem: Calculate the sum of 2 numbers and display the result on the screen: Input: Not available in the problem statement. The user has to supply the numbers. Processing: Add the 2 numbers to determine the sum. Output: The sum as calculated in the processing phase is displayed on the screen of the computer.
Note the following: The value of the numbers must be available before the sum can be calculated. It is impossible to display the sum before it has been calculated. These two remarks indicate that the steps must always be processed in a logical order.
Algorithm in pseudocode as will be discussed in the chapters to follow: CalcWage ~ This program will calculate and display the wage of an employee ~ Input (Provide values for the hours and the pay rate) display Provide the hours worked enter hours display Provide the rate of pay per hour enter payRate ~ Processing (Calculate the wage) wage = hours * payRate ~ Output (Display the wage) display The pay is R, wage end
Notes: Every algorithm has a descriptive name. This algorithm is called CalcWage. The last statement (step) is always end. ~ indicates that a comment that explains the code, will follow. Display means that a message or the contents of a variable is displayed on the screen. (Will be discussed later) Enter indicates that data must be entered by using the keyboard. The calculation is done by using an equation. In this algorithm wage will accept a new value i.e. the product of the hours and the hourly rate of pay.
Exercises Exercises
1. Write a detailed set of instructions, in sequence, to complete the following three tasks. Your instructions must be complete and in the correct sequence so that a novice can perform the tasks only by executing the instructions. 1.1 1.2 1.3 Bake a cake Make a cup of tea Buy a book
2.
Study the following problems, delete redundant information and decide if enough information is provided to obtain an answer. Write down the different steps to follow to solve the problem: 2.1 Jocelyn sold all but 7 of her hamsters for R5 each to a pet shop. The pet shop sells hamsters for R8.50 each. After the pet shop received Jocelyns hamsters they have double the number of hamsters they had before the transaction. How many hamsters did Jocelyn sell to the pet shop? A group of 30 learners, 2 lecturers and some parents took several cars to go to the 3 oclock show of the circus. The price of an admission ticket is R25 per adult and R17.50 per learner. If each car held five people how many cars did they take? Susan and her 3 friends went on vacation to visit her cousin who lives in a village at the sea. They had to travel for 2 days - 720 km on the first day and 485 km on the second day. While they were there, they visited friends in another town. They stayed with Susans cousin for 5 days and it took them 2 days to return to their home. How many kilometres did they travel in total?
2.2
2.3
OUTCOMES
When you have studied this chapter you should be able to: understand the basic concepts in Visual Basic.NET, such as application, solution, project, file, user interface, controls on the interface and their properties, Code Editor Window versus the Designer Window, create a Visual Basic.NET Windows-based application, manage the windows in the IDE Integrated Development Environment, set the properties of an object, use the group box, label, text box and button tools, add a control to the form, enter code in the Code Editor Window, save a solution, start and end an application, close and open an existing solution, understand the difference between a syntax error, a warning error message, a logic error and a run-time error.
2.1.2 AN APPLICATION
A Windows Application has a windows interface and is designed to run on a desktop computer in a MS Windows environment. The interface is what users see on the screen when they use the program and therefore it is also called the user interface. A web application runs from a web server and displays the user interface by using a web browser and includes web forms pages that have a web interface.
10
Some components
Any user interface consists of a number of components or controls and some of them are introduced in Figure 2-2. Note: The purpose of some of the components on the form is there to display information while other components are there for the user to enter data.
Questions
How many components can you identify on the form in Figure 2-2? How many of these components are there to enter data? How many components are there to display instructions and/or information to the user? Can you identify any other components that would not be used to enter data or to display information to the user? What do you think is the purpose of these components?
What will happen when the program is executed? The user (a potential VB.NET learner) must provide his or her first name and surname. The user must then click on the Welcome button to invoke a procedure to display a personalized welcome message on the label as indicated in Figure 2-3.
11
Example:
Figure 2-3
When designing a user interface, there are many guidelines to adhere to in order to make the form as user friendly as possible. In later chapters we will focus on individual controls and guidelines for each. At this stage, we can take note of the following guidelines: Align the borders of all controls and try to make similar components exactly the same size (width and height). Graphics and color should be used sparingly. If you use a graphic, use a small one and place it at a location where it will not distract the user. Limit the number of colors to three. Use a font that is easily readable. Keep the font and the size consistent. The information on a form should flow either horizontally or vertically, with the most important information at the top left corner. Keep margins consistent. Related controls are typically placed close together on the form.
12
2.2 EXPLORING THE IDE (INTEGRATED DEVELOPMENT ENVIRONMENT) AND THE FORM BY DEVELOPING A SMALL APPLICATION
From the above mentioned example we can see that a programmer must first design the way the user will interact with the program. The programmer must then use the IDE to visually design this user interface. Lets go through all the steps that the programmer must follow when the user interface in Figure 2-2 must be designed and to add the necessary code to produce the output in Figure 2-3. STEPS TO FOLLOW TO CREATE A VISUAL BASIC 2005 WINDOWS BASED APPLICATION: Start VB.NET Double click on the following icon on the desktop or Click on the start menu, select Programs and Microsoft Visual Studio 2005. A new application must then be created by clicking on File and choosing New Project as indicated in Figure 2-4.
Figure 2-4
13
The following screen (in Figure 2-5) will appear. Note that the project type must be Visual Basic. (Remember the Visual Studio 2005 IDE also provides for Visual C++ 2005, Visual J# 2005 and Visual C# 2005). If the project type is not Visual Basic, position the cursor on Visual Basic and right click on it. The default name for a new application is WindowsApplication1 (or WindowsApplication2, 3 etc. depending on previous attempts during the same session). As our first program is only going to ask a student for his/her name and is then going to welcome the student, we are going to change the name of the application to be WelcomeProgram, which is a more meaningful name to describe the project and to find it when trying to retrieve it at a later stage.
Figure 2-5
When you click on the OK button, a new form (Form1.vb) will appear in the Windows Form Designer Window. Two other windows, the Solution Explorer and Properties window, should also be open. Should one or both of these windows not be open, click on VIEW and select the required window. The solution explorer displays a list of the projects in the current solution. It also contains the items contained in each project.
14
Our solution contains one project folder and a file named Form1.vb It is good practice to give each form file a more meaningful name. Right-click on Form1.vb and select Rename as indicated in Figure 2-6. According to the Hungarian naming convention, the new name must start with the prefix frm. The extension of the new name must be .vb. Lets choose the new name frmWelcome.vb
Figure 2-6
After the form has been renamed, the new name will automatically appear in the object box of the properties window as well as in the Windows Form Design window (See Figure 2-7):
Figure 2-7
15
A form is an object. All objects have certain characteristics. For instance, a form has a certain colour, height and width. These are just some of the characteristics or properties of the form. Each property has a certain value. The values can be selected and changed in the properties window. To set the properties of a form, the programmer must first select the form by clicking on it (See example in Figure 2-8). The properties will then change to reflect all possible properties that can be selected for the form. There are many properties applicable to the form and the programmer can scroll up and down to select and change various properties according to the specific characteristics that the form must have that the programmer wants to design.
Some of the properties that can be selected for the active form
Figure 2-8
Look for the Text property. The value of this property is currently Form1. This is the value that appears as caption for the form.
16
If we want to change the caption on the form, we must change the value of the text property of the form. If we change the name to Welcome Program, the caption of the form will automatically change to this new value. In a similar way we can change the font from Microsoft Sans Serif, 8.25p (the current default font and size) to Comic Sans, 12p. This will then be the default font and size applicable to all components that will be placed on the form at a later stage. It will also have an effect on the size of the form because the value of the AutoScaleMode property is Font. (See examples in Figure 2-9 to 2-13).
Figure 2-9
17
Click here in order to see the Font dialog box from which the new font and size can be selected
Figure 2-10
Select the new font Select the size Click on OK to confirm the new font and size
Figure 2-11
18
The size of the form will change due to the new font. According to another default attribute, the form will scale when the font changes
New font that will be the default font for the complete form
Figure 2-12
The best way to learn is to explore and to try various options. Go to different properties of the form and change it to see what the effect of the change will be. A few suggestions: Change the BackColor, place a certain image as background on the form via BackgroundImage, then click on + next to the size property to change the height and the width of the form. You will also see that, when a property is selected, a description of the purpose of the property is provided as a help-facility.
19
Figure 2-13
Placing components on a form: Once the default properties for the form have been selected, the necessary components can be placed on the form. All the components can be found in the toolbox window. Remember if any part of the IDE (such as the properties window or toolbox window) is not visible, it can be activated via the view command. In a similar way that we learned about a form, the best way to learn about a component is to select a component and place it on the form and then to explore by playing around with the different properties of that component. For our welcome program we will use labels, text boxes and buttons. We will also use a group box to group some of the components. In later chapters we will start exploring radio buttons, check boxes and list boxes. The purpose of the course
is not to focus on the user interface and to teach you all the components but to focus on the programming logic. You will therefore not be taught about
all the components, but you are free to experiment and play with them. Remember, to explore is the best way to learn about it.
20
To place a component on the form, simply click on the component in the toolbox and drag it to the position on the form where you want to place it. You may also double click on the component in the toolbox in which case it will be placed in the top left corner of the form. You may then drag is from there to the position where you want to place it. To remove a component from the screen simply click on it and the press <delete> Any component can be resized by clicking and dragging the handles. The components that we will use during this course are indicated in Figure 2-14. The purpose of a label is to provide information to a user e.g. to display an instruction or to display an answer to the user. The purpose of a text box is to provide a space where the user can enter an input value. A text box can also be used to display an answer but be careful because in such a case the user may alter the value, unless the enabled property is set to FALSE. The purpose of a button is to provide a place where the user can click if he wants to activate a certain event e.g. to instruct the computer to calculate a certain answer.
Figure 2-14
Remember, at this point we just want to create the user interface in Figure 2-2 and to add the code in order to obtain the output in Figure 2-3. We will discuss all the relevant objects in detail in later chapters. When each object is discussed we will also provide additional design rules to adhere to when these components are placed on a form.
21
Step 1:
Figure 2-15
Place a group box on the form. Name the group box grpEnter. Change the text to the value Please provide the following and change this text in order for it to be displayed in black. Step 2: Place two labels on the group box. Name the first label lblFirstName and the second lblSurname. Change the text to First name: and Surname: respectively and ensure that the two labels are aligned. Step 3: Place a text box next to each label on the group box and ensure that they are aligned. Name the first text box txtFirstName and the second one txtSurname. Step 4: Add a label with a border beneath the group box. Name this label lblWelcomeMessage and align it with the borders of the group box by setting the AutoSize and BorderStyle properties of the label. Ensure that the message will be displayed in the centre of the label by setting the TextAlign property to MiddleCentre.
22
Step 5: Place the following 3 buttons underneath the label (lblWelcomeMessage) and ensure that they are exactly of the same size and aligned. Name: btnWelcome btnClear btnExit Text: Welcome Clear Exit
Ensure that btnWelcome is the default button and that Exit is the cancel button. (Make the form the active object and set the AcceptButton and CancelButton properties respectively). Step 6 Save the form by pressing the Save All icon or click on File and select Save All. This step must be done at regular intervals throughout any practical session and not only at this point.
When the application is saved for the first time, the following screen will appear in order for you to enter the directory where the application must be saved.
Figure 2-16
Ensure the correct folder location in your laboratory or personal computer. The application may also directly be saved to your flash disk drive. However, to develop, test and run an application directly from the flash disk could be very slow. Therefore we would rather recommend that you work on the hard drive and copy your complete application to the flash disk when you leave or when you have finished. Adding working code to the application: We are now going to add code in the code editor in order for the program to welcome the user in the following way: The user must first enter his or her first name and surname and then press the Welcome button (e.g. Tebogo Zulu). You may assume that the user will enter both
23
fields before clicking on the Welcome button. The program must then welcome the person with the following message: Welcome Tebogo Zulu We hope it will be fun learning Visual Basic.NET!! When the user clicks on the clear button, both text boxes as well as the label must be cleared in order to give another user a chance to enter his or her name and to be welcomed in the same way. When the user clicks on the exit button, the program must terminate. Because the Welcome button and the Exit button have been activated as the default button and exit button respectively, it will also be possible for the user to enter both input fields and then press only the enter-key (instead of clicking on the Welcome button) in order to see the welcome message. In a similar way will it be possible to exit the program by pressing the escape key on the keyboard instead of clicking on the Exit button. To enter code for the Welcome button: Double click on the Welcome button. Control will be transferred to the code editor and a procedure header and procedure footer will automatically be generated for this click event. Application name
Public Class frmWelcome
Figure 2-17
24
Add the following code in between the Header and the Footer that automatically appeared.
lblWelcomeMessage.Text = "Welcome " & txtFirstName.Text & " " & _ txtSurname.Text & ControlChars.NewLine & _ "We hope it will be fun learning Visual Basic.NET!!"
The & operator is a concatenation operator that will combine string items together. The word Welcome is combined with the names that the user entered in the two text boxes. A space is concatenated between the first name and surname. The underscore character (_) indicates to the compiler that one statement continues on a next line. ControlChars.Newline is a constant that will instruct the computer to place the next string on a new line on the label. These operators and constants will be fully discussed in chapter 5, but at this point we are going to use them in order to run a simple application and to display output on a label on the screen. After entering these two lines of code, the entries in the code editor look as follows:
Figure 2-18
In a similar way, add the following code for the btnClear click event to clear the screen and to restore the focus to the text box where the user must enter the first name: txtFirstName.Text = "" txtSurname.Text = "" lblWelcomeMessage.Text = "" txtFirstName.Focus() The btnExit click event must contain the statement Close() in order to terminate the application.
25
When all the code has been entered, the code editor will look as follows:
Figure 2-19
Now lets run the program by clicking on the debug icon as indicated in Figure 220. Assume my name is Tebogo and my surname is Zulu:
Debug icon
We may run the program while we are still in the code editor. We may also switch back to the design window before we click on the debug icon.
Figure 2-20
26
The user interface will look as follows after the user entered the values Tebogo and Zulu and then clicked on the Welcome button:
Figure 2-21
Close the application. Ensure to Make sure to close the complete application or project.
To open an existing application at a later stage the option to open a project must be chosen, not the option to open a file. Then double click on the name of the project (folder) in the correct directory.
Figure 2-22
27
TO SAVE AN APPLICATION OR PROJECT ON A FLASH DISK Look in the correct directory (folder) where the project is currently stored. Right click on the application. Send the complete folder to the Flash-drive (In this case, drive I, However it might even be E or F). Do not use the save as option. All the applicable parts of the project must remain in the folder.
Figure 2-23
It is extremely important that these steps must always be followed in the correct way. Do not try to save the code in the code editor separately from the user interface in the design window. Remember all the files belong to the same project of the same solution and it must be saved in the same folder. The purpose of this chapter was just to introduce you to the IDE and to get you going with a simple application. The program did not contain any variables and we will deal with that as we progress. We also assumed that the user has entered valid values before the Welcome-button was clicked. We will also deal with data validation in later chapters.
28
Suppose, in our example, we make the following mistakes when entering the statement to place the welcome message on the label.
Txt instead of Text & omitted
lblWelcomeMessage.Txt = "Welcome " txtFirstName.Text & " " & _ txtSurname.Text & ControlChars.NewLine & _ "We hope it will be fun learning Visual Basic.NET!!"
Figure 2-24 indicates how the two errors will be underlined in the code editor and Figure 2-25 indicates the corresponding error messages in the error list window.
Figure 2-24
Figure 2-25
A syntax error is identified by means of a red circle with a cross in the middle. If you double click on the syntax error, it will take you to that specific line and error in the code editor, in order to correct is. No program will run if there are any syntax errors present and when you try to run it, the following message will appear, as indicated in Figure 2-26. Click on the No-button and correct all syntax errors before you try to run the program again.
29
Apart from the error message and the blue underlining of the error, the line and column where the syntax error appears are also indicated and should also be of help when trying to find all your syntax errors.
Figure 2-26
30
All warning error messages are indicated with an exclamation icon and the error will be underlined in green.
Figure 2-27
31
Practical
1. Enter all the steps as discussed in this example during the practical sessions and run the program a few times with different names in each case. Ensure you understand all steps followed. Design a user interface to look exactly as the one in Figure 2-28. The user must be able to enter his or her name and the color and make of his/her car. The input values must then be combined into a sentence and must be displayed on the label in the following way. Provide for a default and cancel button. Once again you may assume that the user will enter valid values before the display button is clicked. This is also a very considerate programmer because, based on the message, everybody will be smart, no matter what they drive!
2.
Figure 2-28
32
OUTCOMES
When you have studied this chapter you should be able to: understand what a variable is, distinguish between the different data types, know how to declare a variable in Visual Basic.NET, distinguish between a variable with module scope and one with procedure scope, do conversions between different data types, know how to insert the OPTION EXPLICIT ON and OPTION STRICT ON into a program and know why it should be done, distinguish between a variable and a constant, know how to write an assignment statement, know how to format numeric output, know the difference between a format specifier and a precision specifier, understand basic arithmetic operations, know and use all arithmetic operators, set up and evaluate expressions and equations using variables, constants, operators and the hierarchy of operations.
33
3.2 VARIABLES
The programmer refers to a position or location in the memory of the computer as a variable where values can be stored. Initially, the variable need not contain a value. The word variable indicates that the value of the variable may vary as needed or as processing is done. You can visualise a variable as a box in memory that contains one, and only one, specific value at a given time. An illustration is a scoreboard of a football match where the scores of the two teams are displayed. A team has only one score at a given time e.g. at the beginning the score will be zero, but after the first goal it will be one. At no time may the scoreboard contain 2 different scores for one specific team. The same rule applies to a variable. After the statements of the algorithm are processed, the previous value of the variable is replaced by a new value. It is not possible to retain the previous value in the same variable.
3.2.1
NAME OF A VARIABLE
Every variable is given a descriptive name. There is no need for the programmer to know the exact position (address) of the variable in the memory of the computer, as the compiler will link the given name of the variable to the actual address in memory. Only one name is given to a variable and this exact name, is used throughout the algorithm or program. When choosing the name of the variable the programmer must adhere to certain rules: 1. 2. 3. 4. 5. 6. 7. The name must be descriptive e.g. grade, mark. It may not contain a space but more than one word may be joined e.g. bookPages, itemPrice. It may also be joined with an underscore character. It may contain letters and numbers, but not only numbers e.g. department23. It must begin with a letter and may not start with a number. It may not contain any special characters e.g. &, #, @, etc. It may not be too long. (In VB.NET, not longer than 32 characters) The name cannot be a reserved word in the language (e.g. Integer)
How to name a variable: All the characters of the name of a variable are lower case letters except where 2 or more words are joined. In such cases all the following words start with an uppercase letter. Remember that no spaces are allowed in the name of a variable.
34
Examples of valid variable names: Description of variable Name of employee Price of car Author of book Quantity in stock Age of student Total amount of sales Possible variable name empName carPrice author quantity stAge totAmtSales
Questions Questions
The following variable names are invalid. Supply the reasons: 5thGrade member of club abc 5472 theAddressOfTheCompanyInTshwane grade&mark ________________________________ ________________________________ ________________________________ ________________________________ ________________________________ ________________________________
3.2.2
35
Real numbers: A real number variable contains a positive or negative number with a decimal part. Examples of real numbers are the length of a window in meters and centimetres and an amount of money in Rand and cents. Examples: 12.47, -987.123, 17.00 Note that a pure numeric value is never enclosed in quotes.
3.2.3
A variable need not contain an initial value, but a value may be assigned to a variable in the beginning of the algorithm according to the type.
36
Study the following table to understand all the aspects of a variable: Description Name of student Number of books Price of item Student? (Y/N) Code (A C) Variable name stName noBooks price student code Variable type string integer real boolean character Possible value John Smart 234 78.56 true B
Exercises
Complete the following table: Description Colour of dress Length of man in meters Adult? Age in years only Salary in R/c Title of book Player in match? Class code (K,L or M) Author of book Number of computers Variable name Variable type Possible value
3.2.5 3.2.5.1
We have already seen that the name of all variables must be meaningful in order to describe the purpose of the variable. In addition to that, most VB.NET programmers use the Hungarian notation when naming variables. In this notation a three-letter prefix is used as the first 3 characters of the variable name. This three-letter prefix must indicate the data type of the variable. This convention enhances readability and ensures that the programmer gets less confused during the programming process.
37
The different data types and the three-letter prefix for each of the variable names are summarized as follows: Data type Integer Short Long Decimal Single Double Character String Boolean Prefix int shr lng dec sng dbl cha str bln Example intTotal shrNumStudents lngProduct decAmount sngTemp dblPaid chaDept strName blnValueEntered
3.2.5.2
A variable must be declared in a VB.NET program before it can be used. The name of the variable and the data type of the variable must be indicated in the declaration. Syntax:
We can also declare a number of variables of the same type on the same line: Example: Dim intTotal, intNumber1, intNumber2 As Integer
Authors: HG Erasmus, CM Pretorius Copyright Reserved
38
intTotal, intNumber1 and intNumber2 are three variables. Memory space is allocated to them and each one may contain an integer value. In a case like this, where more than one variable are declared in one statement, no initial value may be assigned to them.
3.2.5.3
NUMERIC VARIABLES
As mentioned before, numeric variables are variables that can be used in calculations. They are divided into two types.
a) INTEGERS
In Visual Basic.NET there are 3 data types that can accommodate an integer value and they are summarized in the following table. The main difference between these types is the memory space each requires and the values that it may contain: DATA MEMORY VALUES TYPE REQUIRED FROM TO Integer 4 bytes -2,147,483,648 2,147,483,648 Long 8 bytes -9,223,372,036,854,775,808 9,223,372,036,854,775,808 Short 2 bytes -32,768 32,767 Examples of declarations: Dim intNumber As Integer Dim intNumber As Integer = 0 These 2 declarations are the same. If the initial value for an integer is omitted, it will automatically be initialized to 0
Dim shrNumber As Short Dim shrNum As Short Dim shrNumber, shrNum As Short
The memory size for each of these variables will only be 2 bytes and not 4 bytes as for a normal integer. The first 2 statements can also be combined into one statement as indicated in the third statement
Remember, we will use a convention to start the names for variables with a prefix to indicate the data type. The prefixes for variables that may store integer values are as follows: Data type Prefix Integer int Short shr Long lng
39
b) REAL NUMBERS
A real number has a decimal position, indicated by a decimal point, not a decimal comma. Data types in Visual Basic.NET that can store a decimal position are classified as floating point numbers and fixed point numbers. A floating point number is a number that is expressed as a multiple of some power of 10. Floating point numbers are written in exponential notation, which is similar to scientific notation. E.g. 2,100,000 is equivalent to 2.1 x 106 (scientific notation) and to 2.1E6 (exponential notation) 106 E6
Floating point numbers can also have a negative number after the E. E.g. 0.0000021 is equivalent to 2.1E-6 2.1 divided by 10 to the sixth power Floating point numbers would be used to represent both extremely small and extremely large numbers. A fixed point number is not expressed as a multiple of some power of 10 and they store numbers with a fixed decimal point. Calculations involving fixed point numbers are not subject to the small rounding errors that may occur when using floating point numbers. Therefore the decimal data type is recommended for calculations involving money. Data types for real numbers can be summarized in the following table: DATA TYPE Single Double Decimal MEMORY
REQUIRED
VALUES FROM TO -1.401298E-45 3.402823E38 -4.94065645841E-324 1.79769313486231E308 Smallest non-zero number is +/0.000000000000000000000000001
Examples of declarations: Dim decAmount As Decimal A variable called decAmount may contain a decimal value and will be automatically initialized to 0 The variable called sngValue will contain a floating point number as a value. It will have an initial value of 10
40
Dim decAmt, decNumber As Decimal Naming conventions for variables declared to contain real values: Data type Prefix Decimal dec Single sng Double dbl
The declaration of two variables can be combined in one statement only if they are of the same data type and if no initial values are assigned to it
NON-NUMERIC VARIABLES
Variables that cannot be used in calculations can be categorised into the following types:
a) CHARACTER
A character data type can store one Unicode character. Unicode is the universal coding scheme for characters. It assigns a numeric value to each character used in the writing languages of the world. Each character is represented by 2 bytes. A character value must always be included in quotes in a statement. The variable chaDept is declared to contain one character value and the initial value is A
In our naming convention, variables of data type character, must begin with the prefix cha
b) STRING
A string data type can store text from 0 up to approximately 2 billion characters. The text property of most components (e.g. label, button, text box) is of type string. Declaration examples: Dim strStudentName, strStudentNumber As String
Both these variables could be of type string. Although the student number will contain a number, it is mostly not used in calculations
41
Dim strMessage As String = The value entered was incorrect, please re-enter
In our naming convention, variables of data type string, must begin with the prefix str
c) BOOLEAN
A variable of data type Boolean can only store the Boolean values True or False. We will make use of Boolean variables to determine whether the user has entered a valid value or not (True or False). It can also be used to reset a radio button or to disable a button. Declaration example: Dim blnValidEntry As Boolean = False
A variable called blnValidEntry is initially set to False. After the user has entered a value and it is found to be correct, the value will become true
In our naming convention, variables of data type Boolean, must begin with the prefix bln
Exercises
Declare variables for the following. Each declaration must have a procedure scope. In each case choose a suitable variable name with the correct prefix:
42
1. 2. 3. 4.
A code for a class group. The initial value for this group must be a B. A wage of a cashier. Assign a value of R256.34 to the wage. The number of students in a class. The number of students is 250. A name of a student. The name of the first student is John Adams.
All the rules of a variable apply to a constant, except for the fact that it has a fixed value right through the entire program. Constants are used in cases where we know that the value will never vary or change during the execution of the program. A constant may be of any data type. Examples: There are always 24 hours in a day The value of is always 3.142 A message or legend to be printed may be The name of the student is
3.4.2
In algorithms to follow it will be necessary to display a legend followed by the value of a variable as shown in the following example: The statement wants to display that the percentage obtained by a student is the value that is stored in the variable called percentage.
43
The constant (fixed) part of the display statement will be a legend that has the value Percentage obtained by student: The variable percentage will contain the calculated percentage (example: 50) obtained by the student. The variable name percentage is not contained in quotes. The following statement: display Percentage obtained by student: , percentage, % will produce the output
String constant
variable
character constant
3.4.3
In Visual Basic, a constant value can be used directly in an expression or it can be declared as a constant if the value is known before the program is created. Syntax to declare a constant: Const constantname [As datatype] = expression The declaration must start off with the word Const followed by the name of the constant. Once again, if the data type is omitted, the default type of Object will be assigned to the constant. This is not recommended. A value or expression must be provided in order to assign a value to the constant. Examples: Const decVat As Decimal = 0.14 Const intDistinction As Integer = 75 Const strRadioStation As String = YFM
44
Figure 3-1
45
Figure 3-2
If the values in the text boxes are not converted to integer values, the + operator acts as a concatenate operator between two strings and conversions are therefore essential before any calculations can be done, especially when numeric values are to be entered into text boxes. The conversion methods for all the data types are provided in the following table: Method
Convert.ToInt32(value) Convert.ToInt16(value) Convert.ToInt64(value) Convert.ToDecimal(value) Convert.ToSingle(value) Convert.ToDouble(value) Convert.ToChar(value) Convert.ToString(value) Convert.ToBoolean(value)
Tip: It is not necessary to enter the complete method. As soon as you type the . a list of all possible methods in the Convert class will appear. You can simply select the applicable method and press the tab key.
Therefore, if the number of students is entered into a text box called txtNum and the value must be placed in a variable (intNoStudents) of data type integer, the statement could be as follows: intNoStudents = Convert.ToInt32(txtNum.Text)
46
More Conversion Examples: intNumber = Convert.ToInt32(shrNum) decAmtDue = Convert.ToDecimal(intNoBought * decPrice) sngRate = Convert.ToSingle(txtRate.Text) shrHours = Convert.toInt32(txtHours.Text) chaDept = Convert.ToChar(txtDept.Text) decAmount = Convert.ToDecimal(dblAmnt) If a constant value is assigned to a variable, the following literal type characters may be used to ensure that the variable and the value are of the same data type. Data type of variable
Integer Short Long Decimal Single Double Character
47
These three answers will then be displayed on three labels, to a precision of 7 positions after the decimal point. Studying the output in Figure 3-3, it is clear that some of the precision is lost when these two variables have been converted to a data type of single. In a case where the precision is not important, the programmer could allow conversions like this. An example where precision does not play a major role is conversion from F to C. The code for our current example:
48
Note: If Option Strict On is specified, it is only necessary to insert D and C to specify these conversions. All other conversions will automatically be done and will be accurate.
49
3.9.1
ARITHMETIC OPERATORS
An operator is a symbol used within an expression or equation that tells the computer how to process the data. This symbol joins the operands to be processed. The following operators are used to perform arithmetic operations:
Operator Example Result Precedence
Description
^ *, / \ Mod +,Exponentiation (To the power of) Negation Multiplication and Division Integer division Modulus arithmetic Addition and Subtraction 2^4 -TRUE 5*7 72 / 8 37 \ 5 37 mod 5 4+7 14 - 5 16 FALSE 35 9 7 2 11 9 1 2 3 4 5 6
50
Integer division may only be done when dividing an integer value by another integer value because it discards (drops) the decimal part and also does not round the answer e.g. 49 \ 10 = 4. Modulus arithmetic is done when the user only wants to know what the value of the remainder is when dividing e.g. 49 mod 10 = 9. The order of precedence of execution as shown in the table of operators is important. When the execution of an expression is evaluated, it is always done from left to right and the operator with the highest order of precedence is done before the other operators Study the following example: 5 - 3 ^ 2 \ 8 + 17 mod 3 * 2 To find the answer of this expression we have to determine which operator to use first. The answer of the calculation done will now be printed in bold and underlined. Studying the expression we see that the exponentiation (^) must be done first: 5 - 9 \ 8 + 17 mod 3 * 2 Next step, multiplication and division, from left to right 5 - 9 \ 8 + 17 mod 6 Now, integer division 5 - 1 + 17 mod 6 Now, modulus arithmetic 5-1+5 Lastly, plus and minus are done, from left to right with the minus done first because it is to the left of the plus 4+5 9
Parentheses are used to change the order of execution. Calculations to be done in parentheses have a higher priority than any of the operators. Within the parentheses the priority of execution of the operators applies.
Authors: HG Erasmus, CM Pretorius Copyright Reserved
51
Another example: Calculate the value of the variable k where k = a * b ^ (14 c) mod 4 + 3 \ a where a, b and c are integer variables and have the following values: a = 3, b = 5, c = 11 Substitute the values of the variables before calculating: k = 3 * 5 ^ (14 11) mod 4 + 3 \ 3 = 3 * 5 ^ 3 mod 4 + 3 \ 3 = 3 * 125 mod 4 + 3 \ 3 = 375 mod 4 + 3 \ 3 = 375 mod 4 + 1 = 3+1 = 4 k =4 A problem statement: Kevin works 8 hours per day at a pay rate of R11 per hour. He has to pay R12 taxi fare per day. How much money will he take home after a 5 day work week? money = (hours * payRate transport) * noDays = (8 * 11 12) * 5 = 380
Note that we do not include the units i.e. the rand sign R in any calculation. It also applies to other units such as meters, cm, gram, kilogram, etc.
3.9.2
EXAMPLES IN VB.NET
Declare the necessary variables and constants and write arithmetic expressions for each of the following examples: Example 1: Thandi has 257 items and wants to pack them in packets of 14 each. How many full packets will she have? Dim intItems, intFullPackets As Integer Const intNoPacket As Integer = 14 intFullPackets = intItems \ intNoPacket Example 2: Joseph earns R5.75 per hour. He works 8 hours per day, but has to pay R3.60 bus fare daily. Determine his net income per day.
52
Const decTariff As Decimal = 5.75 Const decBus As Decimal = 3.6 Dim decNetIncome As Decimal decNetIncome = decTariff * 8 decBus Example 3: Bonita bought a number of items at R15.85 per item. She received a discount of 7.5%. Calculate the amount she has to pay. Const decPrice As Decimal = 15.85 Const decDiscount As Decimal = 0.075 Dim decAmtDue As Decimal Dim intNoBought As Integer decAmtDue = Convert.ToDecimal(intNoBought) * decPrice decAmtDue = decAmtDue decAmtDue * decDiscount
Exercises
1. 1.1 1.2 1.3 1.4 1.5 2. Calculate the value of x in each of the following exercises: x x x x x = g 5 + 14 mod h ^ 2 where g = 12 and h = 1 = 27 * y \ 3 / 2 z + 2 where y = 24 and z = 4 = a / (b + 2 ^ 2) 12 + c mod b 2 where a = 96, b = 2, c = 98 = (y - 2 * z) + y / 6 * w \ 2 where w = 10, y = 12, z = 2 = 35 mod y - ( z * w + y / 3 ) + y * w where w = 5, y = 24, z = 3
Write the following in pseudocode format and calculate the results for each of the following: Sandra bought six pairs of socks at R3.50 per pair. What is her amount due? Vusi wrote 2 tests and obtained percentages of 75 and 63. Calculate her average mark. Jimmy has 25 marbles and want to give each of 4 children an equal number. How many will each child receive? Solly bought a number of items and the amount due is R245.60. He receives a discount of 5%. Calculate the new amount due. Loveness packs baskets of biscuits containing 15 biscuits each. How many full baskets can she pack if she has 257 biscuits.
53
It is also possible to declare a variable with a block scope. Such a variable is declared within a selection statement, such as an IF-THEN-ELSE statement, or within a repetition statement, such as a FOR-NEXT statement, in which case the variable may only be used within that specific statement. Variables will block scope will be discussed in Chapter 7.
54
3.10.1
Lets design the user interface in Figure 3-4 to represent a simple calculator that can either add 2 numbers, subtract the second number from the first, multiply the two numbers or divide the second number into the first. The user must first enter the two integer numbers via two text boxes and then press an appropriate button to perform the required action. After the two integers have been entered they must be placed into two variables of the type integer. The answer for the addition, subtraction and multiplication will also be of type integer and the answer of the division must be of type decimal. If we use of procedure level variables, the same two numbers will have to be declared in each button-click procedure. However, if we use of module-level variables, the variables will only have to be declared once in the forms declaration section which will be a more effective way for this application. The conversion from the text boxes to the variables will still have to be done in each of the procedures because a user may click on the multiplication button before he or she clicks on the addition button. At a later stage, when sub procedures and functions are discussed, we will be able to avoid this duplication by placing it in one sub procedure. Example of the user interface:
Figure 3-4
55
An example of input and output when the addition button was clicked is provided in Figure 3-5:
Figure 3-5
The procedures in the code editor with procedure-level variables are indicated in Figure 3-6. Note that there are duplication of variables because every variable may only be used in the procedure where it has been declared:
Scope of variables
Scope of variables
Scope of variables
Figure 3-6
Authors: HG Erasmus, CM Pretorius Copyright Reserved
Scope of variables
56
Figure 3-7 is based on the same application, but now the procedures in the code editor contain module level variables. It is now only necessary to declare the variables intNumber1, intNumber2 and intAnswer once in the declaration of the form. The variable decAnswer is still declared in the last procedure because the answer of the division may result in a decimal answer, which will be different from the answers of the first 3 procedures.
Scope of variable
Figure 3-7
57
Input
Processing
Output
Input values entered via text boxes are of string data type
Numeric input values must be converted via one of the following methods before it can be used in calculations: Convert.ToInt16 Convert.ToInt32 Convert.ToInt64 Convert.ToDecimal Convert.ToSingle Convert.ToDouble
Numeric data must be converted back to string format and formatted by means of one of the following: ToString(C) ToString(D) ToString(F) ToString(N) ToString(P)
Figure 3-10
The formatting is done via a format specifier (C, D, F, N or P) and a number called the precision specifier that controls the number of digits to the right of the decimal point in the new formatted number. The numeric variable that must be displayed on the label must be followed by the convertion .ToString followed by the format specifier and possible precision specifier in quotes within brackets. Examples: decAmtDue.ToString(N2) intNumber.ToString(D) decAmount.ToString(C0) shrAmt.ToString(F2) dblAverage.ToString(P1)
58
F: Fixed point This format specifier is used for real numbers. There will be no thousands separator and negative numbers will be preceded by a minus sign. N: Number This format specifier is used for real numbers. A comma will be inserted as a thousands separator and negative numbers will be preceded by a minus sign. P: Percent The number will be multiplied by 100 and a percentage sign will be added to the number when it is displayed. Negative numbers will be preceded by a minus sign.
3.11.3 EXAMPLES
The following table contains examples of formatted numeric output where A is the format specifier and xx the precision specifier. ToString(Axx) D D D2 D3 C C2 C0 C1 C2 F F2 F0 F1 F2 Value in Variable 5 -5 5 5 3067.28 3067.28 3067.28 3067.28 -3067.28 3067.28 3067.28 3067.28 3067.28 -3067.28 Output displayed 5 -5 05 005 $3,067.28 $3,067.28 $3,067 $3,067.3 ($3,067.28) 3067.28 3067.28 3067 3067.3 -3067.28
59
ToString(Axx) N N2 N0 N1 N2 P P P2 P1 P0
Value in Variable 3067.28 3067.28 3067.28 3067.28 -3067.28 .0755 .0750 .0750 .0750 -0.05
Output displayed 3,067.28 3,067.28 3,067 3,067.3 -3,067.28 7.55% 7.50% 7.50% 7.5% -5%
Practical
Design the following user interface in Figure 3-11 and add the code provided in Figure 3-12 for the button click event. Predict the output that will be displayed and then run the program to check your results.
Figure 3-11
Authors: HG Erasmus, CM Pretorius Copyright Reserved
60
Figure 3-12
Exercises
Indicate the exact value that will be displayed on the label in each of the following cases. 1. decAmount = 19613.417D lblAnswer.text = The amount = R & decAmount.ToString(N2) 2. decAmount = 19613.417D lblAnswer.text = The amount = R & decAmount.ToString(F) 3. decAmtDue = 2399.619D lblAnswer.text = The amount due = & decAmtDue.ToString(C) 4. intNoStudents = 180 lblAnswer.text = The number of students is & _ intNoStudents.ToString(D4) 5. decVat = 0.14D decAmt = 1000D decFinalamt = decAmt + decAmt * decVat lblAnswer.text = decVat.ToString(P0) & VAT added to R & _ decAmt.ToString(F) & = R & decFinalamt.ToString(F2)
Authors: HG Erasmus, CM Pretorius Copyright Reserved
61
OUTCOMES
When you have studied this chapter you should be able to: name controls according to the Hungarian naming convention, know the purpose of a label control and how to add it to a form, know the purpose of a text box control and how to add it to a form, know the purpose of a button and how to add it to a form, know what access keys are and how to set it, set a default button and cancel button on a form, group certain related controls in a group box control, add a picture box control to a form, set different commonly used properties for each type of control, place a background image on a form, design user interfaces according to good GUI design guidelines.
62
Component Form Label Text Box Button Picture Box Group Box Check Box List Box Radio button
Prefix frm lbl txt btn pic grp chk lst rad
Example frmStudent lblHeading txtMark1 btnCalc picLogo grpMarks chkAbsent lstResults radFinal
Purpose Form for a student application Label to display a heading on the form Text box to capture test mark 1 Button to trigger calculations Picture box that contains a logo Group box to group all marks together Chck box to test if student was absent for a test List box to list all the results Radio button to indicate if mark counts towards final mark
63
Figure 4-1
4.3.2
Every label must have a meaningful name starting with lbl according to the Hungarian notation. The first step to do after you have placed a label on the form would be to give it a meaningful name in the name property. Do not leave the name label1 or label2. The next step would be to replace the text property with the text that you want to display on the label. These 2 properties are the minimum that must be set for any label on a form. If the purpose of the label is to display output, the initial text property of the label will be an empty string. The text align property will determine where in the label the text will be displayed. From the following Properties window (Figure 4-2) we can gather that the current active component on the form is a label named lblAnswer. It is currently empty as indicated in the text property, but when a text value is assigned to it, it will be placed in the middle, centre as indicated in the text align property.
64
Figure 4-2
If we want to change the position of text within the label, we must click on the arrow in the text align property. The various options, as indicated in Figure 4-3, will then be displayed and a new position may be selected.
Figure 4-3
The AutoSize property automatically sizes the label to fit its current text property. If this property is set to false the size of the label can be controlled by you. Compare the two labels in the form in Figure 4-4.
65
Figure 4-4
Both labels in Figure 4-4 have a border which can be set in the BorderStyle property. The default is none, in which case the label will not have any border. The type of border in Figure 4-4 is FixedSingle, but a border may also be set to Fixed3D, in which case it will look like the borders of the labels in Figure 4-1. Once again, to change the type of border, click on the arrow next to the property value and make your choice, as indicated in Figure 4-5.
Figure 4-5
You can also set the font property which will change the font and appearance of the text that will be displayed on the label. Part of the font-property is to display the text in bold, italics, underlined etc. as indicated in Figure 4-6.
Figure 4-6
66
There are many other properties to set. As mentioned in chapter 2, the best way to learn is to explore and to try various options. Go to different properties of a label to see what the effect of the change will be.
4.3.3
Keep the following in mind when placing a label onto a form and setting the properties of the label: Label controls must be used to display information that you dont want the user to change while the application is running. A label to identify a text box must be placed to the left or above the text box, should end with a colon and should be typed in sentence capitalization. Labels to identify text boxes should be left aligned. Labels that identify controls should have their BorderStyle property set to none. Labels that display program output, such as the answer of a calculation, normally has the BorderStyle property set to FixedSingle or Normal3D. Restrict the highlight of text to headings.
4.4 A TEXT BOX CONTROL 4.4.1 THE PURPOSE OF A TEXT BOX CONTROL
A text box is used to provide the user an area in which to enter data. Data that a user enters in a text box will be placed in the text property of the text box. Although the value entered may be numeric, it is treated as text and when entered it is therefore not in the correct format to be used in calculations. Before calculations can be done on numeric values entered in a text box, it must first be converted to the correct format and assigned to a variable. This has been discussed in chapter 3. A text box can also be used to display information. In such a case the enabled property must be set to FALSE, to ensure that the user may not change the information. In the example in Figure 4-7, the first text box is provided to enter the length of a lawn in meters and the second text box is provided to enter the width of the lawn in meters. Note, that although the length is entered as 4.5 it is still treated as text and it is not in the correct format to use directly in a calculation and the same applies to the width of the lawn that is entered as 6.2. I
67
1 2
Figure 4-7
4.4.2
Once again, the first property to be set for every text box is the name. Give every text box a meaningful name in the name property according to the Hungarian notation that starts with txt. Dont leave it as textBox1 and TextBox2. In our example meaningful names could be txtLength and txtWidth.
Once again, the best way to learn is to explore and try different properties in order to see the effect and result of each.
68
4.4.3
Keep the following in mind when placing text boxes on the form: Although the background and foreground color of a text box can be set, the number of colors on an interface should be limited to 3. The colors you choose should complement one another and should not distract the attention of the user. Related text boxes should be grouped together. A group box may be used for this purpose. A text box must always contain a related label in order to give clear instructions of what should be entered in the text box Be consistent with fonts and dont use a different font for every text box on a form
4.5 4.5.1
Related controls can be grouped together using a group box control. This control can be instantiated (created) by choosing the GroupBox in the toolbox window. In the following example, Figure 4-8 has been modified to group the two text boxes to enter the length and width of a lawn.
Group Box
Figure 4-8
69
4.5.2
A group box must have a meaningful name starting with the prefix grp. Dont leave it as groupbox1. Change the name of the groupbox in the Name property. The text property of the groupbox must contain the value that will be displayed in the upper-left corner of the control. To change the color of the text to black, click on the arrow next to the ForeColor property. Choose custom and select the color as indicated in Figure 4-9.
Figure 4-9
70
4.5.3
Keep
the following in mind when placing a group box on the form: Use a group box to group related controls together. Maintain a consistent margin from the edge of the group box. Align the borders of the controls in the group box where possible to minimize the number of different margins within the group box.
4.6 4.6.1
The purpose of a button control is to perform an immediate action when clicked. Buttons are commonly used in most Windows applications. Think of a game of solitaire. After you successfully completed the game, a window will appear to ask you if you want to play another game or not. In this window, there will be 2 buttons Yes and No. If you click on No, the game will be terminated, but if you click on Yes, a new game will be initiated.
Figure 4-10
In applications that we will write, there will normally have to be a button to click in order to start the processing after the user has entered input values. The action to perform would then be to do the necessary calculations and to display the answers as output on the screen. There must also be a button to clear all input and output controls in order for the user to enter new input values and to possibly repeat the process. It is not compulsory, but a good technique is to also include an exit-button to terminate the application. There were three buttons in Figure 4-8. The calculate-button must be clicked after input values have been entered in which case the size of the lawn and the time it will take to mow the lawn will be calculated and displayed on the label. When the clear-button is clicked, the two text boxes and the label will be cleared and if the exit-button is clicked, the application will terminate.
71
4.6.2
A button must have a meaningful name in the name property and according to the Hungarian notation it starts with btn. Dont leave it as Button1 or Button2. The code in the code editor is associated with a specific button and therefore it is extremely important that a button must have a meaningful name.
4.6.3
ACCESS KEYS
The text property of a button may contain an ampersand (&).The character following the ampersand will be underlined when the text is displayed on the button. This character will be the access key and will enable the user to select the button by pressing the alt key as well as the specific character which is underlined. It is not always convenient for a user to move and click the mouse in order to select a button. For instance, if a user must enter various text boxes it will be faster to keep his/her hands on the keyboard and to select the button via an access key. Access keys will also allow users with disabilities (who might not be able to use a mouse) to use the application. Lastly access keys allow a user to work with the application even if the mouse becomes inoperative. In the following example (Figure 4-11), the user interface of Figure 4-8 has been modified to change all three buttons to contain access keys. An access key is usually the first character of the text displayed on the button. However, because two of the controls start with a C, the access key of the second button is the second character. As far as an exit-button is concerned, it is normal practice to make the access key an x because x is associated with exit. Take note that access keys are not case sensitive. Therefore alt + X will be equivalent to alt + x.
Authors: HG Erasmus, CM Pretorius Copyright Reserved
72
Figure 4-11
For this user interface, the following properties have been set for the calculatebutton as indicated in Figure 4-12. Name: Text: TextAlign: btnCalc &Calculate MiddleCentre
Figure 4-12
73
4.6.4
In 4.6.3 we mentioned that it can be faster to use an access key instead of moving the mouse to position it on the correct button control and to click the control in order to enable a certain event. An even faster method is to specify the button that is normally clicked to perform the calculations as the default button and to specify the button that is normally clicked to terminate the application as the cancel button. In our example, the Calculate-button could be specified as the default button and the Exit-button can be specified as the cancel button. When a default button has been specified, the user can only press enter in order to activate it and that would be even faster than selecting an access key. To activate the cancel button, the user can only press the escape key. A default button and cancel button is specified for the user interface and therefore it is part of the properties of the form. In our case it can be specified as indicated in Figures 4-13 and 4-14.
Go to the properties for the user interface
The default value for the AcceptButton property is usually none. By selecting btnCalc, this button becomes the default button for the form Figure 4-13
The default value for the CancelButton property is also usually none. By selecting btnExit, this button becomes the default button for the form Figure 4-14
74
When the calculate-button has been selected as the default button, the control will be highlighted, as indicated in Figure 4-15.
Figure 4-15
4.6.4
Keep the following in mind when placing buttons on the form: A button control is used to perform an immediate action when clicked The text property of a button should be entered in book title capitalization. (Capitalize the first letter of every word) When buttons are positioned horizontally on the screen, all the buttons should be of the same height. It is preferred that the widths are also the same although they may vary. When buttons are positioned vertically on the screen, all buttons should be of the same height and width. The commonly used button should be placed first. This button that represents the users most used action should also be the default button. When assigning an access key to a button use the first letter of the caption unless another letter provides a more meaningful association. If the first letter has already been used for another access key, use a distinctive consonant. Lastly use a vowel or a number.
75
4.6.5
When designing an application, double clicking on a button will invoke a sub procedure in the code editor. The actual coding for this button can then be entered between the header and footer of the sub procedure. If we double click on the Exit-button, the following empty sub procedure, which corresponds to this button, will appear in the code editor (Figure 4-16).
Procedure Header
Add the code here. This code will be executed when the button named btnExit is clicked Procedure footer Figure 4-16
Figure 4-17 shows the sub procedure for the btnExit click event after the code has been entered. This event only contains the statement Close() in order to terminate the application when the button is clicked.
Figure 4-17
4.7 4.7.1
Sometimes it might be necessary to display a companys logo as part of the header of the user interface or a diagram in order to highlight or explain something to the user. In such a case an image can be added to the user interface by placing it on a Picture Box control. This control can be instantiated by selecting the PictureBox control from the toolbox window. Assume the user interface in Figure 4-18 has been created to handle orders for the Delight Chicken Farm that sells whole chickens, chicken portions and eggs. You want to place an image of a chicken in the spot next to the name of the farm.
76
Figure 4-18
Currently the Solution Explorer for this application looks as follows (Figure 4-19).
Figure 4-19
When the picture box control has been added to the user interface, click on the image property as indicated in Figure 4-20 in order to place an image on it.
Figure 4-20
77
When the image property has been selected, the following dialog box, as indicated in Figure 4-21 will appear.
Figure 4-21
Click in Import in order to select the picture file that must be placed in the Picture box. Once a file has been selected, the file will be added to the list and the image will appear in the dialog box as indicated in Figure 4-22. Once you click on OK, the picture will be placed on the control.
Figure 4-22
78
Figure 4-23 indicates the final result and Figure 4-24 indicates the new contents of the Solution Explorer in order to indicate that a new file now forms part of this solution.
Figure 4-23
Remember, the Solution Explorer displays the projects in the current solution as well as the items in each project. Our solution is named FET-chickenEx1 and it consists of one project folder. It also contains the files frmChicken.vb and now also the file chicken.jpg.
Figure 4-24
79
4.7.2
Once again, the first property to be set for every picture box is the name. Give every picture box a meaningful name in the name property according to the Hungarian notation that starts with pic.
Once again, the best way to learn is to explore and to try out the different properties in order to see the effect and result of each.
4.7.3
Keep the following in mind when placing picture boxes on the form: Graphics and color should be used sparingly in an interface. If you use an image in the interface, use a small one and place it in a location that will not distract the user.
4.8
A user interface may contain a picture as a background. However, remember that a picture can be disturbing and can distract the user. The user interface should always be simple, user friendly and fulfill the purpose for the user to enter input data, to click on a button to activate an event to display certain output to the user. In the following example we will just illustrate how you can insert a background image on a user interface and how the labels can be placed onto that in a transparent way.
80
The BackgroundImage property is currenty set to the default (none) as indicated in Figure 4-25.
Figure 4-25
If we click on the BackgroundImage property as indicated in Figure 4-25, the Select Resource dialog box (in Figure 4-26) will appear. The file to be used as a background, can be selected in a similar way as the file that has been selected to be placed on the picture box in our previous example.
Figure 4-26
81
Figure 4-27 indicates how the file P1030043.JPG has been selected as background image for the user interface and this file has also been added to the Solution Explorer.
Figure 4-27
Any label placed on the form will have a border as indicated in Figure 4-28. If you dont want this effect on your form, you must set the BackColor property of the label to transparent after the Web option has been selected. This is indicated in Figure 4-29 and the result is indicated in Figure 4-30.
Figure 4-28
82
Figure 4-29
Figure 4-30
The back color of the label is now transparent and therefore no border for the label is shown.
83
Questions
Answer the following questions, based on the the user interface provided in Figure 4-31. This user interface is designed to enter the minimum and maximum temperature for a day and to display the average temperature.
Figure 4-31
1. Another name for a user interface is a ____________________ a. b. c. d. e. Frame Form Facing Feature None of the above
2. This user interface contains the following number of components a. b. c. d. e. 6 9 3 4 None of the above
84
3. This user interface must contain code for ________ events a. b. c. d. e. 6 9 3 4 None of the above
4. In this user interface, the Calculate button is the ______________ button a. b. c. d. e. Accept button Cancel button Default button First button None of the above
5. In the given user interface, the value of the text property of the Clear-button is ____________ a. b. c. d. e. Clear Clear &Clear C&lear Clear
6. The text align property of all the buttons on the user interface is set to ______________ a. b. c. d. e. Middle Middle Centre Middle Right Middle Left Centre
7. On the user interface provided, the following controls are used to enter the minimum and maximum temperatures a. b. c. d. e. Text boxes Labels Buttons Edit box None of the above
85
8. Provide the value of the text property of the given user interface ___________________________ 9. The average temperature is displayed on a __________ called lblAve. a. b. c. d. e. 10. Text box Label Button Group Box None of the above True or False? Provide a reason for your answer. When the user has entered the minimum and maximum temperatures, the only way to display the average temperature is for the user to click on the Calculate-button.
______________________________________________________________ ______________________________________________________________ ______________________________________________________________ 11. To add a control to the user interface, the _______________ must be used. Properties Window Solution Explorer Toolbox View All of the above The following code is needed for the click event of the Exit button on the user interface Close Exit Close() Exit() Quit()
a. b. c. d. e. 12.
a. b. c. d. e.
86
13.
If the Exit button has been selected as the cancel button of the user interface, the following actions will cause the application to terminate Clicking on the Exit button Pressing the Escape key Pressing the alt key and the x-key Any of the above None of the above True or False? Provide a reason for your answer. The user would be able to successfully enter a minimum and a maximum temperature of 0?
a. b. c. d. e. 14.
______________________________________________________________ ______________________________________________________________ ______________________________________________________________ 15. Which one of the following variable names must be used in order to complete the following statement to display the answer?
87
OUTCOMES
When you have studied this chapter you should be able to do the following for a problem that can be solved with steps to be executed in sequential order: Identify all available input data and output needed. Draw an IPO-chart for the problem statement. Write an algorithm in pseusocode to solve the problem. Test the logic of the algorithm with test data in order to predict what the output will be and to see whether the output will be correct. Design a user interface that corresponds to the program planning. Code the program logic that corresponds to the algorithm for one of the buttons on the user interface. Add additional code for a button to clear all applicable controls on the user interface and code to terminate the application. Debug, test and run every program to see whether the output corresponds to the correct output that was prepared when the algorithm was tested with test data.
You should also be able to Use the concatenation character to combine output on a label Place output on two lines on a label by means of the ControlChars.Newline constant
88
Input:
Output:
To do better and more comprehensive planning to enable the programmer to write a complete algorithm without errors, an IPO-chart (Input, Processing, Output) is completed. The IPO chart includes an overview of the processing steps. I name age (use names of variables) P Prompt to read input fields Enter input fields Show name and age on the screen O name age
The preparation is done to write a detailed algorithm that contains every step to solve the problem:
89
Algorithm: ShowDetails ~ ~ This program will enter the name and the age of the learner and show it on the screen display Provide the name of the learner: enter name display Provide the age of the learner: enter age ~ ~display on new line ~display on new line
Show the details on the screen with appropriate legends display The name of the learner is , name display The age of the learner is , age ~display on new line ~display on new line
end The algorithm will provide the following output on the screen:
Provide the name of the learner: John Provide the age of the learner: 18 The name of the learner is John The age of the learner is 18
5.2.2 5.2.2.1
Problem:
Enter the distance between two trees in kilometers. Display the kilometers and then calculate and display the distance in meters as well as the distance in centimeters. Description distance in km. distance in km. distance in m. distance in cm. Type integer integer integer integer Name of variable kilometer kilometer meter centimeter
Input: Output:
90
I kilometer
P Prompt to read kilometer Enter kilometer Calculate meter and centimeter Display output fields
Algorithm: ConvertDistance ~ Convert km to meter en centimeter ~ Enter input data display Please provide the distance in km. ~ display on new line enter kilometer ~ Do the conversions meter = kilometer * 1000 centimeter = meter * 100 ~ Display the output display kilometer, km is equivalent to , meter, m and to , centimeter, cm ~ display all on one line end Output:
If the last display statement is replaced by the following 3 display statements, the output will change as follows: display Distance = , kilometer, km ~ display on a new line display Equivalent distance in cm = , centimeter, cm ~ on a new line display Equivalent distance in meter = , meter, m ~ on a new line New output:
Please provide the distance in km. 3 Distance = 3 km Equivalent distance in cm = 300000 cm Equivalent distance in meter = 3000 m
91
5.2.2.2
Problem:
EXAMPLE 3
Enter the length and the width of a tennis court in meters and then calculate and display the circumference and the area of the tennis court. Description length of court width of court circumference of court area of court Type real real real real Name of variable length width circumf area
Input:
Output:
I length width
P Prompt for input fields Enter input fields Calculate circumference and area Display output fields
O circumf area
Algorithm: CalcTennisCourt ~ Calculate circumference and area of tennis court display Please enter length: ~ display on new enter length display Please enter width: ~ display on new enter width ~ Do calculations and display answers circumf = 2 * (length + width) area = length * width display The circumference of the tennis court is , circumf , meters ~ display on new display The area of the tennis court is , area , square meters ~ display on new
line line
line line
end Output:
Please enter length: 30 Please enter width: 10 The circumference of the tennis court is 80 meters The area of the tennis court is 300 square meters
92
5.2.2.3
Problem:
EXAMPLE 4
Enter two integers on the keyboard and calculate and show the average of these two integers on the screen. Description first number second number average I num1 num2 Type integer integer real P Prompt for num1 and num2 Enter num1 and num2 Calculate average Show average on the screen Name of variable num1 num2 average O average
Input:
Output:
Algorithm: CalculateAverage ~ Prompt for and enter two integers display Enter first number: enter num1 display Enter second number: enter num2 ~ Calculate average average = (num1 + num2) / 2 ~ Show average on the screen display The average of the 2 numbers is , average ~ display on new line end Output:
Enter first number: 24 Enter second number: 41 The average of the 2 numbers is 32.5
93
5.2.2.4
Problem:
EXAMPLE 5
Jason works as a part time assistant in a book shop and receives an hourly wage. Enter the number of hours he worked for a specific week, as well as the pay rate per hour. He has to pay R8 per week towards the recreation club. Calculate and display how much he has earned for the week.
Input:
Output:
I hours rate
P Prompt for input fields Enter hours and rate Calculate wage Display wage on the screen
O wage
Algorithm: CalcWeeklyWage ~ Calculate and display the weekly wage for Jason ~ Enter input data display Provide number of hours Jason worked: enter hours display Provide rate of pay: enter rate ~ Do calculations and display wage wage = hours * rate 8 display Jason earned R, wage, for the week end Output:
Provide number of hours Jason worked: 24 Provide rate of page: 12.00 Jason earned R280.00 for the week
94
5.2.2.5
Problem:
EXAMPLE 6
Tebogo earns a monthly salary and always divides it in the beginning of the month into different amounts according to her needs. She pays R450 for the rent of her room and the remainder of the money is divided as follows: 50% for food , 20% for clothes, 15% for transport, 5% for charity and the remaining amount for pocket money. Enter her monthly salary that is never less than R1800, on the keyboard and then calculate and display how much money she has available for the different categories. Description monthly salary room money food money clothes money transport money charity money pocket money I salary Type real real real real real real real Name of variable salary room food clothes transport charity pocket O room food clothes transport charity pocket
Input: Output:
P Prompt for salary Enter salary Calculate different categories Display output fields
Algorithm: CalculateMoney ~ Divide Tebogos money into different categories display Provide Tebogos monthly salary: ~ display on new line enter salary ~ do calculations remainder = salary 450 food = remainder * 0.5 clothes = remainder * 0.2 transport = remainder * 0.15 charity = remainder * 0.05 pocket = remainder (food + clothes + transport + charity) ~ display results display Tebogo divided her salary as follows: ~ display on new line display Room R450.00 ~ display on new line display Food R, food ~ display on new line display Clothes R, clothes ~ display on new line
95
Provide Tebogos monthly salary: 2000.00 Tebogo divided her salary as follows: Room R450.00 Food R775.00 Clothes R310.00 Transport R232.50 Charity R77.50 Pocket money R155.00
Exercises
In each case, draw an IPO-chart and write an algorithm to solve the problem. 1. Enter the name and price of an item in a shop on the keyboard and then show the information on the screen of the computer with an appropriate legend. Enter two integers. Calculate and show the sum, difference and product of these two integers on the screen. Enter the number of rows of chairs in the city hall as well as the number of chairs per row. Calculate and display the total number of chairs in the hall. Enter Kevins length in feet and inches. Calculate and display his length in inches only (1 foot = 12 inches). Sandra bought a number of the same items at a shop. Enter the number of items she bought and the unit price of an item. Calculate the amount due by multiplying the number by the unit price and then add 14% sales tax to the amount. Display the final amount she owes on the screen of the computer.
2.
3.
4.
5.
96
6.
In a packet of sweets of the same kind, but of different colors, the following can be found: 35% of the sweets will be red; 25% will be yellow, 15% will be blue, 5% will be purple and the remaining sweets will be green. Enter the number of sweets (which will be a multiple of 20) in a big packet on the keyboard. Calculate and display how many of each of the color sweets can be found in this packet. Jane is a typist who works freelance and she charges the following rates: A page typed single spacing R4.75 A page typed double spacing R3.50 The user must enter the number of pages she typed in single spacing and the number of pages she typed in double spacing. Calculate the amount due. She saves 15% of this amount to buy supplies. Display the nett amount she earned for her work.
7.
97
In order to implement any program planning in VB.NET, we must therefore first build an appropriate user interface for the problem. On each interface we must have a button to trigger an event to execute the program logic of the algorithm. However, in most cases there will also be a button to clear all components on a form to prepare it for new input as well as a button to terminate the application. There may be more buttons to trigger more events. However, in this early stage all our applications will contain only these 3 buttons. In the design of the user interface, we can use various ways to display the output. One way is to provide a separate label for every output value. Alternatively, we can combine various output values onto one label. These methods will be illustrated.
5.3.1
For this example, the problem planning in example 5.2.2.5 will be used and the user interface will be designed to place every output value on a separate label.
5.3.1.1
lblPocketMoney
Figure 5-1
The names for the 3 buttons are btnCalc, btnClear and btnExit respectively and the name for the form is frmBudget. When the user clicks on the button named btnCalc, the code in the code editor to be executed, must correspond to the logic planned in the algorithm. When the user
Authors: HG Erasmus, CM Pretorius Copyright Reserved
98
clicks on the button named btnClear, the text box to accept an input amount must be cleared and all the labels to display output answers must be cleared. When the button called btnExit is clicked, the application must be terminated.
5.3.1.2
For this example we will assume that the user will enter valid input data therefore a numeric value greater than or equal to 1800.00. Take note of the use of the line continuation character. If one statement in a sub procedure is too long for one line and must continue to the next line, the first line must be ended with an underscore character (line continuation character). Our example includes comments. Comments in a VB.NET program start with a single quote. The output values have also been formatted to display 2 numeric positions in each case as well as thousands separators, should that be necessary.
Public Class frmBudget Private Sub btnCalc_Click(. . .) Handles btnCalc.Click 'Declare input variable as decimal Dim decIncome As Decimal 'Declare output variables as decimal Dim decRoom As Decimal Dim decFood As Decimal Dim decClothes As Decimal Dim decTransport As Decimal Dim decCharity As Decimal Dim decPocketMoney As Decimal 'Declare intermediate variables Dim decRemainder As Decimal 'Convert the input entered to the correct format and 'store it in the input variable decIncome = Convert.ToDecimal(txtIncome.text) 'Sequential Processing to calculate output decRoom = 450 Line decRemainder = decIncome - 450 continuation decFood = decRemainder * 0.5 character decClothes = decRemainder * 0.2 decTransport = decRemainder * 0.15 decCharity = decRemainder * 0.05 decPocketMoney = decRemainder - (decFood + decClothes _ + decTransport + decCharity) 'Display the output results on labels on the user 'interface lblRoom.Text = decRoom.ToString("N2") Formatted lblFood.Text = decFood.ToString("N2") output lblClothes.Text = decClothes.ToString("N2") lblTransport.Text = decTransport.ToString("N2") lblCharity.Text = decCharity.ToString("N2") lblPocketMoney.Text = decPocketMoney.ToString("N2") End Sub
99
Private Sub btnClear_Click(. . .) Handles btnClear.Click txtIncome.Text = "" lblRoom.Text = "" lblFood.Text = "" lblClothes.Text = "" lblTransport.Text = "" lblCharity.Text = "" txtIncome.Focus() End Sub Private Sub btnExit_Click(. . .) Handles btnExit.Click Close() End Sub End Class
5.3.1.3
Figure 5-2
5.3.2
For this example, the problem planning in example 5.2.2.1 will be used and the user interface will be designed to combine all the output values on a single label.
100
5.3.2.2
Once again, we will assume that the user will enter valid input data therefore a numeric integer value. In order to combine all three output values (the value entered in km and converted equivalent values in cm and meters) onto one label, a concatenation character is needed. The ampersand character (&) is used in VB.NET to act as a concatenation character. It will combine text and numeric output into one string output to be placed onto a label. The values to be concatenated can be either variables or literal strings. A line continuation character is once again needed in the statement to combine all the output fields onto the label. Public Class frmDistance Private Sub btnConvert_Click(. . .) Handles btnConvert.Click 'Declare input variable, it will also be used as an 'output variable Dim intKm As Integer 'Declare output variables Dim intCm, intM As Integer Concatenation 'INPUT character intKm = Convert.ToInt32(txtKm.Text) 'PROCESSING intM = intKm * 1000 intCm = intM * 100 'OUTPUT lblAnswer.Text = intKm & " km is equivalent to " & _ intCm & " cm and to " & intM & " m" End Sub
101
Private Sub btnClear_Click(. . .) Handles btnClear.Click txtKm.Text = "" lblAnswer.Text = "" txtKm.Focus() End Sub Private Sub btnExit_Click(. . .) Handles btnExit.Click Close() End Sub End Class
5.3.2.3
Figure 5-4
5.3.2.4
It could be necessary that the output on the label must be displayed on more than one line. In such a case the ControlChars.Newline constant must be used. It will place the next output to be concatenated onto the label, on a new line on the label. lblAnswer.Text = intKm & " km is equivalent to " & _ intCm & " cm and to " & intM & " m" rewritten as: lblAnswer.Text = "Distance = " & intKm & " km" & _ ControlChars.Newline & "Equivalent distance in cm = " & _ intCm & " cm" & ControlChars.Newline & _ "Equivalent distance in meters = " & intM & " m" will produce the following new output as indicated in Figure 5-5:
102
Figure 5-5
Exercises
1. In each of the following cases, choose a valid name for the variable and write a statement to declare this variable. Then write a statement to convert the value entered in the text box to the correct format and to store it in the declared variable. Name of text Variable: Name of text Variable: Name of text Variable Name of text Variable box: box: box: box: txtName Student name txtAmount An amount of an item in a shop txtDept A department code A, B or C txtNumber Number of students in a class
2.
Study the following declarations in a VB.Net application: Dim Dim Dim Dim intNum1 As Integer = 77 intNum2 As Integer = 100 intNum3 As Integer = 133 decAverage As Decimal
Write the statement to display the following output on a label called lblOutput for Figure 5-6 and Figure 5-7.
103
2.1
Figure 5-6
2.2
Figure 5-7
Practical
Write a VB.NET solution for each of the exercises 1 to 7 on page 96 and 97. In each case design your own user friendly interface. Use the IPO-chart and algorithm that you have designed in each case.
104
OUTCOMES
When you have studied this chapter you should be able to determine the results of relational conditions, evaluate expressions containing logical operators, write a simple if-statement in pseudocode and in VB.NET in order to test a condition, write an if-then-else-statement in pseudocode and in VB.NET, prepare test data to test all possible conditions for a program that contains decision structures, write algorithms and corresponding VB.NET solutions containing o simple if-statement, o if-then-else-statements, o compound if-statements, o Boolean variables, know the difference between the AndAlso and And logical operators and between the OrElse and Or logical operators in VB.NET, know how to add a checkbox control to a form and how to use it in decision statements in the code editor, code defensively and to do data validation wherever possible, use the TryParse method in VB.NET to test for possible input and conversion errors, use the String.IsNullOrEmpty method to test for possible input errors, use a MessageBox.Show method to display error messages and other possible output messages, take actions after a message box has been displayed.
105
DESCRIPTION Equal to Less than Greater than Less or equal to Greater or equal to Not equal to
EXAMPLE A=5 number < 97 totalAmount > 100 noStudents <= 50 weight >= 75 quantity <> 17
All these relational operators have an equal priority, but the mathematical operators have a higher priority than the relational operators. Examples: Determine whether the following expression is true or false: 1. b <= a 3 where b = 5 and a = 7 substitute: 5 <= 7 - 3 false 5 <= 4 m + 7 > n 3 * p where m = 4, n = 12 and p = 5 substitute: 4 + 7 > 12 3 * 5 4 + 7 > 12 - 15 11 > -3 true
2.
106
Exercises
Evaluate the following expressions: 1. 2. 3. 4. a + t <> (a + b) * 4 k ^ 2 <= m mod 5 + 29 n (x \ 8 2) + 3 > y / 12 mod 2 d + 4 * g / 2 < g * 3 + 14 where where where where a = 4, b = 17 and t = 20 k = 5, m = 63, n = 7 x = 59, y = 96 d = 3, g = 24
OR
The order of precedence is indicated in the last column i.e. processing is done in the following order: NOT AND OR When the same operator appears more than once in one expression, it is evaluated from left to right. When different operators are combined in one expression, all the mathematical operators will be processed first, then the relational operators and lastly the logical operators.
107
Examples: Evaluate the following expressions: 1. D OR K AND NOT S where D = TRUE, K = FALSE, S = TRUE substitute: TRUE OR FALSE AND NOT TRUE TRUE OR FALSE AND FALSE TRUE OR FALSE TRUE M > 7 AND D < S ^ 2 where M = 7, D = 8, S = 4 substitute: 7 > 7 AND 8 < 4 ^ 2 7 > 7 AND 8 < 16 FALSE AND 8 < 16 FALSE AND TRUE FALSE D < (E + 7) AND G OR (A * C) >= (D E + C) where A = 5, C = 12, D = -15, E = -17, G = FALSE substitute: -15 < (-17 + 7) AND FALSE OR (5 * 12) >= (-15 (-17) + 12) -15 < -10 AND FALSE OR (5 * 12) >= (-15 (-17) + 12) -15 < -10 AND FALSE OR 60 >= (-15 (-17) + 12) -15 < -10 AND FALSE OR 60 >= (-15 + 17 + 12) -15 < -10 AND FALSE OR 60 >= (2 + 12) -15 < -10 AND FALSE OR 60 >= 14 TRUE AND FALSE OR 60 >= 14 TRUE AND FALSE OR TRUE FALSE OR TRUE TRUE
2.
3.
Exercises
1. Evaluate the following expressions where A = 5, B = 7, C = 12, D = -4, E = TRUE and F = FALSE: A * 3 >= B 14 \ 3 AND F OR C <= D + 3 NOT F OR E AND D + C = A (C D) * 2 <> A + B OR E AND F OR B > D + B ^ 2 D = C MOD 5 AND NOT F OR NOT(A + D <= A D) 108
2.
Choose appropriate names for the variables used and write equations to calculate the required result: The total of the 5 test marks of Cindy is stored in the variable totMark. Calculate the average test mark. The area and length of a carpet is known. Calculate the width. Determine the difference between the 2 integers stored in the variables numOne and numTwo. Annah obtained a test mark stored in the variable test1 out of a possible 60. Convert this mark to a percentage.
109
Please note: There may be any number of statements in the body of the if-statement (between the if and the endif ). The statements will only execute if the condition is TRUE The statement(s) within the if-statement is/are always indented to enhance the readability of the algorithm. The if and the endif are written in the same column while the body of the if statement is indented. The if-statement always renders a Boolean value i.e. the result is always TRUE or FALSE.
It is also possible to test whether a specific condition is not true by inserting the word NOT before the condition. if NOT condition then statement 1 : statement n endif Example: if mark NOT < 50 then display Student has passed endif
110
amounts i.e. if the calculated price is R3.25, then the selling price is R4. In other words, cents are rounded up to the next rand. Description cost of cake price of slice Type real integer Name of variable expense slicePrice
Input: Output:
I expense
O slicePrice
Algorithm: CalcCakePrice ~ Calculate the selling price of cake ~ enter input data display Provide the cost of the cake: enter expense
~ add profit and calculate price per slice cakePrice = expense + expense * 0.3 ~ intermediate var cakePrice slicePrice = cakePrice \ 10 rem = cakePrice mod 10 ~ calc if any cents if rem > 0 then ~ test if any cents slicePrice = slicePrice + 1 endif ~ display the price of a slice of cake display The price of a slice of cake is R , slicePrice ~ display on new line end Test the program by using a manual calculation: Use expense = R18.60 Increase by 30%: R24.18 Gross price / slice R2.418 Integer division results in R2 per slice of cake Because there is a remainder, R1 will be added to the result to give the selling price for a slice of cake. Selling price / slice R3
111
Trace table: The instruction is listed in the leftmost column, followed by the variables used, the outcome of the if-statement and lastly the output as shown in the following table:
expense Instruction cakePrice slicePrice rem Outcome of if Output
display enter calculate calculate calculate if calculate display 18.60 24.18 2 .418 TRUE 3
Output:
Provide the cost of the cake: 18.60 The price of a slice of cake is R3
Whenever an if-statement is involved, test data should be prepared in such a way to test if all possible outcomes of the if-statement work in a correct manner.
6.6.1 EXAMPLE 1
Problem: John bought a number of pencils at a given price. The user must be asked to enter values for these variables. If he buys 25 or more pencils, he receives a discount of 7%. Calculate and display the amount due by John. Description Type number of pencils integer price of one pencil real amount due real 112 Name of variable number price amount
Input:
Output:
I number price
P Prompt to read input fields Enter input fields Calculate amount Display amount
O amount
Algorithm: CalcAmount ~ Calculate the amount due for pencils ~ Input display Provide the number of pencils bought: enter number display Provide price of one pencil: enter price ~ Processing amount = number * price ~ test if John bought 25 or more pencils if number >= 25 then amount = amount (amount * 0.075) ~ the calculation could also have been amount = amount * 0.925 endif ~ Output display The amount due is R , amount end Test the program twice: Number = 16, price = R3.50 (less than 25 pencils) Number = 30, price = R2.25 (equal or more than 25 pencils) Output: Provide the number of pencils bought: 16 Provide price of one pencil: 3.50 The amount due is R56.00 Provide the number of pencils bought: 30 Provide price of one pencil: 2.25 The amount due is R62.44
113
6.6.2 EXAMPLE 2
Problem: The mark obtained by a student is entered. If the student has passed (50 or more marks), the mark must be displayed and a message that indicates that the student passed. But if the mark is less than 50, the mark and a message that indicates that the student has failed, must be displayed. Description Mark obtained Mark obtained Outcome of if I mark Type integer integer string Name of variable mark mark message O mark message
Input: Output:
P Prompt to read mark Enter mark Determine message Display output fields
Algorithm: PrepareResult ~ Prepare and display result of student display Provide mark obtained: ~ display on new line enter mark ~ initialize message message = pass ~ test result if mark < 50 then ~ could also have tested mark <= 49 message = fail endif ~ display result display The mark is , mark, % Result = , message ~ display on new line
end Test the program twice with a mark of 45 and 69 respectively. Output: Provide mark obtained: 45 The mark is 45% Result = fail Provide mark obtained: 69 The mark is 69% Result = pass
114
Exercises
1. Henry rents a trailer to move his furniture to his new house. The basic cost is R200 per day and he also has to pay a specific amount that must be entered by the user for the kilometers traveled. The user also has to enter the kilometers. If he traveled for less than 50 kilometers an additional surcharge of 5% is payable on the amount due for the distance. However, if he used the trailer for more than 400 kilometers, he receives a discount of 12% on the amount due for the distance. Write an algorithm to calculate and display the amount due. (Hint: use 2 different if-statements in your algorithm). Write an algorithm for the following: Jessie and Sally want to buy a large pizza to share. Enter the cost of the pizza and the amounts that Jessie and Sally each have in their purses. If they have enough money, display a message that indicates that they can buy the large pizza. However, if the do not have enough money, display a message that they have to buy a small pizza.
2.
Prepare test data for both examples to test all possibilities, and draw a trace table for each.
Once the condition is entered and the enter key pressed, the compiler will insert the Then and the End If automatically. It is therefore only necessary to include the statement or statements for the body of the if-statement. The compiler will also automatically indent the code properly.
115
116
6.8.3 OUTPUT
Figure 6.2 shows the output if 16 pencils were bought at R3.50 each (in this case the outcome of the if-statement was false and no discount was granted)
Figure 6-2
Figure 6.3 shows the output if 30 pencils were bought at R2.25 each (in this case the outcome of the if-statement was true and a discount of 7.5% was granted) 30 x 2.25 = 67.50 7.5% of 67.50 = 5.06 67.50 5.06 = 62.44
Figure 6-3
117
Figure 6.4 shows the same outcome, but the user interface was designed with a background image of a pencil. Although the background is not that dominant, it could be distracting. Decide for yourself.
Figure 6-4
118
6.10.1 EXAMPLE 1
Problem Angelina and Freedom took part in the final of a competition. A rule of the competition is that judges may not assign equal points to competitors at this stage. Enter the number of points that each competitor obtained. Compare the points and determine who the winner is. Display the name and the number of points of the winner on the screen. Description Angelinas points Freedoms points Winners points Winners name I pointA pointF Type integer integer integer string Name of variable pointA pointF pointW winner O winner pointW
Input:
Output:
P Prompt for points Enter points Determine winner Display winner and points
Algorithm: DetermineWinner ~ Determine the winner of the competition ~ Enter input data display Provide point for Angelina: enter pointA display Provide point for Freedom: enter pointF ~ find the winner if pointA > pointF then pointW = pointA winner = Angelina else pointW = pointF winner = Freedom endif
~ display result display The winner is , winner display and the winning points: , pointW end
119
Test the program - Angelina obtained 175 points and Freedom obtained 179 points Output:
Provide points for Angelina: 175 Provide points for Freedom: 179 The winner is Freedom and the winning points: 179
6.10.2
Problem
EXAMPLE 2
Dennis loves reading books and you have been asked to calculate how many days he will need to read a given book by writing an algorithm to solve the problem. Enter the number of pages in the book and the number of pages that he is able to read per day. Display how many days he needs to read the book. You are also asked to determine if it is possible for him to read 5 books with the same number of pages during his 14 days of holidays. Display this answer. Description Pages per book Pages per day Days per book Result of if Type integer integer real string Name of variable bookPages dayPages bookDays message O bookDays message
Input:
Output:
I bookPages dayPages
P Prompt for input fields Enter input fields Calculate bookDays Determine message Display output fields
Algorithm: ReadingSpeed ~ Enter input data display Provide number of pages per book: enter bookPages display Provide pages Dennis can read per day: enter dayPages
120
~ calculate days per book and days to read 5 books bookDays = bookPages / dayPages days = bookDays * 5 ~ an intermediate variable is used (not I or O) ~ test if 5 books can be read during holidays and display output
display Dennis takes , bookDays, days per book of , bookPages, pages
if days <= 14 then message = Dennis can read 5 of these books during the holidays else message = It is not possible for Dennis to read 5 of these books during the holidays endif display message ~ display on new line end Test the program: Book has 120 pages and 333 pages Dennis can read 50 pages per day Output:
Provide number of pages per book: 120 Provide pages read per day: 50 Dennis takes 2.4 days per book of 120 pages Dennis can read 5 of these books during the holidays Provide number of pages per book: 333 Provide pages read per day: 50 Dennis takes 6.7 days per book of 333 pages It is not possible for Dennis to read 5 of these books during the holidays
Exercises
1. 1.1 In each of the following cases, write an algorithm to solve the problems: The Great College offers 2 different courses in Programming that are offered as self study courses while the lecturer is assisting. The student can decide beforehand how many weeks he/she wants to study. The code of the first course is an A, while the code of the second course has a code of B. You may assume that the user will only enter an A or a B. The price for course code A is R234 per week, while the course for the other course is 121
R287.50 per week. The user has to enter the course code and the number of weeks of study. Calculate and display the course code and total price of the course on the screen. 2. Write only the if-statement for the following. You may choose your own names for the variables where the names are not specified: The weights of 2 dogs, Fluffy and Terry, have been entered. Display the name of the dog that weighs more than the other dog. You may assume that the weights will not be the same An employees salary empSalary has been entered. Determine and display a message to indicate if this person needs to pay income tax. Only people with an income of more than R3000 per month, has to pay tax. Tom decided that he must have one shirt for every pair of pants. Determine if this is true and display an appropriate message. Josie wants to go to the movies, but is only allowed to go if she has done her homework (use a Boolean variable) and has R10 to pay for the ticket. Display a message to indicate if she can go or not. Test the mark of a student. If the mark is more than 47, increase the mark by 2.5%, otherwise decrease the mark by 5.7%. Display the new mark. Values for the variables A and B are given. Both contain real numeric values. If the value of A is greater than 17 and less than 47, swap the values of A and B, but if the value of A is either 5 or 87, increase the value of A by 20 and decrease the value of B by 5. Hint: Make use of a temporary variable if it is necessary to swap the values.
2.1
2.2
2.3
2.4
2.5
2.6
As mentioned before, once the condition is entered and the enter key pressed, the compiler will insert the Then and the End If automatically. However, the user must add the Else. The compiler will automatically indent the code properly when the body is entered.
122
txtBookPages txtDayPages
lblOutput
btnExit
Figure 6-5
btnTest
btnClear
6.12.2
Figure 6-6 indicates the code in the code editor for the Test-button:
123
Figure 6-6
6.12.3
OUTPUT
Figure 6-7 indicates the output if the book contains 120 pages and Dennis can read 50 pages per day whereas Figure 6-8 indicates the output if the book contains 333 pages and Dennis can read 50 pages per day.
Figure 6-7
Figure 6-8
124
Example: If a person is 18 or more years of age and has a drivers license, this person may drive a car. if age >= 18 AND licensed then ~ licenced is a boolean variable display This person may drive a car else display This person may not drive a car endif The result for this compound test is only true when both the conditions are true. If only one or none of the conditions is true, the result is false.
Example:
If an employee is a grade C employee or has worked for the company for more than 5 years, a special bonus of R1000.00 is awarded to this employee.
if grade = C OR years > 5 then bonus = 1000 else bonus = 0 endif For the result of this compound test to be true at least one of the conditions must be true. If none is true, the result is false. In the case where the if-statement contains more than 2 conditions, it is advisable to use parenthesis to indicate which tests must be done before the other, since the tests in the parenthesis are done first. if gender = M OR (age > 20 AND member) then ..statement(s) endif or depending on the question / conditions if (gender = M OR age > 20) AND member then ..statement(s) endif
125
If parenthesis are not used, all the AND tests are evaluated from left to right and only then the OR tests will be evaluated from left to right. The word NOT may also be used, but must be handled extremely careful, for the beginner-programmer the opposite result might be achieved. NOT has a higher precedence than AND and OR which means it will be evaluated first. You can also refer back to 6.3 page 107 where these logical operators have been summarized in a truth table.
6.14.1 EXAMPLE
Problem Everybody in the town Little River will go to the circus during the weekend. Write an algorithm to determine the entrance fee to the circus as persons younger than 12 years or 60 years of age or more, receive a 25% discount. The user must enter the normal entrance fee and their age in years only. Display the actual entrance fee to be paid on the screen. Description entrance fee persons age actual fee I fee age Type real integer real Name of variable fee age actFee O actFee
Input:
Output:
P Prompt to read fee and age Enter input fields Determine actFee Display actFee
Algorithm: DetermineEntranceFee ~ Enter input data display Enter the normal fee: enter fee display Enter the age: enter age
126
~ test age if age < 12 OR age > 59 actFee = fee - fee * 0.25 else actFee = fee endif
~ subtract discount
~ display actual fee on a new line display This person must pay an entrance fee of R, actFee end Test the program twice: Fee of R50 and an age of 9 years Fee of R80.50 and an age of 32 years Output:
Enter the normal fee: 50 Enter the age: 9 This person must pay an entrance fee of R37.50 Enter the normal fee: 80.50 Enter the age: 32 This person must pay an entrance fee of R80.50
6.14.2
6.14.2.1
Figure 6-9
Authors: HG Erasmus, CM Pretorius Copyright Reserved
127
6.14.2.2
Option Explicit On Option Strict On Public Class frmCircus Private Sub btnCalculate_Click(. . .) Handles btnCalculate.Click Dim decFee, decActFee As Decimal Dim intAge As Integer decFee = Convert.ToDecimal(txtFee.Text) intAge = Convert.ToInt32(txtAge.Text) If intAge < 12 Or intAge > 59 Then decActFee = decFee - decFee * 0.25D Else decActFee = decFee End If lblOutput.Text = "This person must pay an entrance fee of R" _ & decActFee.ToString("N2") End Sub Private Sub btnClear_Click(. . .) Handles btnClear.Click txtFee.Text = "" txtAge.Text = "" lblOutput.Text = "" txtFee.Focus() End Sub Private Sub btnExit_Click(. . .) Handles btnExit.Click Close() End Sub End Class
6.14.2.3
EXAMPLES OF OUTPUT
Figure 6-10
Authors: HG Erasmus, CM Pretorius Copyright Reserved
128
Figure 6-11
6.15
Apart from the NOT, AND and OR operators, Visual Basic.NET also provides for the AndAlso and OrElse operators. Both these operators provide for short-circuit evaluation. We know that for an AND to evaluate to TRUE, both conditions must be TRUE. Therefore, in an AndAlso, if the first condition evaluates to FALSE, the second condition will not even be evaluated because the answer will already be FALSE. We also know that an OR operator will evaluate to TRUE if at least one of the conditions evaluates to TRUE. Therefore, in an OrElse, if the first condition evaluates to TRUE, the second condition will not even be evaluated because the answer will already be TRUE. The AndAlso will therefore produce exactly the same result as an AND, and the OrElse will produce exactly the same result as an Or. However, both these operations will be more efficient. The AndAlso and OrElse operators can be summarized in the following truth table. Condition1 True True False True False False Condition2 True False Not Evaluated Not Evaluated True False Condition1 AndAlso Condition2 True False False Condition1 OrElse Condition2 True True False
129
Input:
Output:
I stName member
P Prompt to read input fields Enter input fields Prepare message Display output fields
O stName message
Algorithm: DetermineEntranceFee ~ Enter input data display Enter student name: ~ display on new line enter stName display Indicate if the student is a member or not: ~ display on new line enter member ~ test membership if member then ~ Equivalent to if member = TRUE message = you must pay R8 entrance fee else message = you must pay R12 entrance fee endif ~ display results display stName, message end
130
Test the program by setting the member to TRUE after the name Sally Jones has been entered: Output:
Enter student name: Sally Jones Indicate if the student is a member or not: TRUE Sally Jones you must pay R8 entrance fee
Test the program again by setting the member to FALSE after the name Billy Ceronio has been entered: Output:
Enter student name: Billy Ceronio Indicate if the student is a member or not: FALSE Billy Ceronio you must pay R12 entrance fee
6.17 6.17.1
A check box is a control that can be added to the user interface in order for a user to indicate whether a certain condition is true or not (e.g. if the student is a member of the club or not). If the user selects the check box, he or she will indicate that the condition is true, otherwise it is false. There may be more than one check box grouped together and a user may select more than one of these check boxes. For instance, when the cost of a parcel must be calculated, it could be necessary to enter the weight of the parcel in a text box. It could also be necessary that the user must also indicate whether the parcel must be insured by selecting a check box and whether the parcel has a high priority or not, by selecting a second check box. It could be possible that a parcel must be insured and has a high priority in which case both check boxes will have to be selected.
131
132
6.18.1
txtName grpCboxes
chkMember
chkStudent lblOutput
btnClear
btnExit
6.18.2
Option Explicit On Option Strict On Public Class frmGym Private Sub btnEntranceFee_Click(. . .) Handles btnEntranceFee.Click Dim strName, strMessage As String Dim decEntranceFee, decDiscount As Decimal Test if member check box has strName = txtName.Text been selected in order to If chkMember.Checked Then determine entrance fee. decEntranceFee = 8D Else decEntranceFee = 12D End If Test if student check box If chkStudent.Checked Then has been selected in order to decDiscount = decEntranceFee * 0.1D calculate discount. Else decDiscount = 0 End If decEntranceFee = decEntranceFee - decDiscount strMessage = " you must pay R" & decEntranceFee.ToString("N2") _ & " entrance fee" lblOutput.Text = strName & strMessage End Sub
133
Private Sub btnClear_Click(. . .) Handles btnClear.Click txtName.Text = "" chkStudent.Checked = False A check box can be cleared chkMember.Checked = False by setting the checked lblOutput.Text = "" property to False txtName.Focus() End Sub Private Sub btnExit_Click(. . .) Handles btnExit.Click Close() End Sub End Class
Figure 6-13
134
Figure 6-14
135
Figure 6-15
136
Improved code: if gender = M distance = 100 else if gender = F distance = 75 else distance = 0 display You have entered an invalid gender endif endif NOTE: This previous if-statement is an example of a nested if-statement that will be discussed in chapter 7.
137
With file processing it could be necessary to check that records being read from the file are in the correct sequence, and to test records for their existence. E.g. before a record is added to a file, a test must be done to ensure that it does not already exist. Similar, before a record can be updated, ensure that it exists and when dealing with arrays, an index test must be done to ensure that the value of the index is in the definition range of the array.
138
Figure 6-16
139
Compulsory arguments: String: This is a string value that must be converted to a new data type. This is typically the Text property of a control where input data has been entered. This is the name of the variable where the TryParse method must store the result of the conversion. It must be of the same type as the datatype portion of the syntax.
Variable:
E.g. Decimal.TryParse(txtSales.Text, decSales) The string that has been entered in the text property of the text box txtSales, must be converted to a numeric decimal value and placed in the variable decSales. The optional arguments will enable the user to enter certain formatting characters such as decimal points and currency characters and it will still be able to successfully convert it to specified numeric data types. More Examples: decAmount = Convert.ToDecimal(txtAmount.Text) is equivalent to Decimal.TryParse(txtAmount.Text, decAmount) intNoStudents = Convert.ToInt32(txtNum.Text) is equivalent to Integer.TryParse(txtNum.Text, intNoStudents) chaDept = Convert.ToChar(txtDept.Text) is equivalent to Char.TryParse(txtDept.Text, charDept) In our example in Figure 6-16, to enter the number of students in a class, we can replace the Convert method by the TryParse method and make use of an ifstatement to display the number of students in the class on a label only if a valid value was entered. If not, a suitable error message can be displayed instead. New code in the code editor for the click event of the btnValidate button:
Dim intNoStud As Integer If Integer.TryParse(txtNoStud.Text, intNoStud) Then lblOutcome.Text = "There are " & intNoStud & _ " students in the class" Else lblOutcome.Text = "The value entered may only be an integer" End If
If an invalid value such as 35.5 or xx is entered, the error message will be displayed as indicated in Figure 6-17. For a valid number such as 77, the message indicated in Figure 6-18 will be displayed on the label.
140
Figure 6-17
Figure 6-18
The TryParse method only tests if the value entered is in the correct format and other input errors may still occur unless we specifically test for it. We know that the number of students in a class must be a positive integer and a value of -7 should also result in an error. However, with our previous code for the click event of the btnValidate button, the following output will be displayed (as indicated in Figure 6-19).
Figure 6-19
141
After we are satisfied that the value entered is an integer, we will have to include a test to ensure that a valid integer is entered. We can either do it in an additional ifstatement (A nested if-statement which will be discussed in the next chapter) or we can modify the code as follows:
Dim intNoStud As Integer If Integer.TryParse(txtNoStud.Text, intNoStud) > 0 Then lblOutcome.Text = "There are " & intNoStud & _ " students in the class" Else lblOutcome.Text = "The value entered must be a positive integer" End If
Our if-statement now tests whether the value entered in the text box can successfully be converted to an integer and if it is greater than 0. This code will produce the output as indicated in Figure 6-20.
Figure 6-20
The outcome of the TryParse method can also be assigned to a boolean variable and this variable can then be used in the if-statement to test whether the conversion was valid. Example: Dim blnValid As Boolean Dim intNoStud As Integer blnValid = Integer.TryParse(txtNoStud.Text, intNoStud) If blnValid = True then lblOutcome.Text = "There are " & intNoStud & _ " students in the class" Else lblOutcome.Text = "The value must be a positive integer" End If
142
6.20.2
As mentioned earlier, the more appropriate way of displaying error messages is by means of a message box as that is peculiar to the windows environment. A message box contains text, one or more buttons and/or an icon. The programmer can design the message box in such a way to support the conveying message. For example, if a message must be displayed to inform the user about a certain process, the icon could indicate that it is information and there only need to be an OK button for the user to click after he or she has read the information.
Figure 6-21
On the other hand, if a certain input error has been detected, the icon could be an exclamation mark to indicate the seriousness of the message and the message box could contain a retry button and a cancel button to allow the user to choose whether he or she would like to rectify the mistake or to cancel the process. If the user must rectify the mistake, an ok button could also be used.
Syntax of a message box: MessageBox.Show(text, caption, buttons, icon, [default button]) caption: Text displayed in title bar of message box text: The message displayed in the message box icon: The icon to be displayed in the message box buttons: One or more buttons to be displayed default button: The button that will automatically be selected if the user presses enter
Figure 6-23
143
The following icons are available: MessageBoxIcon.Exclamation MessageBoxIcon.Information MessageBoxIcon.Stop MessageBoxIcon.Question MessageBoxIcon.None The following buttons are available: MessageboxButtons.AbortRetryIgnore MessageboxButtons.OK MessageboxButtons.OKCancel MessageboxButtons.RetryCancel MessageboxButtons.YesNo MessageboxButtons.YesNoCancel There may be a maximum of three buttons on a message box and any of these three may be set as the default button. This entry is optional and if it is omitted, the first button will be treated as the default. MessageBoxDefaultbutton.Button1 (default setting) MessageBoxDefaultButton.Button2 MessageBoxDefaultButton.Button3 It is once again not necessary to enter the complete method. As soon as you type the . after MessageBox, the word Show will appear and you can only press the tab key to select it. After the bracket, text and caption have been provided, a list of all possible Icons will appear. Use the up and down arrow and press the tab key to select the desired option. The same applies for the Buttons and Default button (See Figure 6-24).
E.g.
Select the required button and insert it by pressing the tab key
Figure 6-24
144
Our example can be modified as follows in order to display the error message not on a label but in a message box.
Dim intNoStud As Integer If Integer.TryParse(txtNoStud.Text, intNoStud) > 0 Then lblOutcome.Text = "There are " & intNoStud & _ "students in the class" Else MessageBox.Show("The value entered must be a positive integer", _ "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End If
It will result in the output indicated in Figure 6-25 if incorrect input data is supplied.
Figure 6-25
6.20.3
String.IsNullOrEmpty METHOD
Sometimes is it necessary to test whether the user has entered an input value before processing can be done. The String.IsNullOrEmpty method will test whether the text property of a control contains a value or not. It can also be used to test whether a variable of data type string, contains a value. The result of this method is a boolean value either true or false, depending on whether the string contains a value. Example 1:
If String.IsNullOrEmpty(txtNoStud.Text) Then MessageBox.Show("You must enter a value first", _ "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) End If
145
Example 2: In chapter 2 we created an application to ask the first name and surname of a user and then display a welcome message to that specific person. The code did not contain any validation and if the user clicked on the welcome-button before entering a name and surname, the output would have been as indicated in Figure 6-26.
Figure 6-26
Although the program produced output, it is a logic error, because it is not the required output. We can modify the code for the click event of the welcome-button as follows in order to code defensivelty.
If String.IsNullOrEmpty(txtFirstName.Text) AndAlso _ String.IsNullOrEmpty(txtSurname.Text) Then MessageBox.Show("You must enter your name first", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else lblWelcomeMessage.Text = "Welcome " & txtFirstName.Text & " " & _ txtSurname.Text & ControlChars.NewLine & _ "We hope it will be fun learning Visual Basic.NET!!" End If
This will result in the output as indicated in Figure 6-27 when the user clicks on the welcome button before a name has been provided.
146
Figure 6-27
6.20.4
We will normally just use a message box to display an error message to the user. The user will have to acknowledge this message by clicking on the OK button and the application will simply continue with normal processing. It is good programming to restore the focus to the relevant input control after an error message has been displayed. In this way the user can then rectify his or her mistake by entering a correct value. A message box need not only be used for error messages. It can also be used to display any other type of message or even an answer of a calculation. A message box can also contain more than one button (e.g. a YES and a NO button). In such a case it is possible to take certain actions based on the user answer. The constant DialogResult followed by a period and the specific button that the user clicked, enables the programmer to instruct the computer which statements to execute based on the action of the user. In order to be able to take a certain action, the message box can either be displayed in an if-statement or it can be assigned to a variable that has been declared of the data type integer. This variable or the complete message box can then be tested against the specific dialog result.
147
The following user choices are possible: Constant DialogResult.OK DialogResult.Cancel DialogResult.Abort DialogResult.Retry DialogResult.Ignore DialogResult.Yes DialogResult.No Example: Up to now, the code for the Exit-button has only contained the statement Close(). However, the user could have clicked on this button by mistake and it would be a good idea to display a message first and ask the user to confirm (Yes or No) whether that is what he or she intended to do. If the user then clicks on Yes, the application can be terminated, otherwise, nothing must be done and the user will still be active in the application. The Exit button will now not only contain the function Close(), but would have to change as follows to accommodate a message box. Meaning User clicked User clicked User clicked User clicked User clicked User clicked User clicked
on on on on on on on
OK button Cancel button Abort button Retry button Ignore button Yes button No button
Simple If-statement to test the action that the user has taken Figure 6-28
The following message box will be displayed after the user clicked on Exit:
Figure 6-29
If the user now clicks on Yes, the application will be terminated, otherwise the user interface will remain unchanged and it may be cleared in order to accept new input and continue with processing for this new data.
148
Exercises
Write the necessary statements to display the following message boxes. 1. 2.
3.
4.
5.
6.
149
Practical
Accept an employees annual salary and then calculate and display his/her net monthly salary. Full time employees pay 29.5% income tax. All other employees pay 25% income tax. Display the gross monthly salary, percentage tax, monthly tax payable and net monthly salary as output. Identify all input and output variables and draw an IPO-chart for this problem Write the algorithm to solve this problem. Design two sets of test data and test if your logic works correctly. Create the user interface as indicated in Figure 6-30. Write the solution in VB.NET and provide for the following: Data validation. Use the TryParse Method and a Boolean variable to test if the annual salary can be converted to a decimal value. If not, display the message box indicated in Figure 6-31. Format all output fields in a suitable way.
Figure 6-30
Figure 6-31
150
OUTCOMES
When you have studied this chapter you should be able to write a nested if-statement in pseudocode and in VB.NET, write an If-ElseIf-statement in VB.NET, use the ToUPPER or ToLOWER methods to change the case of a string, know how to add a radio button control to a form and how to use it in decision statements in the code editor, write algorithms and corresponding VB.NET solutions containing o nested if statements, o select case-statements.
Questions
Before we proceed to more complex if-statements, lets revise by answering the following questions about previous chapters. In each case indicate whether the statement is True or False and provide a reason for your answer. A constant may not be used in an arithmetic calculation. All the steps in any algorithm must always be processed. The following expressions are equivalent: A <= B and A > B. The following expressions are equivalent: X <= 20 and X NOT > 21 There may be any number of statements between the if clause and the else clause of an if-statement.
151
The statement following the else clause is processed when the condition in the if-statement is true In an if-statement without parentheses (brackets), all AND conditions will be evaluated before all OR conditions. The following if-statement will be TRUE is x is a multiple of 7 if x / (x \ 7) = 0 The value of the following condition is TRUE if a = 5 and b = 17 if a > b 13 AND b <= a ^ 2 Evaluating an algorithm for accuracy can also be called desk checking IF 7 < age < 12 is a valid test in pseudocode NOT (NOT 5 = 6 OR 6 = 5) = (5 = 5)
Statement1 and / or statement2 may also be if-then-else-statements depending on the problem statement that will change the general format as follows to a nested if-statement: if condition1 then if condition2 then statement1 else statement2 endif else if condition3 then statement3 else statement4 endif endif
~ if condition1 is true
~ if condition1 is false
Note the indentation in columns in the nested if-statement. A nested selection structure will be used if more than one decision must be made before the appropriate action can be taken. In the above example, condition1 is the outer selection structure and condition2 and condition3 are the inner selection structures. The inner selection structures may also be nested.
Authors: HG Erasmus, CM Pretorius Copyright Reserved
152
if gender = M then if age > 15 then points = 17 else points = 20 endif else if gender = F if age < 18 then points = 18 else points = 21 endif else display Invalid gender endif endif
Following the first else, the points = 20 because in the case where the second ifstatement tests false, the age of this male is less or equal to 15. There is no need to test again for this condition. The same rule (logic) applies to the second part of the if statement where a female is tested. Example 2 The following table contains the values of the real variables A and B and the actions to take when different conditions apply. Value of A 5.2 5.2 6 Value of B Greater than 20 Less or equal to 20 Any value Steps(s) to take Increase the value of A by 5 Decrease the value of B by 3.5 Initialize the values of A and B
Note: To initialize a value means that zero must be assigned to a numeric value and spaces to a non-numeric value.
Authors: HG Erasmus, CM Pretorius Copyright Reserved
153
if A = 5.2 then if B > 20 then A=A+5 else B = B 3.5 endif else if A = 6 then A=0 B=0 endif endif
Visual Basic also provides an If-ElseIf-Else-structure which is sometimes referred to as an extended selection structure. With the normal If-Else nested if-statement, there must be an End If for every ifstatement, regardless whether it contains an else-clause. Sometimes there are a lot of alternatives and the structure may become complex. With the If-ElseIf-Else structure, only one End If is needed at the end of the complete statement.
154
Compare the following two examples in VB.NET If-Else nested structure If chaDept = A Then lblDept.Text = Department A Else If chaDept = B Then lblDept.Text = Department B Else If chaDept = C Then lblDept.Text = Department C Else If chaDept = D Then lblDept.Text = Department D Else lblDept.Text = Wrong department code End If End If End If End If Equivalent If-ElseIf-Else structure If chaDept = A Then lblDept.Text = Department A ElseIf chaDept = B Then lblDept.Text = Department B ElseIf chaDept = C Then lblDept.Text = Department C ElseIf chaDept = D Then lblDept.Text = Department D Else lblDept.Text = Wrong department code End If
155
Dim chaDept As Character If char.TryParse(txtDept.Text, chaDept) Then If chaDept = A Or chaDept = a Then lblDept.Text = Department A Else If chaDept = B Or chaDept = b Then lblDept.Text = Department B Else If chaDept = C Or chaDept = c Then lblDept.Text = Department C Else If chaDept = D Or chaDept = d Then lblDept.Text = Department D Else lblDept.Text = Wrong department code End If End If End If End If Else lblDept.Text = you may only enter one character End If The ToUpper method will convert the input in a certain variable to uppercase before the test is done and the code could be modified as follows: Dim chaDept As Character If char.TryParse(txtDept.Text, chaDept) Then If chaDept.ToUpper() = A Then lblDept.Text = Department A Else If chaDept.ToUpper() = B Then lblDept.Text = Department B Else If chaDept.ToUpper() = C Then lblDept.Text = Department C Else If chaDept.ToUpper() = D Then lblDept.Text = Department D Else lblDept.Text = Wrong department code End If End If End If End If End If In a similar way, the ToLower method will convert the value in a variable to lowercase.
156
The ToUpper or ToLower methods can also be implemented when the value in the text box is converted to the correct data type, e.g. chaDept = Convert.ToChar(txtDept.Text.ToUpper())
157
7.6.4.
If we modify the examples on pages 155 and 156 to enter the department by means of a radio button and we name the radio buttons radDeptA, radDeptB, radDeptC and radDeptD, the code can be implemented as follows: If radDeptA.Checked Then lblDept.Text = Department A ElseIf radDeptB.Checked Then lblDept.Text = Department B ElseIf radDeptC.Checked Then lblDept.Text = Department C ElseIf radDeptD.Checked Then lblDept.Text = Department D Else lblDept.Text = Please select the appropriate department End If As mentioned earlier, it is good programming standard to assign a default radio button to a group. In such a case it will not be necessary to test whether a radio button has been selected or not.
7.7.1.1
PROGRAM PLANNING
Do the planning and write an algorithm to solve this problem. The user has to enter the department code and the current annual salary of the employee. Calculate and display the increased monthly salary. Use a nested if statement without AND and/or OR. Ensure that all data entered are correct. Description department code annual salary new monthly salary Type character real real Name of variable deptCode anSalary monSalary
Input: Output:
158
I deptCode anSalary
P Prompt to read input fields Enter input fields Calculate monSalary Display monSalary
O monSalary
Algorithm:
CalcNewMonSalary ~ Calculate the increased monthly salary ~ Enter input display Provide the department code: ~ display on new line enter deptCode display Provide annual salary: ~ display on new line enter anSalary if anSalary is numeric ~ Convert to monthly salary monSalary = anSalary / 12 ~ Calculate increase according to department code if deptCode = A then monSalary = monSalary + monSalary * 7.2 / 100 else if deptCode = B then monSalary = monSalary + monSalary * 6.8 / 100 else monSalary = monSalary + monSalary * 6.3 / 100 endif endif ~ display result display The increased monthly salary is R , monSalary ~ display on new line else display The annual salary must be numeric endif end
Test the program four times, to cover every outcome of the ifstatement:
Department Department Department Department code code code code = = = = A B G C Annual Annual Annual Annual salary salary salary salary R24000.00 R38500.00 R30000.00 = R5OOOO.OO
When testing the program we will have to include incorrect data as well. In the last example, Os in stead of zeros will cause an error.
159
Output:
Provide the department code: A Provide annual salary: 24000.00 The increased monthly salary is R2144.00 Provide the department code: B Provide annual salary: 38500.00 The increased monthly salary is R3426.50 Provide the department code: G Provide annual salary: 30000.00 The increased monthly salary is R2657.50 Provide the department code: C Provide annual salary: 5OOOO.OO The annual salary must be numeric
7.7.1.2
IMPLEMENTATION IN VB.NET
The user interface in Figure 7-1 has been developed for this example. It contains radio buttons and the code contains a nested if-statement. The default radio button is set to other-department and if a user does not select A or B it will automatically default to the last else of the nested if-statement. The code for the btnCalc button click event will only execute if a valid annual salary has been entered. txtAnSal
radDeptA
radDeptB
radOther
Checked property set to True when created
lblAnswer
btnCalc
Authors: HG Erasmus, CM Pretorius Copyright Reserved
btnClear 160
btnExit
Figure 7-1
EXAMPLE OF OUTPUT
Figure 7-2
161
Figure 7-3
Take note: Although only 2 examples of output screens are provided, you must test your program with all input possibilities, as indicated in our planning, to ensure that the program works in the correct way.
7.7.2
EXAMPLE 2
A vet prescribes medicine for dogs to keep them healthy and strong. The daily dosage depends on the weight of the dog and is calculated according to the following table:
The user must enter the name and the weight of the dog in kilogram (to the nearest 500 gram) and then the program must calculate and display the daily dosage that must be administered to the dog as well as the dogs name.
162
7.7.2.1
Input: Output:
PROGRAM PLANNING
Description name of dog weight of dog name of dog daily medicine I Type string real string real Name of variable name dogWeight name medicine O name medicine
name dogWeight
P Prompt for input data Enter input data Calculate medicine Display name, medicine
Algorithm:
CalcMedicine ~ The algorithm will test whether the name for the dog has been entered and whether the ~ weight for the dog is numeric and is in kg, to the nearest 500g (e.g. 3.5, 5, 6.5). A weight ~ of 7.8 will be invalid. The dosage will only be calculated and displayed if the input is valid ~ Enter name of dog display Provide the name of the dog: enter name ~ Test if name has been entered If name = ~ Outer if-statement Display The name of the dog must be entered else ~ Enter weight only if name has been entered display Provide the weight of dog in kg (to nearest 500 gm): enter dogWeight ~ Test if weight is numeric, in which case it must be converted to the equivalent ~ number in 500g If dogWeight is numeric ~ Inner if-statement 1 number500 = dogWeight * 2 ~ Test if weight entered was to the nearest 500g. If the weight in kg ~ is 3.5, the weight in 500 gm will be 7, If the weight in kg is 3, the ~ weight in 500 gm will be 6. Therefore the weight in 500g will ~ never contain a remainder. If number500 MOD 1 = 0 ~ Inner if-statement 2 If dogWeight < 5 then medicine = number500 * 1 else if dogWeight <= 8 then ~ See comment 1 medicine = number500 * 0.9 else if dogWeight <= 12 then ~ See comment2 medicine = number500 * 0.75 else medicine = number500 * 0.6 endif endif endif display name, must receive a daily dose of , medicine, ml
Authors: HG Erasmus, CM Pretorius Copyright Reserved
163
else
~ else-clause for inner if-statement 2 display The weight must be in kg and to the nearest 500g, e.g. 3, 3.5 or 4
endif else endif endif end ~ else-clause for inner if-statement 1 display The weight entered for , name, must be numeric
Comment 1: In every one of the if-statements in the program above, it only tested one condition of weight e.g. the 2nd if statement: if weight <= 8 It did not test if weight >= 5 AND weight <= 8, because the condition where weight is compared to 5 was already tested in the first if statement. When control is passed to the 2nd if statement (the else part), the weight is definitely greater or equal to 5! Comment 2: In a similar way it is not necessary to test if weight > 8 AND weight <= 12. In the last inner if-statement it is only necessary to test if weight <= 12 as it will already be greater than 8 when it reaches this part of the if-statement. When testing this program it is important to use test data that will test all the borderline cases to ensure that this program yields the correct output in all cases. It is also necessary to test the program with incorrect input data to see if applicable error messages will be displayed. Test the program as follows: Name of dog: Any name Test weights: 3.5, 5.0, 8.0, 12.0 and 25.5 kg Then test the program with weights 1O (O in stead of 0) and 10.8 Lastly test the program where the name for the dog is omitted. Output: Provide the name of the dog: Fluffie Provide the weight of dog in kg (to nearest 500 gm): 3.5 Fluffie must receive a daily dose of 7.0 ml Provide the name of the dog: Daisy Provide the weight of dog in kg (to nearest 500 gm): 5.0 Daisy must receive a daily dose of 9.0 ml
164
Output (Continued):
Provide the name for the dog: Georgy Girl Provide the weight of dog in kg (to nearest 500 gm): 8.0 Georgy Girl must receive a daily dose of 14.4 ml Provide the name for the dog: Danny Boy Provide the weight of dog in kg (to nearest 500 gm): 12.0 Danny Boy must receive a daily dose of 18.0 ml Provide the name for the dog: Victor Provide the weight of dog in kg (to nearest 500 gm): 25.5 Victor must receive a daily dose of 30.6 ml Provide the name for the dog: Lady Provide the weight of dog in kg (to nearest 500 gm): 1O The weight entered for Lady must be numeric Provide the name for the dog: Tinky Provide the weight of dog in kg (to nearest 500 gm): 3.8 The weight must be in kg and to the nearest 500g, e.g. 3, 3.5 or 4. Provide the name for the dog: The name of the dog must be entered
7.7.2.2
IMPLEMENTATION IN VB.NET
The user interface has been designed as indicated in Figure 7-4. The names for the controls are as follows: txtName txtDogWeight lblAnswer btnDosage btnClear In the corresponding code for the btndosage click event, the String.IsNullOrEmpty method and TryParse method have been used to test whether the input data has been entered and whether it is in the correct format. The statement to test if the weight is in kg and to the nearest 500g is similar to that in the algorithm. The program uses the If-ElseIf structure.
165
Figure 7-4
lblAnswer.Text = strName & " must receive a daily dose of " _ & sngMedicine.ToString("N1") & " ml" Else MessageBox.Show_ "Weight must be in kg, rounded to the nearest 500g, e.g. 3, 3.5 or 4 kg",_ "Error, please correct", MessageBoxButtons.OK, _ MessageBoxIcon.Information) End If Else MessageBox.Show("The weight entered for " & strName & _ " must be numeric", "Error, please correct", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End If End If End Sub Private Sub btnClear_Click(. . .) Handles btnClear.Click txtName.Text = "" txtDogWeight.Text = "" lblAnswer.Text = "" txtName.Focus() End Sub Private Sub btnExit_Click(. . .) Handles btnExit.Click Close() End Sub End Class
EXAMPLES OF OUTPUT Examples of valid output are provided in Figures 7-5 and Figure 7-6.
Figure 7-5
167
Figure 7-6
Figure 7-7
168
Figure 7-8
Figure 7-9
169
7.7.3 EXAMPLE 3
The price for hiring a car per day from the Reliable Car Hire Company depends on the type of car hired by a customer. The customer may choose between small (code = S), medium (M) and large (L) cars as can be seen in the following table:
The user is asked to enter the type of car he needs as well as the number of days hired. Calculate and display the total amount he or she has to pay using a nested if statement. There is however a special offer at this moment on the hiring of small cars and a discount of 12.5% is given. Provide for correct input data.
I code noDays
P Prompt for input fields Enter input fields Validate data Calculate amtDue Display amtDue
O amtDue
Algorithm: CalcAmtDue ~ Calculate the amount to hire a car ~ Input display Enter the type of car you need S, M or L: ~ display enter code display Enter number of days for car hire: ~ display enter noDays ~ Validate and calculate amount if noDays not numeric then ~ see example in VB.NET display Number of days entered not numeric ~ display display You entered , noDays ~ display 170
else if code = S or code = s then amtDue = noDays * 200 discount = amtDue * 0.125 amtDue = amtDue discount display The amount due is R, amtDue ~ display on new line else if code = M or code = m then amtDue = noDays * 260 display The amount due is R, amtDue ~ display on new line else if code = L or code = l then amtDue = noDays * 400 display The amount due is R, amtDue ~ display on new line else display Wrong code entered, only S, M or L ~ display on new line display You entered the code , code ~ display on new line endif endif endif endif end When testing this program we have to include incorrect data. We will include a type G car in our test data as well as a non-numeric value for number of days. We will also include a small car because of the special offer, as well as a normal transaction. Test the program as follows: Type of car: Small Large Grand Medium Output: Number of days: 4 3 9 K
Enter the type of car you need S, M or L: S Enter number of days for car hire: 4 The amount due is R700.00
171
Output (continued):
Enter the type of car you need S, M or L: L Enter number of days for car hire: 3 The amount due is R1200.00 Enter the type of car you need S, M or L: G Enter number of days for car hire: 9 Wrong code entered, only S, M or L You entered the code G Enter the type of car you need S, M or L: M Enter number of days for car hire: K Number of days entered not numeric You entered K
lblAnswer
Figure 7-10
btnCalculate
Authors: HG Erasmus, CM Pretorius Copyright Reserved
btnClear
btnExit 172
The fact that the type of car to be hired is indicated by means of a radio button will simplify the code because now it will not be necessary to test if the user entered an incorrect code for the type of car. We can also specify that the small car must be the default button, because the company has a special on small cars, and therefore we can assume that most people would prefer to hire small cars. CODE IN THE CODE EDITOR
Option Explicit On Option Strict On Public Class frmCarHire Private Sub btnCalculate_Click(. . .) Handles btnCalculate.Click Dim intNoDays As Integer Dim decAmtDue As Decimal Dim decDiscount As Decimal If Integer.TryParse(txtNoDays.Text, intNoDays) Then If radSmall.Checked Then decAmtDue = intNoDays * 200D decDiscount = decAmtDue * 0.125D decAmtDue = decAmtDue - decDiscount Else If radMedium.Checked Then decAmtDue = intNoDays * 260D Else decAmtDue = intNoDays * 400D End If End If lblAnswer.Text = "The amount due = R" & _ decAmtDue.ToString("N2") Else MessageBox.Show("Number of days not an integer, you entered"_ & txtNoDays.Text, "Error", MessageBoxButtons.OK, _ MessageBoxIcon.Information) End If End Sub
The code for the click event of the button btnCalculate is much shorter than in the algorithm because radio buttons are used. It is therefore not necessary to test for an invalid car size code. The answer has also been displayed only once at the end of the nested if-statement which is more effective.
Private Sub btnClear_Click(. . .) Handles btnClear.Click txtNoDays.Text = "" radSmall.Checked = True radMedium.Checked = False radLarge.Checked = False Set default button lblAnswer.Text = "" txtNoDays.Focus() End Sub
173
EXAMPLES OF OUTPUT Examples of output are provided in Figure 7-11 to Figure 7-14.
Figure 7-11
Figure 7-12
Authors: HG Erasmus, CM Pretorius Copyright Reserved
174
Because the TryParse statement not only tested that the number of days must be numeric, but that it must also be converted to a variable of data type integer, both the following cases will result in an error.
Figure 7-13
Figure 7-14
Authors: HG Erasmus, CM Pretorius Copyright Reserved
175
Exercises
Write nested if statements without AND and/or OR for each of the following: 1. Calculate the medical aid contribution of an employee. The amount is calculated according to the following table. You may assume that his salary is stored in the variable called salary and his number of dependents is stored in the variable noDepend. Monthly Salary 0 4999.99 5000 and more Dependents any number 0 1 and more Percentage of salary 2% 4% 3.5%
2.
If the field ABC has a negative value, calculate the value of XYZ by multiplying the value of ABC by 2.5, but if the value of ABC is positive, store 35% of ABC in XYZ. If the value of ABC is zero, decrease the current value of XYZ by 8.3%. The variable person contains a code of A for adult or a C for child while the variable member contains a TRUE or FALSE to indicate if a person is a member of a club or not. The club is having a fun day and the entrance fee is determined as follows: An adult member pays R25 and a child member pays R8. A non-member pays 50% more than a member. Store the entrance fee in the variable called fee.
3.
Practical
1. Poppy who always counts her cents to buy the most for her money, needs to buy washing powder. She went to the shop and wrote down the prices of 500 gm, 750 gm and 1 kg washing powder. She wants to write a program to determine which one of the packets is the best buy. Do the calculations and display which packet she has to buy. The user is asked to enter the prices of the different packets.
176
You may test your program with the following test data: 500 gm. 750 gm. 1 kg. R14.85 R21.95 R29.83
test
You may not use these values as fixed values in your program - only as values.
2.
Johnny has saved some money in the bank on which he earns an annual interest of 9.5%. The user must enter the amount he has saved and then calculate the amount of interest he receives monthly. For the sake of the calculation you may assume that an equal amount of interest is paid per month (disregard the different number of days per month). Calculate and display the income tax he has to pay on the interest earned according to the following table: Amount of interest Less than R1000 R1000.01 R2000 >= R2000.01 Percentage tax payable 0 7.5% on the amount > R1000 9.5% on the amount > R1100
3.
The Anything Company has representatives that sell products to the public. These representatives (code = REP) are organized in different areas. Every area has an area manager (code = AM). A region contains 5 areas and has a regional manager (code = RM). The user enters the name, code and amount of sales of the representative, area manager or regional manager (only one of the three). A representative receives a commission of 20%, another 5% goes to the area manager and another 2% goes to the regional manager. Calculate and display how much every person will receive for a transaction. Provide for incorrect input values. Note: If the representative sold the products, he, the area manager and the regional manager will receive commission. If the area manager sold the products, only he and the regional manager will receive commission. If the regional manager sold the products, he will be the only one to receive the total amount of commission.
For each of these practical assignments, design a suitable, user friendly interface and code as effective as possible.
177
~ if no match is found
There may also be more than one statement for an outcome of a specific condition. In the following example different ranges of values are tested to calculate a discounted amount and display the answer. select case noItems case 1 to 10 percentage = 5 display You receive 5% discount case 11 to 20 percentage = 6.4 display You receive 6.4% discount case > 20 percentage = 7 display You receive 7% discount endselect amount = (noItems * price) (noItems * price * percentage / 100) display The amount is R, amount
Authors: HG Erasmus, CM Pretorius Copyright Reserved
178
Questions
True or False? If none of the matches in the case statement is true, it is not possible to do any processing regarding the value that is entered. The case structure can test a maximum of 5 different options. The different cases in the case statement must be in ascending or descending order. The last line in a case structure always contains the word endselect. It is possible to use an if-statement or a case-statement to test any condition.
7.9
The code for the select case structure in VB.NET is exactly the same as indicated in the pseudocode. The End Select will automatically be inserted, similar to the End If for an ifstatement. The code will also automatically be indented. Minor typing errors will also automatically be corrected by the compiler. E.g. Case > 10 will automatically be changed to Case Is > 10. When you use the To keyword, the value preceding the To must always be less than the value following the To. An entry such as Case 20 to 5 will not give an error message, but the results will be incorrect. Another reason why it is important to test your code thoroughly for all input possibilities. Example: Select Case intNumber Case 1 lblMessage.Text Case 3 lblMessage.Text Case 5 lblMessage.Text Case Else lblMessage.Text End Select
Authors: HG Erasmus, CM Pretorius Copyright Reserved
179
price = price * 2 price = price * 1.14 price = price * 0.9125 if price > 50 then price = price + 5 else price = price 4 endif
~ (1 - .0875 = 0.9125)
endselect Example 2 Write a select case statement for the following: if the name is Sally or Tania, display the message she is a girl; but if the name is Jim, John or Russell, display the message he is a boy. select case name case Sally, Tania case Jim, John, Russell endselect
180
read, determine and display the minutes using a select case statement. If more than 400 pages are entered, an error message must be displayed, because none of the prescribed books have that many pages! Pages read 0 - 20 21 - 50 51 - 100 More than 100 Minutes 0 10 40 75
P prompt for pages enter pages determine minutes display minutes / message
Algorithm:
RewardingMinutes ~ Initialise a boolean variable to assume that input entered is valid validPages = True ~ Input display Enter the number of pages read: ~ display on new line enter pages ~ Validate input If pages is numeric select case pages case 0 to 20 minutes = 0 case 21 to 50 minutes = 10 case 51 to 100 minutes = 40 case 101 to 400 minutes = 75 case else display The pages must be > 0 and not more than 400 validPages = False endselect else display The pages entered must be a valid integer endif
181
~ Display output only if input was valid. Display a different message if Summer ~ is not allowed to watch TV if minutes = 0 display You must read more than 20 pages to watch TV, Better luck next time else display Good girl! ~ on a new line display You may watch TV for , minutes, minutes ~ on a new line endif end
Enter the number of pages read: 45 Good girl! You may watch TV for 10 minutes Enter the number of pages read: 432 The pages must be > 0 and not more than 400 Enter the number of pages read: -6 The pages must be > 0 and not more than 400 Enter the number of pages read: 255 Good girl! You may watch TV for 75 minutes Enter the number of pages read: x The pages entered must be a valid integer
182
183
EXAMPLES OF OUTPUT Examples of output due to invalid input are provided in Figure 7-16 to Figure 7-18.
Figure 7-16
Figure 7-17
Figure 7-18
184
Examples of output produced due to valid input are given in Figure 7-19 to Figure 7-21.
Figure 7-19
Figure 7-20
Figure 7-21
185
Exercises
1. Write only the select case statement for the following: If the integer variable xyz contains a 7, 8 or 15, display 3 asterisks, but if xyz has a negative value, 5 asterisks must be displayed. However, if the value is from 10 to 20, then 7 asterisks must be displayed. If xyz contains any other value, display 4 equal signs. 2. Rewrite the following IF-statement as a CASE-statement. If Else If Else If Else If Else If Else sport = Unknown Endif Endif Endif Endif Endif code = B sport = Basketball code = H sport = Hockey code = T sport = Tennis code = R sport = Rugby code = S sport = Soccer
186
Practical
1. Rewrite this program that you have done earlier in this chapter, but use a select case statement instead of a nested if statement. Johnny has saved some money in the bank on which he earns a annual interest of 9.5%. The user must enter the amount he has saved and then calculate the amount of interest he receives monthly. For the sake of the calculation you may assume that an equal amount of interest is paid per month (disregard the different number of days per month). Calculate and display the income tax he has to pay on the interest earned according to the following table:
Percentage tax payable 0 7.5% on the amount > R1000 9.5% on the amount > R1100
2. Enock has a gardening service where he and his workers get paid per hour worked as can been seen in the table below. He also charges an additional R2.50 per hour for equipment used. Enter the hours worked as a real number and calculate and display the amount owed to him. Use a select case statement to calculate the amount.
Hours worked 0-2 >2 4.5 4.6 less than 6 6 and more hours
For each of these practical assignments, design a suitable, user friendly interface and code as effective as possible.
187
OUTCOMES
When you have studied this chapter you should be able to write a loop in pseudocode and in VB.NET by means of the for-nextstatement, know the purpose of an accumulator and implement it in a solution, know when to display output during every execution of a loop and when to display it at the end of the loop, know how to add a list box control to a form, how to set the properties of a list box and how to add items to it, use an input box function to enter data during every execution of a loop, plan and write VB.NET programs for problems that can be solved with an automatic counter loop, in other words where the number of executions of the loop is known.
188
In the case where [step variable2] is omitted a default value of +1 is used. There may be one or many statements in the body of the for-loop. The step may be negative, in which case begin-value must be bigger than endvalue. It is not necessary that the variables must be integers. The step may be a fraction, in which case all variables may be of the data type decimal.
8.3.2 EXAMPLE 2
Use the for-statement to display the consecutive numbers from 1 to 10 in descending sequence. The step must now be negative and the above statements must change as follows: for i = 10 to 1 step -1 display i, ~ on the same line next i The output will now be 10 9 8 7 6 5 4 3 2 1
189
Questions
What will the output be of the following for-loops? 1. for x = 0.5 to 5.5 step 0.5 display x, ~ on the same line next x
2.
3.
4.
8.3.3 EXAMPLE 3
Calculate and display the sum of the first 5 odd numbers: sum = 0 ~ initialize the value of sum in the beginning odd = 1 ~ first odd number for k = 1 to 5 sum = sum + odd odd = odd + 2 ~ move to the next odd number next k ~ move to the next value of k display The sum of the first 5 odd numbers is , sum People often think that they only need the sum right at the end of the processing, so they are only going to calculate the sum just before it is needed. But it simply does not work that way! Right at the end, only the last odd number is available. So, whenever the number (in this case the next odd number) is available, it must be added to the sum. Every number will only be available in the current execution of the loop.
Authors: HG Erasmus, CM Pretorius Copyright Reserved
190
Note that in this example, the answer is only displayed once, after the loop has terminated.
The technique used above to add or summate inside a loop, is sometimes referred to as accumulation. The variable, sum, is called an accumulator. Accumulation is often used in problem solving to calculate a total or an average. If you only add 1 to the accumulator during every execution of the loop, the accumulator is called a counter.
8.3.4 EXAMPLE 4
Display the first 6 multiples of 5 (starting at 5) as well as their sum. Once again, we need the sum of all these numbers right at the end. We can only calculate the sum if we add every number (multiple of 5) to the sum when it is available during every execution of the loop. The sum must be displayed only once, at the end of the loop. However, we need to display every new multiple of 5 before we add it to the sum. We will therefore also need a display statement inside the loop. We can display it just after we have added it to the sum, as long as we display it before the next multiple of 5 is calculated. The loop will have to execute 6 times, because we need to calculate 6 multiples of 5.
Authors: HG Erasmus, CM Pretorius Copyright Reserved
191
Algorithm MultiplesOf5 sum = 0 ~ initialize the accumulator multiple = 5 ~ first multiple of 5 display The first 6 multiples of 5 and their sum: for x = 1 to 6 display multiple ~ on a new line sum = sum + multiple ~ accumulate multiple = multiple + 5 ~ calculate the next multiple of 5 next x display Sum = , sum end
Instruction Assignment Assignment Display For Display Calculation Calculation For Display Calculation Calculation For Display Calculation Calculation For Display Calculation Calculation For Display calculation calculation for display calculation calculation For Display
sum 0
multiple 5
Output
Note that in this example, every multiple of 5 is displayed in the loop and their sum is displayed only once, after the loop has terminated, as can be seen in the output column.
Authors: HG Erasmus, CM Pretorius Copyright Reserved
192
8.3.5 EXAMPLE 5
Enter 8 integers between 5 and 48. Display the average of these numbers. Before we start doing the algorithm, we first have to think about it, make some notes and plan how we are going to do the logic. Once more, we only need the average right at the end, but we need a sum before the average can be calculated. Regarding the average, we need the value of the final sum to be divided by the number of values added to the sum. This can only be done right at the end. The numbers that must be entered must be obtained within the for-loop and added to the sum because that must also be done 8 times. Lastly, the average can only be displayed after it has been calculated in the final stage. Algorithm: AverageOf8Integers sum = 0 ~ initialize the value of sum to add the integers for x = 1 to 8 display Enter any integer between 5 and 48: ~ on new line enter number sum = sum + number next x average = sum / 8 display The average of the 8 numbers is , average end
193
Example 3 in 8.3.3 can be written in Vb.NET as follows: Dim Dim Dim For intSum As Integer = 0 intOdd As Integer = 1 intK As Integer intK = 1 to 5 intSum = intSum + intOdd intOdd = intOdd + 2 Next intK lblAnswer.Text = "The sum of the first 5 odd numbers is " _ & intSum The variable intK can also be declared in the For-loop in which case it will have block scope. Dim intSum As Integer = 0 Dim intOdd As Integer = 1 For intK As Integer = 1 to 5 intSum = intSum + intOdd intOdd = intOdd + 2 Next intK lblAnswer.Text = "The sum of the first 5 odd numbers is " _ & intSum
8.4.2
In VB.NET, when a value is assigned to the text property of a label, that value will be displayed on the label. Example: lblAnswer.Text = First answer lblAnswer.Text = Second answer In this case, the value displayed on the label will be Second answer, because it replaced the previous value assigned to the text property of the label. If output must be displayed on a label during every execution of the loop, it means that the new value must be displayed after the previous value. It must not replace the other values that have been placed onto the label during previous executions of the loop. In such a case, the label must have an initial value (it could be an empty string) and during every execution of the loop, the new value must be concatenated to the value(s) already placed onto the label during previous executions of the loop.
194
Lets illustrate this, by using the following algorithm that has been discussed in Example 4 in 8.3.4. MultiplesOf5 sum = 0 ~ initialize the accumulator multiple = 5 ~ first multiple of 5 display The first 6 multiples of 5 and their sum: for x = 1 to 6 display multiple ~ on a new line sum = sum + multiple ~ accumulate multiple = multiple + 5 ~ calculate the next multiple of 5 next x display Sum = , sum end User interface:
lblOutput
Figure 8-1
Code in code editor for the show output button click event: Private Sub btnShow_Click(. . .) Handles btnShow.Click Dim intSum As Integer = 0 Dim intMultiple As Integer = 5 Initial value for text Dim intX As Integer property of the label lblOutput.Text = _ "The first 6 multiples of 5 and their sum:" & _ ControlChars.NewLine Concatenate every multiple of 5 with the For intX = 1 To 6 lblOutput.Text = lblOutput.Text & _ previous value on label ControlChars.NewLine & _ intMultiple intSum = intSum + intMultiple intMultiple = intMultiple + 5 Go to a new line on Next the label before the multiple of 5 is displayed
Authors: HG Erasmus, CM Pretorius Copyright Reserved
195
lblOutput.Text = lblOutput.Text & _ ControlChars.NewLine & _ ControlChars.NewLine & _ "Sum = " & intSum End Sub Display the sum of the multiples after the loop has been terminated. Concatenate it to the previous contents of the label after a blank line has been displayed
OUTPUT
Figure 8-2
8.4.3 8.4.3.1
In the previous example we have added every new output element to a label by concatenating it to the previous value on the label. The label had to be the right size in order to accommodate all the values that would be added to it, which is not always possible knowing in advance. A list box is a control by which a number of output values may be displayed to the user. These values would typically be added during each execution of a loop. The advantage is that the size of the list box may be set according to the design of the user interface. If the number of elements to be displayed on the list box exceeds the size of the list box, a scroll bar will automatically be added to the list box in order to enable the user to scroll up and down to view all the items in the list box.
Authors: HG Erasmus, CM Pretorius Copyright Reserved
196
Another feature of a list box is that a user may select one or more of the entries in the list box. However this is normally done during array processing and for the purpose of this course, we will only use a list box to display values and therefore the SelectionMode property of our list boxes will be set to None. A list box control can be instantiated (created) by choosing the ListBox in the toolbox window. The name of the list box must be meaningful and must start with lst according to the Hungarian naming convention. Assume we want to design a user interface to display the first 200 even numbers in a list box. The form can be designed as indicated in Figure 8-3. Note that the name of the list box will appear in the design window. The size of the list box may vary according to the design and the scroll bar will only appear when items to be listed in the list box exceed the size of the list box.
In this example a list box, named lstEven, has been added to the form in order to display the first 200 even numbers. In the design window, the name of the list box will appear in the list box.
Figure 8-3
8.4.3.2
The following properties of a list box can be set: Name: Font: SelectionMode: Sorted: Give the list box a meaningful name starting with lst. You may select a certain font and size for list box items. Set to None. In such a case a list box will only be used to list items. No items may be selected. Initially set to false, in which case items will be displayed in the order in which they have been added to the list box. If set to true, items will be displayed in alphabetical or numerical order.
197
If false, every item will be displayed on a new line, otherwise items will be displayed in five columns across the list box. Determine the number of items in a list box. Adds a new item to the list box.
Students are advised to play around and explore with the different properties of a list box. When SelectionMode is not none, but set to indicate that one or more items may be selected, you may also use the SelectedIndex property to get or set the index of the selected item and the SelectedItem property to get or set the value of the selected item. However, this will not be used that during this course.
8.4.3.3
Keep the following in mind when placing a list box on the form: It is recommended that a list box should display a minimum of 3 and a maximum of 8 selections at a time. List box items are either arranged by use, where the entries most used will appear first in the list. Otherwise it is sorted in ascending or descending sequence depending on the application.
8.4.3.4
The items in a list box belong to a collection called the items collection a group of one or more individual objects treated as a unit. The first item in the item collection appears as the first item in the list box. Items can be added to the list box by using the Add method of the items collection.
Object.Items.Add(item)
The name of the list box to which you want the item added
Example: lstNames.Items.Add(Sam) The name Sam is added to the items in the list box called lstNames.
198
The code in the code editor for our example would be as follows if we want to display the first 200 even numbers in the list box when the Display-button is clicked.
Private Sub btnDisplay_Click(. . .) Handles btnDisplay.Click Dim intX As Integer Dim intEven As Integer = 2 For intX = 1 To 200 lstEven.Items.Add(intEven) intEven = intEven + 2 Next End Sub
It would result in the output indicated in Figure 8-4 and Figure 8-5. In the second figure, the scroll bar has been moved to the end of the list box.
Figure 8-4
Figure 8-5
Private Sub btnDisplay_Click(. . .) Handles btnDisplay.Click Dim intEven As Integer For intEven = 2 To 400 Step 2 lstEven.Items.Add(intEven) Next End Sub
199
If the MultiColumn property of the lstEven list box is set to true, the output will be displayed in columns as indicated in Figure 8-6 and Figure 8-7. The scroll bar will then appear horizontally.
Figure 8-6
Figure 8-7
8.4.4
When data must be entered repetitively, it can not be entered into a text box but the input box function must be used instead to display a predefined dialog box. The dialog box should contain a message to prompt the user to enter a value in the input area of the dialog box. The value entered must be stored in a variable that has been declared as data type String, regardless the data type of the value entered. If a numeric value must be entered, it must be stored in a variable declared as data type string and must then be converted to the correct data type before it can be used in calculations.
200
The format of the input box function is as follows and illustrated in Figure 8-8: Variable = InputBox(prompt [, title] [, default value]) The message to instruct the user to enter the correct data. The message must be clear and unambiguous and it must instruct the user clearly how to end the process. The message may also include a variable e.g. Please enter amount & intNum The message Please enter amount 1 would be displayed if intNum contains the value 1. If intNum contains the value 2 during the next execution of the loop, the message would change to: Please enter amount 2 etc. Title: The title that will appear as caption in the input box. It is optional. Default value: A default value may be assigned to the value that will be entered in the input box. A default response for a numeric value could be 0. E.g. strAmount = InputBox(Please enter amount & intNum & ,Cancel to stop, _ Calculation of final Amt due, 0) Prompt:
Figure 8-8
For this example, if the user enters an amount of 60.99, the value in strAmount would be 60.99. In order to use it in a calculation, it would have to be converted to decimal and to be placed in a variable that has been declared as decimal. E.g. decAmount = Convert.ToDecimal(strAmount) Remember, all the validation techniques must still be applied to ensure that the value entered is valid. E.g. strAmount = InputBox(Please enter amount & intNum _ & ,Cancel to stop, Calculation of final Amt due, 0) If Decimal.TryParse(strAmount, decAmount) Then : :
Authors: HG Erasmus, CM Pretorius Copyright Reserved
201
The prompt and the title part of the input box can also be variables: E.g. Dim strPrompt, strTitle, strAmount As String Dim intNum As Integer = 1 : strPrompt = Please enter amount & intNum & _ ,Cancel to stop strTitle = Calculation of final Amt due : strAmount = InputBox(strPrompt, strTitle, 0) : If the default value is omitted, no value will be indicated in the input area. However, if the title is omitted, the project name will be displayed as the title. In the following example only the prompt is provided and the name for the project is Project4 as indicated in the result in Figure 8-9: strAmount = InputBox(Please enter amount & intNum & _ ,Cancel to stop)
Figure 8-9
The user can enter the current input value by clicking on the OK-button or by pressing the enter-key because the OK-button is automatically the default button of an input box.
8.5 8.5.1
Do the planning and write a program to display a series of even numbers. The user is going to ask 2 questions: At what even number do you want to start? How many even numbers do you want to display?
202
8.5.1.1
PROGRAM PLANNING
Description even number to start how many even numbers output even numbers Type integer integer integer Name of variable beginNo howMany evenNo
Input: Output:
I beginNo howMany
P Prompt for input fields Enter input fields Calculate new even number Display evenNo
O evenNo
Algorithm: DisplayEvenNumbers ~ Calculate the desired even numbers display Provide the beginning even number ~ display on new line enter beginNo display How many even numbers must be displayed?~ display on new line enter howMany if beginNo is numeric if howMany is numeric and howMany > 0 ~ test if beginNo is an even number remainder = beginNo MOD 2 If remainder = 0 ~ Use a loop to display the even numbers even = beginNo for x = 1 to howMany display even, ~ on one line even = even + 2 next x else display The begin number must be an even number endif else display The number must be numeric and greater than 0 endif else display The begin number must be numeric endif end
203
Test the program with the following 4 sets of test data: beginNo = 8, howMany = 10 beginNo = 9, howMany = 15 beginNo = 16, howMany = -3 beginNo = x, howMany = 3 Output: 8 10 12 14 16 18 20 22 24 26 The begin number must be an even number The number must be numeric and greater than 0 The begin number must be numeric
Questions
What will the output be if the user enters -16 for a begin value and 9 for howMany? What will the output be if the user enters 0 for a begin value and 4 for howMany?
Exercises
The for-loop in the algorithm above can be changed as follows: for x = beginNo to ((beginNo * 2) + howMany) step 2 display x next x Do a trace table to prove that this last for loop will yield the correct result.
8.5.1.2
IMPLEMENTATION IN VB.NET
The user interface has been designed to display all the even numbers on a label. The two text boxes are named txtBeginNo and txtHowMany and the label to display the answer is lblDisplay. The button to activate the above event is btnDisplay.
Authors: HG Erasmus, CM Pretorius Copyright Reserved
204
CORRESPONDING CODE IN THE CODE EDITOR Private Sub btnDisplay_Click(. . .) Handles btnDisplay.Click Dim intBeginNo, intHowMany, intRem As Integer Dim intEven, intX As Integer lblDisplay.Text = "" If Integer.TryParse(txtBeginNo.Text, intBeginNo) Then If Integer.TryParse(txtHowMany.Text, intHowMany) Then If intHowMany > 0 Then intRem = intBeginNo Mod 2 If intRem = 0 Then intEven = intBeginNo
Data Validation: Test if the two numbers entered are integers and if the second number is greater than zero
For intX = 1 To intHowMany lblDisplay.Text = lblDisplay.Text & _ intEven & " " intEven = intEven + 2 Next Execute the Else loop only if all MessageBox.Show(_ input values are "The begin number must be an even number",_ valid. Display "Error", MessageBoxButtons.OK, _ every new even MessageBoxIcon.Information) value on the label by txtBeginNo.Text = "" concatenating it txtBeginNo.Focus() to the previous End If even values Else already on the MessageBox.Show(_ label "The second number must be numeric", "Error",_ MessageBoxButtons.OK, MessageBoxIcon.Information) txtHowMany.Text = "" txtHowMany.Focus() End If Else MessageBox.Show("The second number must be > 0",_ "Error", MessageBoxButtons.OK, _ MessageBoxIcon.Information) txtHowMany.Text = "" txtHowMany.Focus() End If Else MessageBox.Show("The begin number must be numeric",_ "Error", MessageBoxButtons.OK, _ MessageBoxIcon.Information) txtBeginNo.Text = "" txtBeginNo.Focus() End If End Sub
205
EXAMPLES OF OUTPUT: Three examples of possible output are provided in Figures 8-10 to 8-12. Figure 8-11 provides the answer for one of the previous questions on page 204. We are sure you answered it correctly. Yes, -16 is a valid even number as the program specification did not state that only positive even numbers must be displayed. 0 is also treated as an even number.
Figure 8-10
Figure 8-11
Authors: HG Erasmus, CM Pretorius Copyright Reserved
206
Figure 8-12
8.5.2.1
PROGRAM PLANNING
When planning this program, we need to clarify a few aspects. At first we need to have a value to compare the current mark to in order to determine which mark is lower or higher than the other one. So, we are going to declare a variable called lowest and another variable called highest that will contain the lowest and the highest test marks respectively. There are 2 different ways of doing this: a. Assign a very low value to highest i.e. 1 so that all the remaining values compared to this number will be higher. Assign a very high value to lowest i.e. 101 so that all the remaining values compare to this number will be less. Repeat the process 10 times.
207
or b. Assign the mark of the first student to lowest as well as to highest in order to compare the remaining values to it. Repeat the process only 9 times, because the first value has already been dealt with.
We are going to use the second method in our program. For this program demonstration we are going to assume that all input values will be valid. Description name of student test percentage of student name of best student highest percentage name of lowest student lowest percentage Type string integer string integer string integer Name of variable stName testMark highestName highest lowestName lowest
Input: Output:
I stName testMark
P Prompt for input fields Enter input fields Compare to find results Display output fields
Algorithm: TestResults ~ Find highest and lowest marks of test results ~ Enter the name and percentage for the first student ~ display on new line ~ display on new line
display Enter the name of the first student enter stName display Enter test percentage of the first student enter testMark ~ ~
assign values to highest and lowest names belonging to the test marks must also be stored
highestName = stName highest = testMark lowestName = stName lowest = testMark ~ ~ ~ Execute a loop. Repeat 9 times (from student 2 to student 10) For each student compare his or her marks to the current highest and current lowest mark. 208
for st = 2 to 10 ~ Enter every student name and mark. ~ Indicate number of student in message display Enter the name of student no , st ~ display on new line enter stName display Enter test percentage of student no , st ~ display on new line enter testMark ~ ~ ~ if Compare to highest and lowest mark. If necessary, place new name and mark in variables that keep track of highest and lowest scores highest < testMark then highest = testMark highestName = stName
else if lowest > testMark lowest = testMark ~assign lower value to lowest lowestName = stName ~ store name as well endif endif next st ~ ~ ~ The results can only be displayed after all the names and their test marks have been entered and compared. The final answers are now ready to be displayed. Display on clear screen.
display The name of the student who obtained the highest mark is , highestName ~ display on new display The highest mark obtained is , highest ~ display on new display The name of the student who obtained the lowest mark is , lowestName ~ display on new display The lowest mark obtained is , lowest ~ display on new end Test the program using the following test data:
Name: Danny Bill Don Dave Sonny Edith Bob Robbie Casandra Julie Test percentage: 50 67 92 28 62 54 34 43 64 78
209
Output: The The The The name of the student who obtained the highest mark is Don highest mark obtained is 92 name of the student who obtained the lowest mark is Dave lowest mark obtained is 28
8.5.2.2
IMPLEMENTATION IN VB.NET
The following user interface has been designed for this problem. It contains only a label (lblAnswer), to display the output after the highest and lowest mark (and respective student names who obtained it), have been determined in the loop.
Figure 8-13
210
For intSt As Integer = 2 To 10 strStName = InputBox("Enter the name for the student no " & _ intSt, "Information Systems Test") strTestMark = InputBox("Enter the test mark for student no " _ & intSt, "Enter as an integer percentage") intTestMark = Convert.ToInt32(strTestMark) If intTestMark > intHighest Then intHighest = intTestMark strHighestName = strStName Else If intTestMark < intLowest Then intLowest = intTestMark strLowestName = strStName End If End If Next lblAnswer.Text = "The name of the student who obtained the highest mark is " _ & strHighestName & ControlChars.NewLine & _ "The highest mark obtained is " & intHighest _ & ControlChars.NewLine & _ "The name of the student who obtained the lowest mark is " & _ strLowestName & ControlChars.NewLine & _ "The lowest mark obtained is " & intLowest End Sub
OUTPUT When the user clicks on BEGIN, the input boxes will be displayed and the user must enter the student name and test percentage for every student. As from student 2, the number of the student will appear as part of the message in the message box. The first 4 input boxes displayed are shown in Figure 8-14.
Figure 8-14
Authors: HG Erasmus, CM Pretorius Copyright Reserved
211
When the last test mark has been entered, the loop will automatically be terminated and the following output will be displayed on the label (Figure 8-15).
Figure 8-15
8.5.3
PRACTICAL EXAMPLE 3
In this program we are going to do division by subtracting values using a forloop. The user is asked to enter an integer total number that is greater than 400. Calculate what the result will be if the total number is divided by 5 without using division. The answer must be an integer.
8.5.3.1
Input: Output:
PROGRAM PLANNING
Description total number result Type integer integer Name of variable totNumber result
I totNumber
P Prompt for totNumber Enter totNumber Subtract 5 from totNumber until finished Display result 212
O result
Algorithm: DivisionProgram ~ Divide by using subtraction ~ Initialize the result result = 0 display Enter the total number to be divided by 5 enter totNumber if ~ display on new line
totNumber is Numeric then if totNumber > 5 then ~ Repeat subtracting until totNumber < 5 for y = totNumber to 0 step 5 totNumber = totNumber 5 result = result + 1 if totNumber < 5 then y=0 ~ too small for another subtraction endif next y display The number can be divided by five , result, times else display The number is less than 5, it cannot be divided by 5 endif display The number entered must be a positive integer
else endif end Test the program using 543, 3 and x as the total number Output: The number can be divided by five 108 times The number is less than 5, it cannot be divided by 5 The number entered must be a positive integer
8.5.3.2
IMPLEMENTATION IN VB.NET
The corresponding code in the code editor and output for the above mentioned test data is now provided.
213
OUTPUT Three examples of output are provided in Figure 8-16 to Figure 8-18.
Figure 8-16
214
Figure 8-17
Figure 8-18
Practical
Do the necessary planning and write a solution in VB.NET for each of the following problems. Each solution should contain a For-loop. 1. You have been asked to display a multiplication table. The user has to enter which table (any integer from 1 to 12) he/she wants and then the program must produce the table. Provide for incorrect input and test your program with various tables. If the user entered a 5 the table should look like the example in Figure 8-19:
215
Figure 8-19
2.
Rewrite example 4 in 8.3.4 (applied in VB.NET in 8.4.2) to display any number of multiples of five as indicated in Figure 8-20.
Figure 8-20
216
3.
Rewrite practical example 2 in 8.5.2 to provide for incorrect input. Therefore, if the user enters an invalid test mark for the third student, he or she must be able to correct it before continuing to the next iteration of the loop. The program must also ensure that every student name is entered. The distribution manager of a newspaper uses 25 boys to assist her to deliver the newspapers early in the morning. She has to know what is the average number of newspapers delivered daily and also how many boys deliver more than the average, how many deliver less than the average and how many deliver the number equal to the average. Use a for-next-loop to enter the number delivered by each boy. Display all the totals calculated. (hint: calculate the average using one for-next-loop and then use another for-next-loop to determine the totals). The Direct Postal Service sends parcels to customers world wide. A customer often orders a number of items to be packed in different parcels. Every parcel is marked with the name of the customer, the weight of the parcel and the number of the parcel e.g. if 5 parcels are sent to the same customer, the second parcel will be numbered 2 of 5. The user is asked to enter the name of the customer and the number of parcels (maximum 20 parcels). This number is used to control the for-next-loop. The weight of every parcel (real number) must also be entered before the details for every parcel must be displayed as follows: Name of customer Weight of parcel in kg. Parcel x of y You have to write this program for one customer only.
4.
5.
6.
Keep it Kleen is a company that sells vacuum cleaners. The company uses representatives to sell their stock. Every representative has a goal provided by the company. If the representative sells more vacuum cleaners than the goal, he receives R56.20 as a bonus per additional vacuum cleaner sold. If he has not met the goal, he has to pay R15.75 for every vacuum cleaner sold less than the goal. Enter the name, goal and number of vacuum cleaners sold and then calculate the bonus or amount that must be paid to the company. Display the name and amount for every representative. Repeat this procedure for 15 representatives.
For practical assignments 4 to 6, design a suitable, user friendly interface and code as effective as possible.
217
OUTCOMES
When you have studied this chapter you should be able to understand the difference between a pretest loop and a posttest loop, write a do while-loop in pseudocode and in VB.NET, write a do-loop-until-statement in pseudocode and in VB.NET, know what a sentinel is and how to use it to terminate a do-loop, know the different ways in which a do-loop can also be terminated in VB.NET, write algorithms and corresponding VB.NET solutions containing o do-while-loops, o do-loop-until-statements, o combinations of all structures previously covered, e.g. an ifstatements within a loop etc.
218
If all these conditions were included in a program, it is clear that we really have no idea when the repetition must stop. The program needs a statement to test these conditions otherwise it will run forever (endless loop). There are two types of Do-loops. When planning a solution that contains a number of statements to be repeated several times, the programmer has to decide which type of loop must be used.
9.2.1
The first one is called the pretest loop where the condition is tested before the statements within the loops are processed. Looking at the box office selling the football tickets, the following conditions may occur: Nobody may stand in the line to buy tickets, all the tickets were sold out yesterday or the lady who sells the tickets did not open the box office. In this case no tickets will be sold. An example of this type of loop is: Do while time <= 1700 Statement-1 Statement-2 : Statement-n loop The statements in the body of the do-loop will be processed while the condition is true. As soon as it becomes false, the next statement after the end of the loop will be processed. If it is false the first time when it is tested, it might happen that the statements in the loop will not even be executed once.
9.2.2
The next type of do-loop is called the posttest loop. The statements in the body of the loop will be processed at least once. The condition will be tested only after the statements in the body of the loop have been executed. In this case we may consider an example where only 100 tickets are available but there are 150 people waiting to buy tickets. So, tickets will only be sold until 100 tickets have been sold. An example of this type of loop is: Do Statement-1 Statement-2 : Statement-n loop until noTickets >= 100
219
The statements in the do-loop will repeatedly be processed until the condition at the end of the loop becomes true. It will then proceed to the next statement following the do-loop structure.
9.2.3
There must be a statement in the body of the loop for both the pretest loop and the posttest loop that enables the outcome of the condition tested in the loop control statement to change. If not present, the loop will never end. For example, when sales must repeatedly be entered to determine the highest sales, the programmer may decide to enter a sales amount of -1 to end the loop. Any suitable value may have been chosen to indicate the end of the processing, as long as this value is not a possible valid input to the program. The value is called a sentinel. In VB.NET, a programmer can use a sentinel to end the loop, or make use of the functions provided in the Input Box Function to end the loop (or even make use of both). The input box function provides an easy way to terminate a loop if the user clicks on the Cancel-button or clicks on the Stop-icon.
Ideal way to terminate the loop would be for the user to click on the Cancel-button or the Stop-icon.
Figure 9-1
When the user clicks on either the Cancel-button, or on the Stop-icon, the input box will return an empty string. The programmer can therefore process the loop while the variable is not equal to an empty string. For our previous example, the code could be as follows: strAmount = InputBox_ (Enter the sales amount, -1 or cancel to stop, _ Determine highest sales) Do While strAmount <> AndAlso strAmount <> -1 : : Loop
220
9.3.1
EXAMPLE 1
Calculate the sum of all the consecutive integers starting at 24 while the sum is less than 23456. Display how many integers have been added to the sum. CalcSum ~ Accumulate a counter of integers added to a sum sum = 0 ~ initialize sum see number = 24 comment 1 count = 0 ~ initialize the counter do while sum < 23456 sum = sum + number ~ accumulate the sum number = number + 1 ~ proceed to the next consecutive no count = count + 1 ~ increment count loop display The number of integers added is , count end At this stage it is necessary to understand which statements must be done before processing the loop, what statements must be within the loop and which statements must be placed after the loop to yield the correct results. Comment 1: These statements prepare variables before going into the loop. They initialize the variables with the correct starting values. In the do while control statement the sum is tested to be less than 23456. In the body of the while-loop, the statement sum = sum + number will increase sum. As number is a positive integer, sum will increase until it eventually reaches 23456 or more. At this stage the do while-loop will terminate. The count is also incremented to indicate that the body of the loop was processed once more. Comment 2: It is only possible to print a final count when the condition in the do while control statement is no longer satisfied. ~ see comment 2
221
9.3.2.1
PROGRAM PLANNING
The fishing society had a competition to determine who is the best fisherman. The competition is won by the person who caught the most fish in the given time. For every fisherman, enter the name of the person and the number of fish caught. After all the data are entered a number of fish equal to -1 (sentinel) will be entered. Display the name of the winner and the number of fish caught. Description name of fisherman number of fish caught name of winner Type string integer string Name of variable fmName noFish winner
Input: Output:
I fmName noFish
P Prompt for input values Enter fmName and noFish Determine winner Display winner, noFish
O Winner noFish
Before we start writing the algorithm we have to think about the planning of the loop. The control statement in the do while-loop has a condition and reading the problem statement closely, it is clear that the number of fish is tested in this condition. Once the loop is entered the condition must already contain a value to be tested. The programmer must now realize that the number of fish caught by the first person must be entered before the loop. But there is no necessity to enter the name of the fisherman before the loop is entered. This implies that the number of fish caught by the next person must be entered at the end of the body of the loop to be tested when returning to the do while-loop control statement. Let us proceed with the algorithm: FindFishermanWinner ~ Determine who caught the most fish! winnerNumber = 0 ~ choose low number for winner winner = display Provide the number of fish caught by the first fisherman ~ display on new line display Enter 1 to indicate no more input ~ display on new line enter noFish
222
do while noFish <> -1 ~ test if loop must continue display Provide name of fisherman ~ display on new line enter fmName if noFish is numeric if noFish > winnerNumber then winnerNumber = noFish winner = fmName endif else display The number of fish caught must be numeric endif display Provide the number of fish caught by the fisherman ~ display on new line display Enter 1 to indicate no more input ~ display on new enter noFish loop display The name of the winner is , winner ~ display on new display winner, caught , winnerNumber, fish ~ display on new display Congratulations , winner, !!! ~ display on new end Test the program using the following test data: Name: Sam Johnny Kevin Fred Bill Ted Paul number of fish: 8 2 7 10 5 12 9
line
Output:
Provide the number of fish caught by the Enter 1 to indicate no more input 8 Provide name of fisherman Sam Provide the number of fish caught by the Enter 1 to indicate no more input 2 Provide name of fisherman Johnny : : Provide the number of fish caught by the Enter 1 to indicate no more input 9 Provide name of fisherman Paul Provide the number of fish caught by the Enter 1 to indicate no more input -1 The name of the winner is Ted Ted caught 12 fish Congratulations Ted!!!
Authors: HG Erasmus, CM Pretorius Copyright Reserved
fisherman
fisherman
fisherman
first fisherman
223
9.3.2.2
IMPLEMENTION IN VB.NET
USER INTERFACE
Figure 9-2
strNumFish = InputBox _ ("Provide the number of fish caught by first fisherman,_ enter -1 or press cancel to stop", "Fishing competition") Do While strNumFish <> "" And strNumFish <> "-1" If Integer.TryParse(strNumFish, intNumFish) Then strFmName = InputBox("Provide name of fisherman", _ "Fishing competition") If intNumFish > intWinnerNumber Then intWinnerNumber = intNumFish strWinner = strFmName End If
224
1 strNumFish = InputBox_ ("Provide the number of fish caught by the next fisherman, enter -1 or press cancel to stop", _ "Fishing competition") Else MessageBox.Show_ ("The number of fish caught must be numeric", "Error",_ MessageBoxButtons.OK, MessageBoxIcon.Exclamation) strNumFish = InputBox("Re-enter the number of fish caught by this fisherman, enter -1 or press cancel to stop", _ "Fishing competition") End If Loop lblWinner.Text = "The name of the winner is " & strWinner & _ ControlChars.NewLine & strWinner & " caught " & _ intWinnerNumber & " fish" & ControlChars.NewLine & _ "Congratulations " & strWinner & "!!!" End Sub
Take note: If one statement is too long for one line, a line continuation character (_) must be used to indicate that the statement continues on a new line. However, a literal value (enclosed in quotes) may not be split in the middle of the value. Although our messages, indicated at point (1) and (2) are on one line in the code editor, it was impossible to fit them in one line in A4 format. Please dont see this as a syntax error. EXAMPLES OF OUTPUT When the Enter details-button is clicked, the following input boxes (as indicated in Figure 9-3 to Figure 9-8) will appear. The user must keep on providing the number of fish caught as well as the name of the respective fisherman for all fishermen who entered the competition. These values correspond to the data that was used for desk checking of the algorithm. Take note of Figure 9-6 where an error message occurs and the user must rectify the mistake. When the details for the last fisherman have been entered, the user must enter -1 for the number of fish caught (or cancel or stop must be clicked). The process will then be terminated and the output will be displayed on the label as indicated in Figure 9-9.
Figure 9-3
Authors: HG Erasmus, CM Pretorius Copyright Reserved
225
Figure 9-4
Figure 9-5
: : :
Figure 9-6
226
Figure 9-7
Figure 9-8
Figure 9-9
227
Alexis went shopping and bought a number of different items. Enter the amount of money in her purse and the price of every item. Calculate the total amount. After the prices of all the items are entered, a price of 0 (zero) is entered to indicate that she has finished picking items to buy. If the total amount she spent is more than R100 she will receive a discount of 3.5%. If the money in her purse is enough to pay for her shopping, calculate and display how much money she will have left in her purse after she received any change. If her money is not enough, display a message to indicate how much more money she will need to pay for her shopping. Description price of item money in purse money left in purse money still needed I price purseMoney Type real real real real Name of variable price purseMoney change shortMoney O change shortMoney
Input: Output:
P Prompt for input values Enter price and purseMoney Calculate totAmount Test purseMoney Display results
Algorithm: ~ AlexisShopping total = 0 ~ enter money in her purse once display Enter the amount of money in Alexis purse ~ display on new line enter purseMoney if purseMoney is numeric ~ enter prices for items to buy in a loop if money in purse is valid display Enter the price of the first item ~ display on new line enter price do while price <> 0 if price is numeric total = total + price else display The price must be numeric endif display Enter the price of the next item, enter 0 to stop enter price loop
228
~ the total amount has now been calculated, ~ determine discount, if any if total > 100 then total = total total * 0.035 ~ total = total * 0.965 is equivalent to the statement above endif ~ clear the screen if purseMoney >= total then change = purseMoney total display Alexis has enough money, she now has R, change, in her purse ~ display on new line else shortMoney = total purseMoney display Alexis needs R, shortMoney, more to pay for her purchases ~display on new line endif else display The money in her purse must be a numeric amount endif end Test the program using the following two sets of test data: The amount Item 1 Item 2 Item 3 in her purse is R709.55 R150.50 R285.70 R397.42
Desk checking: The total amount she spent is R833.62 This amount is more than R100, she receives 3.5% discount. The amount due is now R833.62 R29.18 = R804.44 She needs R804.44 R709.55 = R94.89 The amount Item 1 Item 2 Item 3 Item 4 in her purse is R75.00 R3.00 R25.50 R21.60 R7.80
Desk checking: The total amount she spent is R57.90 This amount is not more than R100, she receives no discount. The amount in her purse is now R75.00 57.90 = R17.10
229
Output:
Alexis needs R94.89 more to pay for her purchases Alexis has enough money, she now has R17.10 in her purse
9.3.3.2
IMPLEMENTATION IN VB.NET
USER INTERFACE
Figure 9-10
230
If decTotal > 100 Then decTotal = decTotal - decTotal * 0.035 End If If decPurseMoney >= decTotal Then decChange = decPurseMoney - decTotal lblAnswer.Text = _ "Alexis has enough money to buy all items" & _ ControlChars.NewLine & "She now has R" & _ decChange.ToString("N2") & " change in her purse" Else decShortMoney = decTotal - decPurseMoney lblAnswer.Text = "Alexis cannot buy all these items" _ & ControlChars.NewLine & "She needs R" & _ decShortMoney.ToString("N2") & _ " more to pay for all her purchases" End If Else MessageBox.Show_ ("The money in her purse must be a numeric amount",_ "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) txtPurseMoney.Focus() End If Else MessageBox.Show(_ "Enter the amount in her purse before you click on ITEMS",_ "Retry", MessageBoxButtons.OK, MessageBoxIcon.Information) txtPurseMoney.Focus() End If End Sub
OUTPUT Figure 9-11 gives an example of an error message if the ITEMS-button was clicked before the amount in her purse was entered.
Figure 9-11
231
Figure 9-12 and Figure 9-13 illustrate the example where Alexis has R709.55 in her purse and wants to buy 3 items that are more than this amount. After the third amount has been entered, the user clicked on cancel. The output result in Figure 9-14 will then be displayed.
Figure 9-12
Figure 9-13
232
Figure 9-14
Figure 9-15 to Figure 9-18 illustrate the example where Alexis has R75.00 in her purse and wants to buy items of R3, R25.50, R21.60 and R7.80. She has enough money to pay and will still have R19.13 change in her purse as the output in Figure 9-19 indicates after the user has entered a 0 to end the loop. Take note, in Figure 9-17 the user has entered a wrong amount, in which case a suitable error message was displayed.
Figure 9-15
233
Figure 9-16
Figure 9-17
Figure 9-18
234
Figure 9-19
9.3.4 9.3.4.1
Be Prepared is a company that sells electric and gas stoves to customers. Each of Prepareds salespeople receives a commission based on the total of his or her sales. The algorithm should allow the user to enter the salespersons name and amount of electric stoves sales and the amount of gas stoves sales. It should then calculate the commission on the sum of the sales amounts and display the name and commission for each of the salespeople. A salesman name of ZZZZZ is entered to indicate the end of the input data. The total sales and total commission on sales of all salespeople should also be calculated and displayed with appropriate messages. Use the following information to code the algorithm: Sales in Rand Commission 1 100 000 4% on sales 100 000.01 300 000 R4 000 + 7.5% on sum of sales over R100 000 300 000.01 or more R19 000 + 14% on sum of sales over R300 000 Description name of salesman electric stove sales gas stove sales names of salesman commission earned total sales total commission Type string real real string real real real 235 Name of variable name elecSales gasSales name commission totSales totComm
Input:
Output:
P Prompt for input fields Enter input fields Calculate commission Calculate totals Display name and commission Display totals
Algorithm: SalesmenCommission totSales = 0 totComm = 0 display Enter the name of the first salesman, enter ZZZZZ to stop ~ display on new line enter name do while name NOT = ZZZZZ display Enter the electric stove sales ~ display on new line enter elecSales display Enter the gas stove sales ~ display on new line enter gasSales if elecSales is numeric AND gasSales is numeric totalSales = elecSales + gasSales ~ calculate commission if totalSales <= 100000 then commission = totalSales * 0.04 else if totalSales <= 300000 then commission = 4000 + (totalSales 100000) * 0.075 else commission = 19000 + (totalSales 300000) * 0.14 endif endif ~ calculate totals totSales = totSales + totalSales totComm = totComm + commission ~ display details of one salesman display The commission for , name, = R, commission ~ display on new line ~ proceed to the next salesman display Enter the name of the next salesman, ZZZZZ to stop enter name else display The sales values were invalid endif loop
Authors: HG Erasmus, CM Pretorius Copyright Reserved
236
~ Display the final results display The total amount sold by all the salespeople is R, totSales ~ display on new line display Total commission earned by all the salespeople is R, totComm ~ display on new line end Possible input values with respective output results:
Enter the name of the first salesman, enter ZZZZZ to stop Nicolas Enter the electric stove sales R150799.50 Enter the gas stove sales R200085.50 The commission for Nicolas = R26123.90 Enter the name of the next salesman, ZZZZZ to stop Thomas Enter the electric stove sales R50000.00 Enter the gas stove sales R40000.00 The commission for Thomas = R3600.00 Enter the name of the next salesman, ZZZZZ to stop ZZZZZ The total amount sold by all the salespeople is R440885.00 Total commission earned by all the salespeople is R29723.90
9.3.4.2
IMPLEMENTATION IN VB.NET
USER INTERFACE
Figure 9-20
Authors: HG Erasmus, CM Pretorius Copyright Reserved
237
CODE IN THE CODE EDITOR Private Sub btnStart_Click(. . .) Handles btnStart.Click Dim decTotSales As Decimal = 0 Dim decTotComm As Decimal = 0 Dim strName, strElecSales, strGasSales As String Dim decElecSales, decGasSales, decTotalSales As Decimal Dim decCommission As Decimal strName = InputBox_ ("Enter the name of the first salesperson", _ "Enter ZZZZZ or click on cancel to stop ") Do While strName.ToUpper() <> "ZZZZZ" And strName <> "" strElecSales = InputBox_ ("Enter the electric stove sales", strName) strGasSales = InputBox_ ("Enter the gas stove sales", strName) If Decimal.TryParse(strElecSales, decElecSales) _ AndAlso _ Decimal.TryParse(strGasSales, decGasSales) Then decTotalSales = decElecSales + decGasSales If decTotalSales <= 100000D Then decCommission = decTotalSales * 0.04D Else If decTotalSales <= 300000D Then decCommission = 4000D + _ (decTotalSales - 100000) * 0.075D Else decCommission = 19000D + _ (decTotalSales - 300000) * 0.14D End If End If decTotSales = decTotSales + decTotalSales decTotComm = decTotComm + decCommission MessageBox.Show("The commission for " & strName & _ " = R" & decCommission.ToString("N2"), " ", _ MessageBoxButtons.OK, MessageBoxIcon.Information) strName = InputBox_ ("Enter the name of the next salesperson", _ "Enter ZZZZZ or click on cancel to stop ") Else MessageBox.Show("The sales values were invalid", _ "Please re-enter") End If Loop lblAnswer.Text = _ "The total amount sold by all the salespeople is R" & _ decTotSales.ToString("N2") & ControlChars.NewLine & _ "Total commission earned by all the salespeople is R" _ & decTotComm.ToString("N2") End Sub
238
OUTPUT Figure 9-21 to Figure 9-23 indicate the values entered in the input boxes and respective commission displayed in a message box for every sales representative. When a name of ZZZZZ is entered, the total sales and commission will be displayed as indicated in Figure 9-24. Take note of the error message that will be displayed if an incorrect amount is entered, as indicated in Figure 9-25.
Figure 9-21
Figure 9-22
Authors: HG Erasmus, CM Pretorius Copyright Reserved
239
Figure 9-23
Figure 9-24
240
Figure 9-25
9.4
We have already discussed the do-until-loop which is a posttest loop that tests the condition at the end of the loop. Let us study an example:
9.4.1
PROGRAM PLANNING
Problem statement: Angel has offered to pick strawberries for her mother who wants to cook jam. She needs between 4.5 and 5.5 kilograms of strawberries for the jam. Angel, who is only a little girl can pick and bring between 400 and 900 grams of strawberries at a time to empty her basket into her mothers container on the scale. The user is asked to enter the weight of the strawberries in grams every time Angel brings strawberries. The program must calculate and display how many times she has to go to the garden to pick strawberries before her mother has enough to cook. The program must also display the total weight of the strawberries picked. Description weight in grams number of times total weight in kg I weight Type real integer real Name of variable weight noTimes totWeight O noTimes totWeight
Input: Output:
P Prompt for weight Enter weight Count noTimes Accumulate totWeight Display noTimes, totWeight
241
Algorithm CalculateNumberTimes ~ Calculate number of times Angel picked strawberries noTimes = 0 totWeight = 0 do display Enter the weight of the strawberries in grams Angel picked ~ display on new line enter weight if weight is numeric totWeight = totWeight + weight / 1000 ~ convert to kilogram and add to total weight noTimes = noTimes + 1 ~accumulate count else display weight, is not a valid input value, please re-enter endif loop until totWeight >= 4.5 ~ number of times has been calculated display The number of times Angel picked strawberries is , noTimes ~ display on new line Display She picked a total of , totWeight, kg of strawberries end Test data: Possible input values with respective output results:
Enter the weight of the strawberries in grams Angel Enter the weight of the strawberries in grams Angel 88O is not a valid input value, please re-enter Enter the weight of the strawberries in grams Angel Enter the weight of the strawberries in grams Angel Enter the weight of the strawberries in grams Angel Enter the weight of the strawberries in grams Angel Enter the weight of the strawberries in grams Angel Enter the weight of the strawberries in grams Angel Enter the weight of the strawberries in grams Angel The number of times Angel picked strawberries is 8 She picked a total of 4.570kg strawberries
picked 500 picked 88O picked picked picked picked picked picked picked 880 720 450 570 770 360 320
242
9.4.2
IMPLEMENTATION IN VB.NET
USER INTERFACE:
Figure 9-26
lblAnswer.Text = "The number of times Angel picked strawberries is " _ & intNoTimes & ControlChars.NewLine & _ "She picked a total of " & decTotWeight.ToString("N3") & _ "kg of strawberries" End Sub
243
OUTPUT Figure 9-27 to Figure 9-29 correspond to the test data on page 241. When the total weight that has been accumulated in the loop, exceeds 4.5 kg, the loop will terminate and the output, as indicated in Figure 9-30, will be displayed.
Figure 9-27
: : :
Figure 9-28
Figure 9-29
244
Figure 9-30
Practical
Every one of the following problems contain do-loops. When planning your program you have to decide which type of loop will be the best suited to solve this particular problem. If the problem contains decisions to be made, you may also decide whether you are going to use an if-statement or the select case statement. 1. A number of people joined the Streamline Club during the first week of January and the weight of each member was written on their membership card. During the last week of March everybody was weighed again and their new weights were also written on their cards. Plan and write a program to enter the name, first weight and last weight. Calculate the loss of weight (or gain, if they gained weight) and display the results i.e. name and weight loss or gained with a suitable message. The program will terminate when a beginning weight of 0 is entered. The average weight loss must be display at the end. Jerry is not sure how much money he has, but he knows he has between R100 and R135 in R1, R2 and R5 coins. The user will enter the price of the item he wants to buy. The price does not exceed R100. Jerry pays for the item bought giving one coin at a time to the salesperson. The value of this coin is entered every time he presents the coin and it is subtracted from the 245
2.
amount still due. Determine how many coins he used to pay for the item and display this number. Remember that you do not know how many of what coins he has. There may be an equal number of all the coins, no R1 coins or no R5 coins, etc. Also calculate and display the amount of change, if any. 3. The Walk-In restaurant is very popular amongst employees in the area because they provide home-cooked meals consisting of meat and vegetables already dished up. They provide different meals for men (code = M) and women (code = L). Children (code = C) pay half price of a ladies meal. The prices are as follows: Price per meal Type of meal Men Ladies R20.50 R16.80
The user enters the number of different meals available in the beginning of the program i.e. for men, ladies and children. Every time a person orders meals (He/she may also buy for friends) the type of meal and the number is entered. Firstly, if the meals are available, this number is subtracted from the relevant total and then the amount due is calculated and displayed. If there are no meals of that specific type available, a suitable message must be displayed. If fewer meals than the customer orders are available, a new transaction is started. When all three types of meals are finished, the program will terminate. You may assume that for the sake of this program, all the meals will be bought. (If you want to change the program so that not all the meals are sold, you may include another condition to terminate the program. In this case you can also display how many meals and of what type, are not sold). 4. A florist wants to send coupons to her 420 regular customers based on the number of orders the customer placed during the past year. The amount on the coupon depends on the number of orders according to the following table: Amount on coupon Number of orders 26 7 15 16 30 31 or more The number of orders times R10 The number of orders times R11.50 The number of orders times R14 The number of orders times R17
The user is asked to enter the name of the customer and the number of orders placed. Determine the value of the customers coupon and then
246
display the following message on the screen (In the example the test data name is Carol and the coupon is worth R50). Thank you Carol! You receive a coupon worth R50 to collect lovely flowers!
5.
The learners in the CLEVER SCHOOL pay school fees according to their grade. The name and the grade of the learner must be entered. The learners in the first grade pay R14 for the months February to November (excluding July). The fee increases by R4.50 for every next grade (e.g. 2nd grade pays R18.50, 3rd grade pays R23.00, etc.). Calculate and display the name and annual school fee of every learner in the CLEVER SCHOOL. At the end the average annual school fee must be displayed. A name of ABCD is entered after the details of all the schools learners have been entered. The manager of the Nutcracker Hotel needs a program to print invoices for the guests who stayed at his hotel. The input to this program is the name of the guest, the number of nights he/she spent in the hotel and also the number of breakfasts taken. The number of nights and the number of breakfasts need not be the same. A guest receives one free night and one free breakfast for every night spent in the hotel. You may assume that the number of free breakfasts will never exceed the number of the input breakfasts. The price of a night is R340 and a breakfast costs R65. The invoice for every guest must contain the name of the guest, number of nights stayed, number of breakfasts, number of free nights and the final amount due. At the end of the program the total amount paid by all the guests must be displayed. The programmer has to decide on the sentinel used to end the program.
6.
7.
People who want to hire a machine to wash their carpets usually go to the WishyWashy Company where they can hire any one of 3 types of machines i.e. type A, B or C for heavy duty, ordinary and light washes. The prices for using the machines are as follows: Type of machine A B C Initial cost R50.00 R62.50 R74.87 Additional cost per hour or part thereof R30.00 R36.25 R40.50
The input to this program is the name of the client, the code of the type of machine, the time the machine was used (in minutes).
Authors: HG Erasmus, CM Pretorius Copyright Reserved
247
The amount must be calculated by adding the initial cost to the calculated cost for the time used. Vat of 14% must be added to the amount to be able to present the final amount due to the client to pay. At the end of the program, a total amount, total vat amount and the final total amount due to WishyWashy must be displayed. Choose your own sentinel.
For each of these practical assignments, design a suitable, user friendly interface and code as effective as possible.
248
Pseudocode has been used throughout these notes when planning programs. There are however, different methods that can be used when representing an algorithm. The use of flowcharts and Nassi-Shneiderman methods will now briefly be discussed. We will first write the algorithms for solving the two problems in pseudo-code and then repeat the process using flowcharts, followed by the algorithm using a NassiShneiderman diagram.
2.
PSEUDOCODE
EXAMPLE 1: Write an algorithm to enter 2 numbers that are not equal and display the bigger number. FindTheBigger display Enter a number enter num1 display Enter the next number not equal to the first number enter num2 if num1 > num2 then display num1 is bigger than num2 else display num2 is bigger than num1 endif end
249
EXAMPLE 2: Write an algorithm to enter integers between 5 and 20 until their sum is greater than 200. Display how many integers were entered. CountTheNumber sum = 0 count = 0 do while sum <= 200 display Enter an integer between 5 and 20 enter num sum = sum + num count = count + 1 loop display The number of integers is , count end
250
3.
FLOWCHARTS
A flowchart is a schematic representation of an algorithm. It illustrates the steps in a process and it consists of a number of specific diagrams joined in a specific manner. It graphically represents the program logic through a series of standard geometric symbols and connecting lines. Different flowchart symbols are used for different aspects of the process. Flowchart symbols: The following symbols are used:
Symbol
Description Terminal symbol This symbol indicates the starting or stopping point in the logic. Every flowchart should begin and end with this symbol.
Input/Output symbol
This symbol represents an input or output process in the algorithm. It is used for reading, writing, displaying, etc.
Processing
This symbol is used for types of processing such as arithmetic statements and assigning values.
Decision symbol
This symbol is used to compare different variables / values that may change the flow of the logic. It may cause the logic to branch in another direction.
Module symbol
This symbol represents another module that must be processed. This module will have its own flowchart.
Connector
The connector joins 2 parts of the flowchart e.g. from one page to the next page.
Connecting lines
These lines connect flowchart symbols with one another
251
Examples:
1. Draw a flowchart to enter 2 numbers that are not equal and display the bigger number.
Begin
Enter num1
Enter num2
False
True
End
Figure A1
252
2.
Draw a flowchart to enter integers between 5 and 20 until their sum is greater than 200. Display how many were entered.
Begin
sum = 0 count = 0
False
Sum <= Sum <= 200
Enter num
Stop
Figure A2
253
4.
NASSI-SHNEIDERMAN
A Nassi-Shneiderman diagram (or NSD) is a graphical design representation for structured programming. Developed in 1972 by Isaac Nassi and Ben Shneiderman, these diagrams are also called structograms, as they show a program's structures. Everything you can represent with a Nassi-Shneiderman diagram you can also represent with a flowchart. For flowcharts of programs, just about everything you can represent with a flowchart you can also represent with a Nassi-Shneiderman diagram.
254
We will now draw Nassi-Shneiderman diagrams to solve our two problems: 1. Draw a Nassi-Shneiderman diagram to enter 2 numbers that are not equal and display the bigger number.
FindTheBigger display Enter a number enter num1 display Enter the next number not equal to the first number enter num2 num1 > num2 True display num1 is bigger than num2 End
Figure A3
2.
Draw a Nassi-Shneiderman diagram to enter integers between 5 and 20 until their sum is greater than 200. Display how many were entered.
CountTheNumber sum = 0 count = 0 sum <= 200 display Enter an integer between 5 and 20 enter num sum = sum + num count = count + 1 display The number of integers is , count End
Figure A4
255
5.
INTEGRATED EXAMPLE
Note: The following integrated example illustrates the use of various program documentation tools and concepts. The complete program is modeled using UML (See appendix B). The complete solution is documented using various methods including: Pseudocode Nassi Shneiderman diagrams Flowcharts It is advisable to study each of these documented solutions in order to obtain a better understanding of each of the documentation methods. Problem: Develop an application that will allow a customer to pay his parking ticket at a shopping mall. The customer will enter his ticket into a ticket machine. This machine consists of a card reading module that determines how long the car has been parked. This value (parking duration in minutes) is sent to the ticket application to determine the amount due and to print a receipt after the customer has paid.
For our purposes you may assume that the total minutes supplied will be entered into a text box. The amount due will then be calculated as follows: Time parked <= 1 hour > 1 hour, but <= 2 hours > 2 hours, but <= 3 hours > 3 hours Amount due Free R2.50 R4.00 R4.00 + R1.00 for every full hour and 50c for every part of an hour
If the customer parked for free, his time and a suitable message must be displayed on the label (that serves as a receipt). E.g. You parked for only 45 minutes Your parking is free
If the parking is not for free, the amount due must be displayed on a message box and the user must then enter every amount paid into an input box until the total amount paid is more or equal to the amount due. After every amount has been entered into the input box, the total amount paid and remaining amount due (if any) must be displayed in a message box. When the full amount has been paid,
256
the amount due, total paid and change (if any) must be displayed on the label to serve as a receipt. E.g. Total amount due: R8.50 First amount paid: R5 Message: You paid R5.00. You still need to pay R3.50 Next amount paid: R2 Message: You paid R7.00. You still need to pay R1.50 Next amount paid: R2 Receipt (displayed on label) You parked for 7 hours and 20 minutes Amount due for parking = R8.50 Amount paid = R9.00 Change = R0.50
Output:
hours parked integer minutes parked (less than 1 hour) integer amount due real change to receive real I P Prompt for input fields Enter input fields Calculate time, amount, amount paid, change Display output fields
minutes amtPaid
Algorithm: CalcParking ~ Calculate the amount due for parking totPaid = 0 display Provide minutes parked enter minutes if minutes numeric then hours = minutes \ 60 min = minutes mod 60
257
if minutes <= 60 then amount = 0 else if minutes <= 120 then amount = 2.5 else if minutes <= 180 then amount = 4 else extra = hours - 3 amount = 4 + extra if min > 0 then amount = amount + 0.5 endif endif endif endif if amount > 0 then display Minutes = , minutes, Amount = , amount ~ display on new line else Do display Enter money to pay for parking ~display on new line enter amtPaid if amtoPaid is numeric then totPaid = totPaid + amtPaid endif if totPaid < amount then display Amount still to pay , (amount - totPaid) ~display new line endif until totPaid >= amount if totPaid > amount then change = 0 else change = totPaid - amount endif display Hours = , hours, minutes = , min, Amount = R, amount, change = R, change ~ display on new line else display Minutes parked , minutes, Amount due = 0 ~ display on new line else display Invalid minutes entered ~ display on new line end
258
METHOD 2: FLOWCHART
Begin
TotPaid = 0
Enter minutes
False
Minutes numeric
True
Minutes <= 60
True
False
Amount = 0
False
True
Amount = 2.5
B Amount = 4
Figure A5
259
ExHrs = hours - 3
Amount = ExHrs + 4
Min >0
True
False
Figure A5 (Continued)
260
False
Amount = 0 ?
True
Enter AmtPaid
False
Amountpaid Numeric ?
True
False
Display More
False
Figure A5 (Continued)
261
False
totPaid = Amount ?
True
Change = 0
End
Figure A5 (Continued)
262
totPaid = 0 Prompt for minutes Enter minutes Minutes numeric ? False Display invalid minutes False minutes <= 120 False minutes <= 180 False extra = hours 3 Amount = 4 + extra Min > 0 False True Amount = Amount + 0.5 False Prompt for money Enter amtPaid amtPaid numeric ? False Display incorrect amount entered True Add amtPaid to totPaid TotPaid< Amount False True Display Amount still to pay (amount totPaid) True Amount = 4 True Amount = 2.5 True Hours = minutes \ 60 Min = minutes mod 60 minutes <= 60 True Amount = 0
Until totPaid >= amount totPaid > amount False True Change = totPaid amount Change = 0 Display hours, min, amount, change End
Figure A6
263
Figure A7
264
If decAmount = 0 Then lblReceipt.Text = "You parked for only " & intMinutes &_ " minutes" & ControlChars.NewLine & _ "Your parking is free" Else MessageBox.Show("Your amount due = R" & _ decAmount.ToString("N2"), " ", _ MessageBoxButtons.OK, MessageBoxIcon.Information) Do strAmtPaid = InputBox("Enter money to pay", " ") If Decimal.TryParse(strAmtPaid, decAmtPaid) Then decTotalPaid = decTotalPaid + decAmtPaid Else MessageBox.Show("Sorry, I cannot accept that",_ "Error in money", MessageBoxButtons.OK, _ MessageBoxIcon.Exclamation) End If If decTotalPaid < decAmount Then MessageBox.Show("You paid R" & decTotalPaid & _ ". You still need to pay R" & _ (decAmount - decTotalPaid), " ",_ MessageBoxButtons.OK, MessageBoxIcon.Information) End If Loop Until decTotalPaid >= decAmount If decTotalPaid = decAmount Then decChange = 0 Else decChange = decTotalPaid - decAmount End If lblReceipt.Text = "You parked for " & intHours & _ " hours and " & intMin & " minutes" & _ ControlChars.NewLine & _ "Amount due for parking = R" & _ decAmount.ToString("N2") & _ ControlChars.NewLine & "Amount paid = R" & _ decTotalPaid.ToString("N2") & _ ControlChars.NewLine & "Change = R" & _ decChange.ToString("N2") End If Else MessageBox.Show("You entered an invalid value for hours",_ "Please correct", MessageBoxButtons.OK, _ MessageBoxIcon.Exclamation) txtHours.Text = "" txtHours.Focus() End If End Sub
265
OUTPUT: Example 1: The customer parked for only 45 minutes and the parking is for free.
Figure A8
Example 2: The customer parked for 440 minutes. It is equivalent to 7 hours and 20 minutes and the amount due is R8.50. He pays with a R5 coin and 2 R2 coins.
Figure A9
266
Figure A10
Figure A11
Figure A12
267
EXAMPLE 3: The customer parked for 80 minutes. It is equivalent to 1 hour and 20 minutes and the amount due is R2.50. He pays with a R2 coin and a 50c coin.
Figure A13
Figure A14
Figure A15
268
Figure A16
269
1.
INTRODUCTION
In previous sections of these notes you have been introduced to various techniques for documenting the flow and logic for a specific problems solution. The Unified Modelling Language (UML) is a symbolic language that implements symbols to depict and describe how certain systems behave. The OMG group (http://www.uml.org/ 2008) defines UML by stating that:
"The Unified Modelling Language (UML) is a graphical language for visualizing, specifying, constructing, and documenting the artefacts of a software-intensive system. The UML offers a standard way to write a system's blueprints, including conceptual things such as business processes and system functions as well as concrete things such as programming language statements, database schemas, and reusable software components."
UML consist of various types of diagrams that could be used to represent systems behaviour as well as its functioning. These diagrams include amongst others: - Class Diagrams - Use Case Diagrams - Sequence Diagrams - Interaction Diagrams - State Diagrams - Component Diagrams - Deployment Diagrams As part of this course we will only cover the first three diagrams as listed above.
2.
CLASS DIAGRAMS
Class diagrams are used to depict the various classes used within a system. Classes and objects form part of a programming paradigm called OOD (Object Oriented Design) which includes OOP (Object Oriented Programming). NOTE: VB.NET is a true OOP language which conforms to OOD principles. OOP is a programming methodology that mimics the interaction and behaviour between various real-world objects. OOP as a programming methodology is covered within your normal prescribed textbook.
270
Class diagrams are used to represent objects in terms of its attributes and behaviour (methods). The diagram below depicts the three sections of a class diagram. The objects attributes represents values or other objects that are used to describe the new object. The objects methods represents the actions or tasks that may be performed by the object.
Object Name
Object Attributes
Object Methods
Figure B1
Methods
constructor Create; procedure MarkPaid function GetDuration procedure SetExitTime function GetSerialNumber
Figure B2
3.
A use case diagram represents the uses of a specific solution. In many solutions actors play an important role. An actor is a person or entity that interacts with the system. Actors are represented in UML using a symbol as given below. A use case represents the specific steps or processes in a certain solution. Each use case could also represent a single task. A use case task or process is represented in oval shapes.
271
Figure B3
Actor1
4.
The Use Case diagram example below depicts the various use cases of a user (customer) paying a parking ticket at a parking vendor machine. (refer to the integrated in Appendix A).
Parking Ticket System
ests S Requ
ervice
Process Ticket
Receiv e a Re ceipt
ke t
Clear Ticket
Figure B4
The rectangle is used to indicate what use cases forms part of the systems boundary. The Process Ticket use case could represent a number of steps or a single step in the system.
5.
SEQUENCE DIAGRAMS
A sequence diagram depicts the interaction between the various objects and actors in the sequence in which a process or solution may take place. Where a use case diagram depicts the various use cases (uses) of the system a sequence diagram are used to depict the sequence of processes and the interaction between the objects and actors to perform a specific task. The duration of each of the processes are also indicated.
272
In the example sequence diagram below a customer (Actor) interacts with a parking ticket system. The ticket system needs to interact with a ticket reader in order to obtain the duration of the stay in a parking bay. Sequence diagrams are made up of the following symbols:
Classes
Messages
Actors
The following sequence diagram could depict the interaction between the customer (actor) with the Ticket System.
273
TicketReader
TicketFrmClass
Actor1 Customer
Ticket
Duration
Figure B6
The customer(actor) will insert the parking ticket into the ticket reader the ticket reader will send the duration to the Formclass and activate the process to calculate the amount due. The customer will be prompted for the payment and pay for the parking. A receipt will be printed and the notification of the payment will be sent to the ticket reader. The ticket reader would clear the ticket and return the ticket to the customer.
274
BIBLIOGRAPHY
BURROWS WE, LANGFORD JD: 2003, Learning Programming using Visual Basic.NET, McGraw-Hill, ISBN 0072451963.
ERASMUS HG, FOURIE M, PRETORIUS CM: 2002, Basic Programming Principles, Heinemann, ISBN 0796202222.
FARRELL, JOYCE: 2004, Programming Logic and Design, Thomson Course Technology, ISBN 061926913. KONEMAN, PHILIP A: 2004, Visual Basic.NET, Programming for Business, Pearson: Prentice Hall, ISBN 0130473685. OMG Group 2008 [Online] Available at http://www.uml.org/ Accessed [22/04/2008] ROBERTSON, LA: 2004, Simple Program Design, Fouth Edition, Thomson Course Technology, ISBN 0619160462. SHELLY, G.B. CASHMAN, T.J. ROSENBLATT, H.J. (2006) Systems Analysis and Design 6th Edition. USA: Thompson- Course Technology TSAY, JEFFREY J: 2004, Visual Basic.NET Programming, Business Applications with a Design Perspective (2nd Edition), Pearson: Prentice Hall, ISBN 0130094218. WIKIPEDIA. 2008. From Wikipedia, the free encyclopedia - Nassi-Shneiderman diagram [Online] Available at: http://en.wikipedia.org/wiki/NassiShneiderman_diagram Accessed [22/04/2008] ZAK, DIANE: 2002, Programming with Microsoft Visual Basic.NET, Thomson Course Technology, ISBN 0619016620. ZAK, DIANE: 2007, Microsoft Visual Basic 2005 RELOADED (2nd Edition), Thomson Course Technology, ISBN 1418836230.
275