CHAPTER ONE



WHAT IS WRONG? PUT YOUR FEAR ASIDE!

How many people drive a car without knowing how the engine functions? How many people use the telephone without knowing the conversion process of voice to digit or vice versa? We use many machines daily without understanding how they work. However, people have different expectations when it comes to learning about programming; they want to understand it all. People have heard and seen so much about computers that they expect superior intelligence from them in every situation. They are curious to explore this unknown machine while at the same time are frightened to cause a malfunction. If the computer is not working properly or it is not “friendly” enough, the user assumes that they are not good or intelligent enough to learn about computers or programming. 

You don't have to know it all at once. If you start learning little by little you will overcome the fear. The learning process is just like watching a movie: you don't have to read, listen to, or see everything on the screen to understand or appreciate a movie. In fact we don't see everything in a movie because of limitation of our senses. You just have to focus on the important things. The problem beginners have is that they can’t distinguish what is important from what is not; they mistakenly think everything is important. You don't have to be mathematically or scientifically gifted to understand computer programming. Whether you are a child or an elderly person, you can program. All you need is to combine awareness with effort, and you can make your way through programming.
 

A WORD OF ENCOURAGEMENT:
 

It may be silly to ask these questions, but do you remember how you learned to walk, tie your shoelaces, ride a bike, or drive a car? Isn't it true that through a series of attempts and failures you finally got it? Have you seen a child ice-skate professionally? The combination of fearlessness, continuous practice, and enjoyment is the key to success.

My mission in writing this is to instill confidence in you so that you can gain practical skills in programming. I am going to spend a great deal of time emphasizing how important it is to put your phobias aside and not to give up. Remember that no one is born with the ability to program. Programming is a skill you learn through the process of trial and error. You must have the desire to go for it. 

The pace of learning varies from person to person: some learn faster than others, some learn slowly, but retain the material learned longer. Some people must try harder than others, especially when unexpected situations arise. This may seem like a barrier to learning, but in the long run it is a valuable experience that will provide additional benefits. As experience builds, you will see there are many alternative ways to reach your goal.
 

BENEFIT OF LEARNING PROGRAMMING:


The computer programming is now a pervasive force in our society and our daily lives, and we have little choice about whether we want it or not. Society is divided into two segments: those who know the computer programming those who do not, as matter of fact one out of six of US population alone are End User Developers meaning people who have experience programming. With the emergence of the Internet, programming skills are increasingly valuable, not just for those pursuing a career as a professional programmer. Learning programming enables us to better conceptualize what is happening, and provokes critical thinking on how things are done or might be done. It gives us control over the otherwise overwhelming bombardment of information directed at us from seemingly everywhere in contemporary life. If you take the first step to learn programming, you may find that your creativity will take you further than you imagined. In fact, many accomplished programmers never dreamed of achieving their present success. 

Differentiation: HOW IS THIS BOOK DIFFERENT?

Unlike the traditional textbook format, this book will be presented in a conversational style. In other words, it is a virtual classroom. You are not just a reader anymore, but also a participating student. To ensure optimum comprehension of the subject matter, I will present the material to you from different approaches. Questions like why, what, how, and where are very often asked when the student encounters difficult materials. To address this problem, I attempt to explain such material with several techniques until the solution is clear. I will provide varying models to arrive at a solution using simple words in the hope that if one word is not understood, another might be clearer. 

As a teacher for more than two decades, including nineteen years as a professor teaching programming, I have been searching for a book that teaches how to program and how to use a programming language. Unfortunately, most of the programming books tend to focus on the programming language alone, and explain only grammar (syntax) and the meaning (semantics) of that particular language. Little emphasis is put on the problem-solving capability of the language. Books that do illustrate programming styles and problem-solving techniques are often abstract, hard to follow, and usually incorporate a lot of mathematical notations that intimidate the student. Some books even ignore the most viable programming languages altogether and express the algorithms (solutions) in English like statements (pseudo codes) instead. 

In this book, I am going to balance these two approaches in the proper way. Both language and problem-solving techniques are needed to write a program. This book will teach you how to program in Visual Basic .NET, and how to apply their particular tools to solve problems. Cryptic and arcane notations will be minimized and explained, and difficult material will be approached slowly. From my teaching experience, I have found the following methods make teaching and learning programming fun. Neither the student nor the teacher is ever bored. 

DIFFERENT APPROACHES TO PROGRAMMING

1) Learning by analogy - A programming problem is better understood if you associate it with a similar problem that exists in real life and forming an analogy between the two. A sample analogy for writing a program that puts a series of numbers in order could be compared to the steps needed to sort a deck of playing cards. By forming an analogy between programming concepts and real-life situations, the material becomes easy to grasp and hard to forget. 
2) Learning by chaining - A program is extended to form a new program, and the new program is extended to create a newer program. Studying this chain of related programs promotes incremental learning and improves comprehension of the material. Examples that are “chained” help us to better understand the solution to a problem, and clarify the nature of the problem itself. The same basic example is continually expanded upon and re-incorporated as new subjects are introduced, so that the learning will be incremental and the transition from one subject to the next will be smooth. Also, you can compare different programming methods and problem solving-techniques through “chaining”. This is why the organization of this textbook differs from others.
3) Learning by doing - By testing existing programs and observing the input and output, you gain programming experience. You will be able to test the program yourself and see what is happening. Learning becomes easier when you explore, and analyze the program output by changing the input data. The ability to modify and enhance a program is a very rewarding experience.
4) Learning by creating a demand and providing a supply - Learning can be fun if we know why we should learn a new subject. In other words, what is its contribution? Can we live without it? Will it make certain problems easier to solve? Throwing in a lot of formulas and new information, without any practical justification, frustrates the student and hinders learning. A new subject is introduced only when it is needed (demand). "Why are we learning this?" is the kind of question that I look forward to hearing from my students.
5) Learning by error - Programmers spend many hours rectifying their errors. Studying common errors will help you become more prepared, and prevent you from repeating the same mistakes. Although learning by trial and error is very time consuming, it is widely known by educators that materials learned in this way are more likely to be retained. I will point out common programming errors, and the pitfalls that are most likely to occur in programming and Visual Basic .NET in particular. I will provide the shortcuts best designed to solve the problem on hand. 

In summary, the main purpose of this book is to learn programming in Visual Basic .NET the easy way. Simplicity is the heart of this book, although there is occasional redundancy. I am sure that by investing your time and effort, your newly acquired skill will make you very attractive in the growing job market. 


ACKNOWLEDGMENTS


I want to name everyone who helped me from the beginning, but I feared that I might have forgotten to include the names of some people who have helped me. While I have begun compiling a list, I decided to make my thanks a generic one for now. I am most grateful to my students for their encouragement to start this book and put it together. To my friends who kept me going and finally to my family from whom I took valuable time. Special thanks to Erin William for encouragement and Editor of Prentice Hall for making this book possible..

 

 How to design (build) an interface for a payroll system, a carwash, and a fast food restaurant.

     - Interface is what you see on the screen, between you and computer. Visual Basic is an easy tool for design of interfaces. It is like drawing, but you pick, drop, and type on it.

 

 What is Basic and who has created?

   - Basic means something simple. Here we mean a simple programming language. The purpose of the basic language design was to make an easy and learnable language for programming for everyone even children. One time in elementary school it was a language of choice. The original language Basic was developed in 1964 by two professors John Kemeny and Thomas Krutz, from Dartmouth College in Hanover, New Hampshire. You may have asked yourself why it is called Basic. The word Basic stands for  Beginners All purpose Symbolic Instruction Code, which means a computer language( symbolic instruction code) to do everything (all purpose) for everyone (beginners and more). Basic was the first interactive programming language, and it means to interact with computer back and forth.

  How does an ORIGINAL Basic program (original Basic) look?

 The following program is for you to get familiar as how a program written in Basic looks. This basic program will compute Net Pay salary for an Employee. There are 14 lines of code (statements). In the first 4 lines the input data is set to appropriate name. The word LET is an optional. Due to restriction of original basic only one letter is used to represent each name. The letter E represents Employee ID with the value of 8756. The value 40 is assigned to letter H which represents Hours work and similarly the letter T with value of 0.20 represents Tax Rate, and letter R with value of 25.28 represents Hourly Rate. The line 5 to 7 is the heart of the program where the computation is taking place. Line 5 compute the Gross Pay and assign it to G. Line 6 compute Tax Amount and is assigned to letter name A . Finally in line 7 Net Pay is computed and is assigned to letter N. The line 8 to 13 will display (output) each input and computation.

       1       LET E = 8756
       2       LET H = 40
       3       LET T = 0.20
       4       LET R = 25.28
       5       LET G = H*R
       6       LET A = G*T
       7       LET N = G-A
       8       PRINT "EMPLOYEE ID = ", E
       9       PRINT "HOURS WORKED = ", H
      10      PRINT "HOURLY RATE = ", R
      11      PRINT "GROSS PAY = ", G
      12      PRINT "TAX AMOUNT = ", A
      13      PRINT "NET PAY = ", N
      14      END

 The result output will be display as follow :

EMPLOYEE ID = 8756
HOURS WORKED = 40
HOURLY RATE = 25.28 
GROSS PAY = 1011.2
TAX AMOUNT = 202.24
NET PAY = 808.96


   Original Basic program use one letter to represent each name and * used for multiplication (historical reason). The word LET and =(equal sign) is used to assign a value. The word PRINT used to display the value. It was important that every statement in Basic to start with line number and is mandatory. Therefore only one statement can be written on a line.

  How does a Visual Basic look?   ( Example 1)

The following is for illustration purposes not to be fully understood at this moment. A Visual Basic has two parts, one is visualization (Form) and the other one is programming part (Code).  The following figure illustrate the visualization part of visual basic. Showing a form with 6 input boxes and 6 labels and one button known as Compute in this case. Simply designed by drag and drop and typing. Visualization part is an easy task and you should  not have difficulties to do it. However this is an important feature of visual basic.

 

The following code represent the program for the above form which compute the Net Pay for an Employee. After double-clicking on the Compute button you will type the necessary code.

  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim
employeeId, hoursworked As Integer
Dim
hourlyrate, grosspay, taxamount, netpay, taxrate As Double
taxrate = 0.2
employeeId = TextBox1.Text
hoursworked = TextBox2.Text
hourlyrate = TextBox3.Text
grosspay = hoursworked * hourlyrate
TextBox4.Text = grosspay
taxamount = grosspay * taxrate
TextBox5.Text = taxamount
netpay = grosspay - taxamount
TextBox6.Text = netpay

End
Sub

 

The following figure shows the result of above program after it has been clicked on the Compute button ( execution).

How does a Visual Basic look?   ( Example 2)

 

 

The above form, labels, text boxes, and buttons illustrate the visualization part of VB programming which simply designed by picking these control tools from the tool bar and dropping them in specific place. As simple as you were drawing these shapes and forms.

 

what I need to start writing a program with Visual Basic?

 First you need to have a Visual Basic software ( Compiler) available and working in your computer. In this case we are practicing with Visual Basic .Net version. The VB .Net is provided in a package known as Visual Studio .Net provided by Microsoft. You may need to purchase the software or download the Beta version and Download the free trial Beta version:

 http://lab.msdn.microsoft.com/express/vbasic/
 

 Like working with any other program you need to locate the Visual Basic .Net and activate it and then you are under Visual Basic environment similar as you are in word processing (MSWORD) program and you have to follow certain guidelines.

 

THE FIRST LOOK OF VISUAL BASIC .NET: WHAT DO YOU SEE AFTER ACTIVATING VISUAL BASIC .NET FROM MICROSOFT VISUAL .NET STUDIO?)

The following is the first screen that you will see after activating Visual Studio .Net. From the file menu select the Add Project follow by the new project.

 

 

 

A new window shows the new project and group of languages such as C#, J#, C++ as Project Types. In our case Visual Basic Projects will be selected as shown. In conjunction we must selected templates and our case Windows Application is selected as it shown. You have to give a name to the project and by the default would be WindowsApplication1. A directory known as Visual Studio Project hold all the VB projects for you under a specific drive such as D drive or F drive. However it is a good practice to give a unique and proper name to each project.

 Then click OK.

You will see a Solution Explorer window like the following with a default Form1.vb that we will click to start the design of the form.
 
 

The following figure shows WindowsApplication1 Project with Form1 in the design mode. Note that the toolbox with hammer and ranch on the left of the form and the items are not shown.

VB.NET project form

The following toolbox shows the tools that you can select, drag, and drop to your form. You don't need all of these tools. The maximum you will experience with ten of these. The ten important tools are Text Box, Label, Command Button, Picture Box, Option Button, Check Box, List Box, Timer, Data, and Frame.

 

In property clear the text, make sure it is multi line if you need it. Also you can change the color and etc. At the moment do not change the name and leave it as default. If you need to delete extra boxes use right click mouse to delete it.

In this example we will show seven textboxes and labels to represent:     EMPLOYEE NAME, HOURS WORKED, HOURLY RATE, GROSS PAY, TAX RATE, TAX AMOUNT, NET PAY.

The following window shows the programming part of Visual Basic for Form1 after double clicking on the Form1.

Form1_Load procedure edit window

To compile your program, click Build | Build Solution.

If there are error messages in the bottom window, double-click on each message to go to the location of the error in your file. Fix the errors and build your program again.

Execute your program by pressing F5 or clicking Debug | Start.

http://www.functionx.com/vbnet/applications/payroll.htm

What is Visual Basic?

It is a visualization of original Basic meaning using the tools such as forms, text boxes ,and buttons. Each of these tools can be separately programmed, by double clicking on the tool.

   

CASE STUDY PAYROLL SYSTEM: PHASE 1

You are designing to build a payroll system (program)  from scratch. Choose a name for your company, for example: Dr.Ebrahimi.com Payroll System Inc.   Your job is to research from search engines and people to gather the requirements and  formulate the specifications as what is needed for a payroll system for a small company. There are few employees in the company now but the company is growing.   The program will be in the Visual Basic language and be able to work in the MS Windows and Linux (open source) environments. The program has to be user-friendly (good interface) so people can use the software without problem. At this stage you may not be able to implement this program but as you progress through this book, you will be able to complete this program phase by phase.
At the end of phase I of your project I want to be able to design the form with necessary toolboxes and run the form. All the steps of designing a form and using the toolboxes such as textbox, label, button, and groupbox are explained in this chapter. For the sake of understanding how a payroll system can be very complicated research and try to answer the following. If you answer the following right you are consider as a software engineer.

a)       What would be the requirements and specifications for a small payroll system?

 

b)       What would be the design procedure?

 

c)       How would you implement it?

 

d)      How would you make sure that your software is correct?

 

e)       How would you put it into production and maintain it?

 

       

 

Self-Test True/ False Chapter 1: Evolution of Programming.

 

__1. A systematic way or step by step procedure to solve problem is known as an algorithm.

 

__2. A program is a set of instructions that tell a computer what to do.

 

__3. Every character languages has its own ASCII code, such as 65 for uppercase A and             97 for lowercase a.

 

__4. Computer languages are ambiguous and natural languages are not ambiguous.

 

__5. Visual Basic.net was developed before Visual Basic and Basic.

 

__6. In Visual Basic.net = is used for equality comparison as well as assignment statements.

 

__7. Every problem has only one algorithm to solve it.

 

__8. A complier will not find a logical error, such as substituting addition for subtraction.

 

__9. In order to get an output from a program you must edit, compile, and execute the program.

 

__10. A data file (input file) is a program and can therefore be executed.

 

__11. If there is a syntax error in visual basic.net can you still execute the program.

 

__12. Decision making is also called a loop.

 

__13. Comments in a program can be executed just as statements in the program.

 

__14. Basic, Visual Basic, C, C++, Fox Pro, Visual Basic.net, Java, and C# are all programming languages.

 

__15. The binary state of a computer is represented as 0 and 1 at the lowest level.

 

__16. With the symbol  ‘ you can create a single line of comment.

 

__17. Basic is better than Visual Basic and Visual Basic.net because it is simple object oriented.

 

__18. Visual basic.net is an object oriented software.

 

__19. Visual Basic was developed before Basic and Visual Basic.net.

 

__20. Visual Basic and Visual Basic.net are user Friendly and were designed for teaching purposes only.

 

__21. A Visual Basic program has the extension .vb and a form in the program uses the extension .frm.

 

__22. Visual Basic .net Toolbox consist of text boxes ,command button, check boxes, list box and frame.

 

__23. Basic was line oriented therefore to execute multiple statements you must use goto.

­­

__24.   Basic was designed by two professors John Kennedy and Thomas Krutz from Dartmouth  College.

 

__25.  HoursWorked=Msgbox(“Enter the Employee Id”) is a logically correct statement

 

 

 

CHAPTER TWO

Do you know the computer itself is in a constant cycle of input, process, and output? The computer waits for you to enter the require information even pressing a keyboard. Based on the entered information, the computer takes the appropriate actions (process). Finally, the result is displayed on screen or printed out (output). An analogy for input, process and output would be a food processor ( Juice-maker) where food, fruit and other ingredients are put into the machine. Afterward, based on the selected setting, such as cutting, chopping or mixing, the food processor performs the appropriate task, and finally the desired mixture is ready to be used.

 

HOW TO DESIGN AN  ATM  MACHINE INTERFACE (FORM) AND RUN IT:


Your form should contain Bank name, a picture of the bank in the background or an image on the side, a text for entering the pin or password, a group box with radio button for selecting checking account, and saving account. At the end a textbox for entering the amount of withdraw. To program the interface we need a button and call it WITHDRAW.

 

 Transfer of programming learning knowledge "going from Payroll program to invoice program":

Now that you have learned to design and program the Pay Roll system you be able to design and program an invoice system. For a moment think of the similarities between these two systems. One has the employee name and the other has items name. The Gross Pay program has hours worked and hourly rate while invoice program has quantity and  unit price. The invoice program has sale tax while the pay roll equivalent would be tax rate and both have tax amount. Finally pay roll program has Net Pay and invoice program has total. Remember that tax amount is added to the subtotal while in pay roll program is subtotal.

 

CASE STUDY- PAYROLL PLAN PHASE 2: INPUT/PROCESS/OUTPUT

 

The task of phase two of your pay roll project is to compute gross pay and net pay. In order to practice what you learned so far we are dividing the task into several versions and follow the instruction.

2A) Compute Gross Pay. "Design the form with appropriate names, text boxes, labels, and a button. Assign the input data to the corresponding variables such as employee id or name, hours worked, and hourly rate. Program the button to compute the Gross Pay and then assign the gross pay variable value to a textbox to display.

Name your command button: Compute Grosspay

Beautify your Interface. Use properties for form and each of: textboxes, labels, and Button to reset the text (to clear), back color, font, and etc. Remember that each toolbox has its own properties and its own default number such as textbox1.text, textbox2.text.

 

Use the following input data is as a sample of the input and the output for phase 2A:

INPUT

Employee ID: 5678
Hours worked: 40
Hourly Rate: 15

 OUTPUT

Your Sample output should be:
Gross Pay: 600.00

 

Hint:

 

Visual Basic Tutorial Site: http://www.vbtutor.net/vbtutor.html. Tutorials for older version of VB, which is the VB 6.

 

HW assignment: Pg. 51 #2A, Do it interactively, using variable=inputbox (“…”) and MsgBox (“…”)

 

HINTS-----

 

Version I:

FAQ: How do you know what to DIM (what to declare?)

ANS: as soon as you have a name, you have to have a declaration for it. If it is dealt with money, it is fraction, and you DIM the variables as Single. If it is an integer, you need to DIM the variable as Integer. For more of this information, please refer to pg. 39 in Volume 1 of C++ Programming Easy Ways.

Version II:

            Goal: to familiarize yourself with textbox. After interaction, the variables will be assigned to the appropriate textboxes. In this operation, you don’t need to use the MsgBox.

            DIM employeeid as integer

            employeeid=Inputbox (“ENTER THE EMPLOYEE ID”)

            TextBox1.text=employeeid

            ……

Version III:

            Use button for computation, and use appropriate textboxes. In this case of Gross Pay, you probably need 4 textboxes. And in the case of Net Pay, you may need 6 textboxes, one for taxamount and the other for netpay. Use 3 buttons, one for gross pay, one for taxamount computation, and one for netpay. And place the buttons in the proper order. Tax rate has its own textbox in this case, and default value in property is set to 0.30.

SUBMISSION RULES OF THE HOMEWORK:

·        EACH HOMEWORK SHOULD HAVE COMMENTS EXPLAINING WHAT YOU ARE DOING IN THE PARTICULAR HOMEWORK.

For example the following line is a comment starting with single quotation:
' My name is Mike and this is a gross pay program'

·        PLEASE BRING IN A PRINT-OUT OF YOUR HOMEWORK WITH CODES AND THE OUTPUT OF THE PROGRAM. USE ctrl+Print Screen TO COPY THE OUTPUT SCREENS TO THE CLIPBOARD AND THEN  PASTE IT  TO THE WORD DOCUMENT. Each time take a snapshot and paste it to the word document,

·        THE COPY OF THE FORM, CODES, AND SAMPLE OUTPUT SHOULD BE IN THE HOMEWORK SUBMITTED.

 

 

2B)  This part of the phase is to compute the netpay by applying a fixed tax rate of 30% and calculating the tax amount. You must enter employee’s id. (Enter only last for digits of SSN).  For the output display you should use textboxes.

1. Gross Pay Button: Orange

2. Tax Amount: Yellow

3. Net Pay Button: Blue

 

Note:

·        In order to understand the order of execution use three buttons

1 Compute Gross pay

2 Compute Tax Amount

3 Compute Net Pay

 

·        Input must be separated by the calculation button which processes the output.

 

·        You must go step by step if your Gross pay button does not computer correctly do not move onto Tax amount button until the problem is fixed.

·        At this time you may ask the question: Why do I need Employee ID? You may wonder, what is the purpose of using employee id?  However this payroll plan is escalating, later on you will use the employee id to reflect the employee information.  

 

 

 

 

2C)   Now repeat 2A instead of entering data into the textboxes, use inputbox to receive input and assign it to corresponding variable, employeeid, hourlyworked, hourlyrate. Msgboxes (will display the computed variable grosspay.)

Employeeid= inputbox(“ Enter Employee Id:”)

Or

Textbox1.text= inputbox(“Enter Employee Id:”)

Refer to page 45

Texbox2.text=inputbox(“Enter Hours Worked:”)

 

 

Hint:

msgbox ( “ You Employee ID IS: “& employeeid &char(10)&_

           “Your Hours Worked IS:” & hoursworked &char(10)&_............

 

2D) Now repeat 2B instead of entering data into the textboxes, use input boxes to receive input and assign it to corresponding variable, employeeid, hourlyworked, hourlyrate. Msgboxes will display the computed variable netpay.

 

Extra Work:

Const taxrate as single.

 

 BUILDING An INVOICE system "easiest ways" :first version:

1. Activate the VB .net from visual studio and start a new project and name your application as invoice. If you have problem review your chapter one.

2. Design the form by changing the text ( Ebrahimi invoice INC.) and placing the tool boxes, labels, and a command. Remember the changes are done in properties. Go to the text clear or retype and press enter.

3. Program the  button by clicking on it. Do not try to figure out other extra programming words that you see at this moment just type where the marker is which is between sub button1 and end sub. There are five lines of the codes such as Public class, Inherits, Private sub, End sub, and End class which are provided automatically by Visual Basic and we will get to that at way later time. Do not delete or change them because it will cause problems.

Invoice System Form "snapshots illustration":

 The following snapshot illustrate the form for the Invoice System. The text of the form is changing the properties of the form and it is ready to place the toolboxes into the form. Remember that toolbox window is in the left of the form as it is shown with "hammer and the ranch " logo. The property for each form and toolbox item are on the right of the form.

 

 

Running the invoice program: Easiest version:

The following illustrate snapshot after the debugging by choosing the menu from the debug "Start" or "Start without debugging" ( for shortcut:F5 or ctrl F5) the program (Running or Executing). Realize that the form is changed ( smooth) and you have entered the data for Item Name, Quantity, and Unit Price and you press the button "Compute Subtotal" and the result will be displayed. Note that Quantity is in textbox2 and Unit Price is in textbox3 and the result is placed (assigned)in textbox4 which is Subtotal.

 

 

HOW TO CHANGE THE NAME OF THE TOOLBOX ITEMS:

By default Visual Basic give you an ordered number for each toolbox item such as textbox1.text, textbox2.text, and textbox3.text. Similarly label1,label2,and label3. Why is it better to give a name to each toolbox item?  The answer is it will identify the toolbox better and you can remember and use it in your program. For example: Renaming the textbox1 to textbox4 to txtName, txtQuantity, txtUnitPrice, and txtSubtotal. To change the name of toolbox must be done in each property. Similarly the name of button will change to btnComputeSubtotal. Convention for the naming of toolbox is that you start with three letters of toolbox item and follow by the name. Remember do not leave a space between the words and capitalize first letter of each word. The abbreviation for textbox is txt, for label is lbl, for button is btn, and for form is frm. Warning: Do not change the names of item items back and forth that will cause the problems.( talk to Microsoft).

 

what is wrong in using a textbox for numerical data?

A textbox as the name suggest is used to hold a text (characters) not a numerical value for example a text "123" is not one hundred twenty three but just one, two, and three. Visual Basic compiler convert a text to a numerical value when applying arithmetic operation  however there is a danger of not doing it right the way you want it. For that reason you must convert it to number such as integer, single, or double. For your information integer means the whole number such as "123" and single and double mean number with fraction such as "123.45".

In the below snapshot the + operator will concatenate both text values instead of adding them. The solution is to convert the text to number and more specific to integer, single, or double.

 

After correction in codes:
 

txtTotal.text = CSng ( txtSubtotal.text) + CDbl ( txtTaxAmount.text)

CInt ( txtQuantity.text) * CSng ( txtUnitPrice.text) 

 

 

RECAPPING ASSIGNMENT # 2:

The major steps in solving problems is  to understand what a problem wants and then divide the  problem into sub problems. To solve the main problem you need to solve each sub problems.  For example in the pay roll program the main problem is to compute the salary however to compute the salary we need to compute two sub problem and then such as gross pay and net pay. The order of  solving the sub problem is important. You have to solve gross pay before net pay. You should ask your self what do you need  to solve a gross pay and what you need to solve  net pay? What are the input for gross pay?.  What are the input for net pay?  We need two input one is gross pay and the other one is tax amount. The new sub problem  here is to compute tax amount that should be done before the net pay. In order to compute tax amount you need to have gross pay and tax rate. In this program for simplicity tax rate is fixed such as 30% (0 .30). In assignment #4 we are going to compute varies tax rates according to the government rules. The way you are asked to design the form is very  important for example you are asked to have two buttons instead of one button. In case of two buttons each one will have its own program. To understand the program you may want have three buttons and place them proper location.  

 

 

CHAPTER THREE

RECAPPING ASSIGNMENT # 3: REPEATING PAY ROLL FOR MORE THE ONE EMPLOYEE

To do the assignment you need to know what makes program to go more the one times. You don't need to change anything in your computation you just need to add a Visual Basic loop to your program  such as for loop or while. Adding a loop is a minor change in you programming code and  will have additional maximum of five lines of code.  For example adding for loop you require only three line of code :

DIM counter AS integer

For counter = 1 to 5

 -----------------

------------------

next counter

As shown bellow while loop requires only additional lines:

DIM counter AS INTEGER

counter = 1

WHILE counter <=5

------------------

------------------

counter = counter + 1

end while

For adding a loop  make sure to place your previous program ( assignment #1) or code inside the loop.

LOOPING THE INVOICE PROGRAM

Giving a little background,  invoice program will compute the subtotal and total of items purchased. Your Visual Basic form should include itemname or Itemid, Quantity, Unitprice, Subtotal, Salestax, Taxamount and Total. I hope you know how to design this form if not repeat (loop) previous chapter. The question is  why do we want to loop the invoice program? The first question is How does the Visual Basic  loop work? The second is How can we change the program?, and the third is How can we benefit from it overall? To start the invoice program assume that we have five customers. For each one we will create an invoice and again assume that at the beginning each will have a simple purchase. Before we start, imagine how you can see this program having many customers, many items of different price, and generating or searching for price automatically. For purpose of new learning and simplicity, program the form by double clicking on it (form1_load). Do not use any buttons, your loop program will automatically execute as the form will be loaded. 

First Version of the program and its running:                         

CHAPTER FOUR

DECISION MAKING:

 

This is the most important element of our life is about decisions making. Usually the answer evaluates “True” or “False” and based on each evaluation we take an action. As human we are constantly in decision making process. Starting with today find out how many decision have you made today related to your work, mind, and body. Decision making is very important and without it there would be no choices. And without good decision making there wouldn’t be accuracy and intelligence. A chess champion wins because of decision making and similarly a chess program wins because of decision making.

 

 

 

 HOW DOES COMPUTER MAKE A DECISION?

 

Computer is in constant process of making decision as it has been programmed. For program to make a decision you have to have a word (construct) that tells the program to make a decision. The famous word in a programming language is to make a decision is “IF”. The statement that responsible for decision making is known as “IF Statement”. Visual Basic if statement has the following general syntax (grammar).

 

If condition then

   ‘Process the truth of the condition

Else

    ‘Process the false of the condition

End If

 

The four words (reserve words) that make the Visual Basic If Statement

     

The first word “IF” tells the program that you are making a decision. The second word “THEN” tells that you are processing the truth of the condition. The third word “ELSE” tells that you are processing the false of the condition. And the last word “ENDIF” shows the end of If statement.

 

If ……….. Then
 …………….
…………………
…………
Else
…………
………..
End If

 

 

WHAT IS THE CONDITION OF THE IF STATEMENT?

 

The condition of “If statement” would evaluate to true or false and this is known as Boolean expression. In the following example the condition has two values with comparison operator “>’. However you can use any variable(s) with other operators (logical).

Example1:

If  3>2  then
      Msgbox ( “always true”)
Else
      Msgbox (“ always false”)
End If

 

( output is true)

 

 

Example2:

If  2>3  then
      Msgbox ( “always true”)
Else
      Msgbox (“ always false”)
End If

 

(output is false)

 

 

Important example of program control flow (IF statement and loop)] " ATM scenario":

      You are at the ATM machine and you are asked to swipe your card (Entering ID) then enter your password (bin) and you able to see series of options (decision)  such as your Balance, Withdraw, Transfer, Deposit and etc. For each option there would be series of operation which include other decisions. For example there is a decision to check the amount of balance against your withdraw. The following demonstrates the password program construction of ATM machine step by step. In step one we will have a form with a textbox for a password entry and a command button to process the simple decision making and a label to display the result.

After programming the button which has an If statement that compare the textbox entry with supposed passw3ord  and run it the following will be display: (For simplicity we have chosen a fix password for everyone)

 

 

ATM sample scenario 2  is you've given four choices:

 

To make the program run more than one time we need a loop and in this case we are going to use the For loop.

For counter=1 to 4
.................
................
next counter

 

 

 

 

 SECOND STEP FOR ATM MACHINE:

 

Problem with previous program was that we had a generic password and we want one password for each person. We have two solution:

1) Use the file: create the file using an editor such as notepad and type for each individual ID and associate password and inside the program declare the file and use the file.  "ebrahimi","mahrokh","kodoochi
                                                       "13212fe","ew545wfew","ret34534"

2) Use the array:

                               Dim name as string = [ "ebrahimi","mahrokh","kodoochi"]
                       Dim password as string = [ "13212fe","ew545wfew","ret34534"]