Docstoc

Week3

Document Sample
Week3 Powered By Docstoc
					Conditional Statements

Tonight we will discuss conditional statements in Visual Basic .NET. Prior to that
however we will discuss how algorithms work in general in computer languages.

What is an Algorithm

The word algorithm is comes from the name of a historical mathematician Mohammed
ibn-Musa al-Khwarizm. In all technicality there is really no one standard agreed upon
definition of what constitutes an algorithm, however, it is best defined as a procedure to
solve a problem in a pre-defined number of steps. The best example often given for an
algorithm is a cooking recipe.

Algorithms in computing take in inputs, as we saw last week in variables. They also
produce some sort of output. In between there is a logical path to that output. There are 3
major types of logical paths that we will now discuss.

Do Something in a Specified Order

Lets consider what we have done so far in our programs. We have started from main, and
gone one line at a time until the final outputs have been achieved. This type of logic is
obviously the simplest. What is important is that the steps are designed in the correct
order. Sometimes an incorrect order can produce the overall end result but end up with an
unwanted glitch. For example, consider this algorithm borrowed from Dr. Harvey Dietel

   1.   Wake Up
   2.   Take Shower
   3.   Get Dressed
   4.   Eat Breakfast
   5.   Go to work

In this algorithm, all steps are done in their respective order ending up with the output
that a clean dressed person is at his / her job. Consider what happens when the steps
within the order are changed.

   1.   Wake Up
   2.   Get Dressed
   3.   take Shower
   4.   Eat breakfast
   5.   Go To Work

In the above example the individual will end up at work with soaking wet clothes.

The second concept of logical paths is the one in which we will focus on tonight.

Do Something based on Conditions



                                                                                             1
Ever been in a restaurant during the day and there is hardly any customers and wonder to
yourself, “Does it really make sense for this restaurant to be open right now?” An
economist might tell you this, If marginal costs are less then or equal to marginal
revenues in slow hours it makes sense to be open during them. Else it would not make
sense. In this type of logic we are making a choice between options based upon the value
of one or more variables. In the above example we consider two variables, marginal cost
and marginal revenues. Sometimes there may only be one or two options, sometimes
sthere are numerous options to chose from. Above we consider two options, to open or
not to open. Programming languages all have a mechanism to provide logical paths based
on one or more conditions. The statements that are used to break the flow of logical paths
are called Flow Control Statements. Tonight we will see how to control flow based upon
conditions.

Do something until a certain condition has been achieved

When you teach a child to catch a football, you tell him to “Keep your eye on the ball
until you have made the catch.” When we deal cards in a card game we deal a card to
each individual in the array of players at the table.
These are examples of real world repetitive logic. In flow controls that we cover next
week we explore the methods used to achieve this.

But for now lets jump into conditional statements.

The IF Statement

The if statement is the most bread and butter statement used in Visual Basic. In its
simplest form it follows this syntax

If CONDTION Then
       LINES OF EXECTION…
End If

The condition itself is any expression that could be evaluated a value of 0 or not zero. 0 is
always false. Anything other than zero, even a negative number is always true.

If the condition is true then the lines in between the if statement and end if will execute.
Then the code will continue with lines after end if. If it the condition is not true, then the
code jumps to line after end if.

It is legal, however I do not recommend doing this,

If CONDITION THEN SINGLELINE

This is for many people harder to read. But basically if you only have one line of code to
execute after your if statement you can put that single line on the same line as the if and
not have to type end if.



                                                                                                 2
Lets do our first simple example tonight. This example will demonstrate the if statements
and then we look at some more ways the if statement can be used.

Start a new console application. Here is the code

Module Main_Module



     Sub Main()
         If 1 Then
             Console.WriteLine("1 is true")
         End If
         If 0 Then
             Console.WriteLine("0 is true")
         End If
         If -1 Then
             Console.WriteLine("-1 is true")
         End If
         Console.ReadLine()

     End Sub

End Module

When you execute this code you will see that the first and third if statements code gets
executed. The second does not, because the value is 0.

Lets explore more about the expressions that are being evaluated. The condition can be
an expression with a logical operator. Like this:

If SomeVariable = SomeValue then

In this case the logical operator is =. Other operators are as follows:

           >- Greater than
           < - Less than
           >= Greater than or equal to
           <= Less than or equal to
           Not – Reverses the logical result. Must precede the variable eg if Not x = 1
           And – bitwise and operator *
           Andalso – logical and
           Or – bitwise Operator *
           XOr – Exclusive or operator *
           Orelse – Logical or
           The And, Or and XOr are all what they call bitwise ands and ors. This
           produces a slightly different result than you might expect. Lets say we had this
           code:

           If 1 And 2 then


                                                                                           3
           Console.WriteLine(“1 and 2 is true”)
          End if
The program will not execute the Console.WriteLine as you may expect. This is because
the comparison is done at the bitwise level.

A Bitwise and works like this:

Each number has a binary value to it. The binary number system works similar to the 10
based number system. For example if we had this decimal based number 231 We could
break down the number like this:

1 * 100 + 3 * 101 + 2 * 102 =
1 * 1 + 3 * 10 + 2 * 100 =
1 + 30 + 200 =
231

A binary number is no different only we are using the 2 based number system. For
example if we had the number 37 which is 100101 in binary we could break down the
number like this

1 * 20 + 0 * 21 + 1 * 22 + 0 * 23 + 0 * 24 + 1 * 25 =
1 * 1 + 0 * 2 + 1 * 4 + 0 * 8 + 0 * 16 + 1 * 32 =
1 + 0 + 4 + 0 + 0 + 32 = 37 or 100101

A binary and works like this

Line up the binary numbers. If there is a 0 in both places return 1. Else return 0 In the
above statement

If 1 and 2 then ..

Means
If
(00000001) Binary and (00000010)
Which equals
00000000

Which is 0. The logical and operator which is called AndAlso will logically and the
values together.

If 1 AndAlso 2 Then
            Console.WriteLine("1 and 2 is true")
End If

The OrElse is the logical Or. Bitwise Or comes in 2 flavors inclusive or exclusive. The
inclusive bitwise Or which in Visual Basic .Net is Or lines up the binary number. It will
return 1 where either bit has a one. For example 2 Or 1 = 3


                                                                                            4
00000001 or 00000010 = 00000011
The bitwise exclusive or means works by returning 1 where one or the other bits is one
but not both. It uses the XOr operator in VB .NET. In other words

2 XOr 3 = 1

00000010 Xor 00000011 = 00000001

Bitwise ands and ors are used in truth tabling. That is something that is a little more
advanced than anything we will do in this class, but I wanted to explain how they work so
that you don’t end up with an anurism someday trying to figure out why 2 and 1 is false.

Lets right a simple algorithm. This one will introduce another new concept called
psuedocode. Psuedocode is like code that uses algorithm logic, however does not have
the exact syntax of a programming language. People use psuedocode to plan their
algorithms. They can quickly be converted to program code.

Here is the psuedocode

The User’s Age = Prompt the user for his / her age

If the User’s Age is 28 then
        Tell the user he / she is the same age as me
If the user’s age is less than 28 then
        Tell the user that he / she is younger than me
If the user’s age is greater than 28 then
        Tell the user that he / she is older than me

In the above psuedocode what I am doing is pretty simple to follow. The logic is broken
down to code-like English instructions. This is a method of planning code, that can be
easily translated into code like this:

Option Explicit On
Option Strict On

Module Main_Module



     Sub Main()
         Dim UserAge As Integer, UserInput As String

          Console.Write("Please enter your age: ")
          UserInput = Console.ReadLine
          Integer.TryParse(UserInput, UserAge)

          If UserAge = 28 Then
              Console.WriteLine("You are the same age as me")
          End If
          If UserAge < 28 Then


                                                                                          5
              Console.WriteLine("You are younger than me")
          End If
          If UserAge > 28 Then
              Console.WriteLine("You are older than me")
          End If
          Console.ReadLine()

     End Sub

End Module

In the above code each condition is being individually tested for. This doesn’t make a lot
of sense, since once one condition is true, we know the other conditions could not be.
Lets look at the next part of the if statement, the else.

Else
Else is a keyword that will only execute if the connected if condition is false. The
simplest if else looks like this:

If CONDITION Then
       DoSomething
Else
       DoSomethingElse
End if

As you can see, else goes before end if. Its code will only execute if the if statement fails.
We could amend our above example to this:

..

          If UserAge = 28 Then
               Console.WriteLine("You are the same age as me")
          Else
               If UserAge < 28 Then
                   Console.WriteLine("You are younger than me")
               End If
               If UserAge > 28 Then
                   Console.WriteLine("You are older than me")
               End If
          End If

Notice in the above code we now only bother looking the ages greater than or less than if
the first age fails. This is still not quite all that efficient however. Lets consider elseif.

Elseif allows us to look for another specific condition like the if statement would.
However this condition would only be evaluated under the circumstance that the
proceeding if statement were to fail, so even if the else if’s condition was true it would
not execute if the if statements condition was true.

Here is the most efficient version of what we coded a moment ago:


                                                                                             6
          If UserAge = 28 Then
               Console.WriteLine("You are the same age as me")
          ElseIf UserAge < 28 Then
               Console.WriteLine("You are younger than me")
          Else
               Console.WriteLine("You are older than me")
          End If

Notice that I only have one else if and then an else. This is because by deduction if a
number is not equal to or less than another number it must be greater than that number.
We can have an else with a code series of if and else if. It will execute only if all other
conditions fail and it must be at the end of the block. Obviously there can be only one
else statement per if statement.

Nesting statements

We can also nest statements within one another. We did this once earlier but for the sake
of clarification we will cover it. Sometimes we have nested possibilities. For example

If the username exists
        If the password matches the user name on record
                Log user in
        Else
                Prompt user with invalid password
Else
        Prompt user with unknown user name

The above code only attempts to look up the password if the user name exists. This is
nested. You can keep nesting down as needed.

Select Case Structure

The select case structure allows you to select from several possibilities that one variable
may have. The syntax of a select case looks like this

Select Case VARIABLENAME

       Case EXPRESSION
             ACTIONS
       [OPTIONAL]CASE ELSE
             DEFAULT ACTION
End Select

The variable name is the variable being used to evaluate the expressions. Each case can
have several expression syntaxes. One is a specific value like this

Select Case Grade


                                                                                              7
       Case “A”
…

In that example we use the exact value A to match a case to. If we wanted to handle
several values with the same case we could say:

Case “A”, “B”

Which allows us to handle both an a and b with the same case.
For numeric expressions we can use the same convention 10, 20. We can also use

Case is OPERATOR
Where operator is <, >, <= or >=. We can also use ranges

Case 10 to 20. The case else will only execute if all other cases fail to be true. We do not
have to use Case Else. Technically you wont get an error for not using multiple cases but
it does not make sense to. Here is an example select case statement used to calculate
numerical grades.

Option Explicit On
Option Strict On

Module Main_Module



     Sub Main()
         Dim UserGrade As Integer, UserInput As String

        Console.Write("Please enter your grade: ")
        UserInput = Console.ReadLine
        Integer.TryParse(UserInput, UserGrade)
        Select Case UserGrade
            Case Is > 90
                Console.WriteLine("Nice Job you get an A")
            Case 80 To 89
                Console.WriteLine("A B is pretty good")
            Case 70 To 79
                Console.WriteLine("You did Ok, but you can do better")
            Case 65 To 69
                Console.WriteLine("At least you passed")
            Case Is < 65
                Console.WriteLine("You failed, better luck next
semester")
        End Select

     End Sub

End Module

Of course you can nest select case statements and if statements together.



                                                                                           8
Data Validation

Last week we converted data and as I said we would learn this week how to ensure the
conversion was correct. We do this with the if statement. Next week we will see more
effective data validation such as making sure a string is an email. This week we will
adjust our GUI app from last week to ensure the data is entered correctly.

Go ahead and select File Close to close your current project. Then say file open and
browse to your project from last week named Week_2_Gui. If you don’t have it, let me
know.

Double click the calculate button to bring up the code. TO refresh your memory here is
what it should look like

Dim InterestAmount As Decimal, TotalLoan As Decimal, MonthlyPayment As
Decimal
        Dim InterestRate As Decimal, Term As Decimal, Principle As
Decimal
        Dim ResultForm As New DisplayForm

         Decimal.TryParse(txtInterest.text, InterestRate)
         Decimal.TryParse(txtAmount.Text, Principle)
         Decimal.TryParse(txtTerm.Text, Term)

         InterestAmount = (InterestRate / 100) * Principle * Term
         TotalLoan = InterestAmount + Principle
         MonthlyPayment = TotalLoan / (Term * 12)
         ResultForm.LoanAmount = TotalLoan
         ResultForm.MonthlyPayment = MonthlyPayment
         ResultForm.ShowDialog()


Now we will take these lines:

Decimal.TryParse(txtInterest.text, InterestRate)

Each one of those lines performs the conversion. We are going to adjust
the code so that we tell the user if he / she enters invalid data and
then we set the focus to that control and leave the sub routine.

We only look at one at a time, and we exit the sub every time one fails
so if you have mopre than one bad entry you would have to click the
calculate button 2 times.

The TryParse returns true if it works or false if it doesn’t. Therefore
all we need to do to ensure it worked is use an if statement. If Not
Decimal.TryParse will execute if it fails. Here is the new code.

Private Sub cmdCalculate_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles cmdCalculate.Click
        Dim InterestAmount As Decimal, TotalLoan As Decimal,
MonthlyPayment As Decimal
        Dim InterestRate As Decimal, Term As Decimal, Principle As
Decimal


                                                                                         9
       Dim ResultForm As New DisplayForm

       If Not Decimal.TryParse(txtInterest.Text, InterestRate) Then
           MessageBox.Show("Invalid Interest Rate entered")
           txtInterest.Text = ""
           txtInterest.Focus()
           Exit Sub
       End If
       If Not Decimal.TryParse(txtAmount.Text, Principle) Then
           MessageBox.Show("Invalid amount entered")
           txtAmount.Text = ""
           txtAmount.Focus()
           Exit Sub
       End If
       If Not Decimal.TryParse(txtTerm.Text, Term) Then
           MessageBox.Show("Invalid Term entered")
           txtTerm.Text = ""
           txtTerm.Focus()
           Exit Sub
       End If

       InterestAmount = (InterestRate / 100) * Principle * Term
       TotalLoan = InterestAmount + Principle
       MonthlyPayment = TotalLoan / (Term * 12)
       ResultForm.LoanAmount = TotalLoan
       ResultForm.MonthlyPayment = MonthlyPayment
       ResultForm.ShowDialog()

   End Sub

Next week we cover iteration. We will look at more advanced data
validation. See Ya then.




                                                                      10

				
DOCUMENT INFO