Counting and Looping |
|
|
|
Practical Learning: Using do...While |
Imports System Module Module1 Enum TypeOfApplication NewDriversLicense = 1 UpgradeFromIDCard TransferFromAnotherState end enum Sub Main() Dim LastName As String, FirstName As String Dim OrganDonorAnswer As String, Gender As String Dim Sex As Char, DLClass As Char Dim iType As Integer Console.WriteLine(" -=- Motor Vehicle Administration -=-") Console.WriteLine(" --- Driver's License Application ---") Do Console.WriteLine(" - Select the type of application -") Console.WriteLine("1 - Applying for a brand new Driver's License") Console.WriteLine("2 - Applicant already had an ID Card and is applying for a Driver's License") Console.WriteLine("3 - Applicant is transferring his/her Driver's License from another state") Console.Write("Your Choice: ") iType = CInt(Console.ReadLine()) Console.WriteLine("") Loop While iType > 3 Console.Write("First Name: ") FirstName = Console.ReadLine() Console.Write("Last Name: ") LastName = Console.ReadLine() . . . No Change End Sub End Module |
-=- Motor Vehicle Administration -=- --- Driver's License Application --- - Select the type of application - 1 - Applying for a brand new Driver's License 2 - Applicant already had an ID Card and is applying for a Driver's License 3 - Applicant is transferring his/her Driver's License from another state Your Choice: 8 - Select the type of application - 1 - Applying for a brand new Driver's License 2 - Applicant already had an ID Card and is applying for a Driver's License 3 - Applicant is transferring his/her Driver's License from another state Your Choice: 4 - Select the type of application - 1 - Applying for a brand new Driver's License 2 - Applicant already had an ID Card and is applying for a Driver's License 3 - Applicant is transferring his/her Driver's License from another state Your Choice: 1 First Name: Leon Last Name: Schless Sex(F=Female/M=Male): m - Driver's License Class - A - All Non-commercial vehicles except motorcycles B - Non-commercial vehicles up to and including 26,001/more lbs. C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs. K - Mopeds M - Motorcycles Your Choice: a Are you willing to be an Organ Donor(1=Yes/0=No)? 1 -=- Motor Vehicle Administration -=- --- Driver's License Information --- Type of Application: New Driver's License Full Name: Leon Schless Sex: Male Class: A Organ Donor? Yes |
An alternative to the Do... Loop While uses the following formula: Do Statement(s) Loop Until Condition Once again, the Statement(s) section executes first. After executing the Statement(s), the compiler checks the Condition. If the Condition is true, the compiler returns to the Statement(s) section to execute it. This will continue until the Condition is false. Once the Condition becomes false, the compiler gets out of this loop and continues with the section under the Loop Until line. Here is an example: Imports System Module Module1 Sub Main() Dim Answer As Char Do Console.Write("Are we there yet (1=Yes/0=No)? ") Answer = Console.ReadLine() Loop Until Answer = "1" Console.WriteLine("Wonderful, we have arrived") Console.WriteLine() End Sub End Module |
The Do While... Loop Statement |
As mentioned above, the Do While... Loop expression executes a statement first before checking a condition that would allow it to repeat. If you want to check a condition first before executing a statement, you can use another version as Do While... Loop. Its formula is: Do While Condition Statement(s) Loop In this case, the compiler checks the Condition first. If the Condition is true, the compiler then executes the Statement(s) and checks the Condition again. If the Condition is false, or when the Condition becomes false, the compiler skips the Statement(s) section and continues the code below the Loop keyword. Here is an example: Inports System Module Module1 Sub Main() Dim Number As Short Do While Number < 46 Console.Write("{0} ", Number) Number += 4 Loop Console.WriteLine() Console.WriteLine("Counting Stopped at: {0}", Number) Console.WriteLine() End Sub End Module This would produce: 0 4 8 12 16 20 24 28 32 36 40 44 Counting Stopped at: 48
|
The Do Until... Loop Statement |
An alternative to the Do While... Loop loop uses the following formula: Do Until Condition Statement(s) Loop This loop works like the Do While... Loop expression. The compiler examines the Condition first. If the condition is true, then it executes the Statement(s) section. Here is an example: Inports System Module Module1 Sub Main() Dim Answer As Char Do Until (Answer = "1") Console.Write("Are we there yet (1=Yes/0=No)? ") Answer = Console.ReadLine() Loop Console.WriteLine("Wonderful, we have arrived") Console.WriteLine() End Sub End Module |
Loop Counters |
Introduction |
The looping statements we reviewed above are used when you don't know or can't anticipate the number of times a condition needs to be checked in order to execute a statement. If you know with certainty how many times you want to execute a statement, you can use another form of loops that use the For...Next expression. |
One of the loop counters you can use is For...To...Next. Its formula is: For Counter = Start To End Statement(s) Next Used for counting, the expression begins counting at the Start point. Then it examines whether the current value (after starting to count) is lower than End. If that's the case, it then executes the Statement(s). Next, it increments the value of Counter by 1 and examines the condition again. This process goes on until the value of Counter becomes equal to the End value. Once this condition is reached, the looping stops. Here is an example: Inports System Module Module1 Sub Main() Dim Number As Short For Number = 5 To 16 Console.Write("{0} ", Number) Next Console.WriteLine() Console.WriteLine("Counting Stopped at: {0}", Number) Console.WriteLine() End Sub End Module This would produce: 5 6 7 8 9 10 11 12 13 14 15 16 Counting Stopped at: 17 |
The formula above will increment the counting by 1 at the end of each statement. If you want to control how the incrementing processes, you can set your own, using the Step option. Here is the formula: For Counter = Start To End Step Increment Statement(s) Next You can set the incrementing value to your choice. If the value of Increment is positive, the Counter will be added its value. Here is an example: Inports System Module Module1 Sub Main() Dim Number As Short For Number = 5 To 42 Step 4 Console.Write("{0} ", Number) Next Console.WriteLine() End Sub End Module This would produce: 5 9 13 17 21 25 29 33 37 41 You can also set a negative value to the Increment factor, in which case the Counter will be subtracted the set value. |
Techniques of Writing Conditional Statements |
A condition can be created inside of another to write a more effective statement. This is referred to as nesting one condition inside of another. Almost any condition can be part of another and multiple conditions can be included inside of others. As we have learned, different conditional statements are applied in specific circumstances. In some situations, they are interchangeable or one can be applied just like another, which becomes a matter of choice. Statements can be combined to render a better result with each playing an appropriate role. Here is an example of an if condition nested inside of a do...while loop: Imports System Module Module1 Sub Main() Dim SittingDown As Char Dim SitDown As String Do Console.Write("Are you sitting down now(y/n)? ") SitDown = Console.ReadLine() SittingDown = CChar(SitDown) If SittingDown <> "y" Then Console.WriteLine("Could you please sit down for the next exercise? ") End If Loop While Not (SittingDown = "y") Console.WriteLine() End Sub End Module Here is an example of running the program: Are you sitting down now(y/n)? n Could you please sit down for the next exercise? Are you sitting down now(y/n)? a Could you please sit down for the next exercise? Are you sitting down now(y/n)? k Could you please sit down for the next exercise? Are you sitting down now(y/n)? y One of the reasons you would need to nest conditions is because one would lead to another. Sometimes, before checking one condition, another primary condition would have to be met. Our ergonomic program asks the user whether she is sitting down. Once the user is sitting down, you would write an exercise she would perform. Depending on her strength, at a certain time, one user will be tired and want to stop while for the same amount of previous exercises, another user would like to continue. Before continuing with a subsequent exercise, you may want to check whether the user would like to continue. Of course, this would be easily done with: |
using System; Module Module1 Sub Main() Dim SittingDown As Char Dim SitDown As String Dim WantToContinue As String Do Console.Write("Are you sitting down now(y/n)? ") SitDown = Console.ReadLine() SittingDown = CChar(SitDown) If SittingDown <> "y" Then Console.WriteLine("Could you please sit down for the next exercise? ") End If Loop While Not (SittingDown = "y") Console.WriteLine() Console.Write("Do you want to continue(y=Yes/n=No)? ") Dim ToContinue As String = Console.ReadLine() WantToContinue = CChar(ToContinue) Console.WriteLine() End Sub End Module
If the user answers No, you can stop the program. If she answers Yes, you would need to continue the program with another exercise. Because the user answered Yes, the subsequent exercise would be included in the previous condition because it does not apply for a user who wants to stop. In this case, one “if” could be inserted inside of another. Here is an example: |
Imports System Module Module1 Sub Main() Dim SittingDown As Char Dim SitDown As String Dim WantToContinue As String Do Console.Write("Are you sitting down now(y/n)? ") SitDown = Console.ReadLine() SittingDown = CChar(SitDown) If SittingDown <> "y" Then Console.WriteLine("Could you please sit down for the next exercise? ") End If Loop While Not (SittingDown = "y") Console.WriteLine() Console.Write("Do you want to continue(1=Yes/0=No)? ") WantToContinue = CChar(Console.ReadLine()) If WantToContinue = "1" Then Dim LayOnBack As Char Console.WriteLine("Good!" & vbCrLf & "For the next exercise, you should lay on your back") Console.Write("Are you laying on your back(1=Yes/0=No)? ") Dim lay As String = Console.ReadLine() LayOnBack = CChar(Lay) If LayOnBack = "1" Then Console.WriteLine("Great!" & vbCrLf & "Now we will start the next exercise.") Else Console.WriteLine("Well, it looks like you are getting tired...") End If else Console.WriteLine("We had enough today") End If Console.WriteLine("We will stop the session now." & vbCrLf & "Thanks.") Console.WriteLine() End Sub End Module
Practical Learning: Nesting Conditions |
Imports System Module Module1 Enum TypeOfApplication NewDriversLicense = 1 UpgradeFromIDCard TransferFromAnotherState end enum Sub Main() Dim LastName As String, FirstName As String Dim OrganDonorAnswer As String, Gender As String Dim Sex As Char, DLClass As Char Dim iType As Integer Console.WriteLine(" -=- Motor Vehicle Administration -=-") Console.WriteLine(" --- Driver's License Application ---") Do Console.WriteLine(" - Select the type of application -") Console.WriteLine("1 - Applying for a brand new Driver's License") Console.WriteLine("2 - Applicant already had an ID Card and is applying for a Driver's License") Console.WriteLine("3 - Applicant is transferring his/her Driver's License from another state") Console.Write("Your Choice: ") iType = CInt(Console.ReadLine()) Console.WriteLine("") If iType > 3 Then Console.WriteLine("Bad Selection") Loop While iType > 3 Console.Write("First Name: ") FirstName = Console.ReadLine() Console.Write("Last Name: ") LastName = Console.ReadLine() . . . No Change End Sub End Module |
C:\VBasic\MVA2>vbc Exercise.vb Microsoft (R) Visual Basic .NET Compiler version 7.10.3052.4 for Microsoft (R) .NET Framework version 1.1.4322.573 Copyright (C) Microsoft Corporation 1987-2002. All rights reserved. C:\VBasic\MVA2>Exercise -=- Motor Vehicle Administration -=- --- Driver's License Application --- - Select the type of application - 1 - Applying for a brand new Driver's License 2 - Applicant already had an ID Card and is applying for a Driver's License 3 - Applicant is transferring his/her Driver's License from another state Your Choice: 8 Bad Selection - Select the type of application - 1 - Applying for a brand new Driver's License 2 - Applicant already had an ID Card and is applying for a Driver's License 3 - Applicant is transferring his/her Driver's License from another state Your Choice: 4 Bad Selection - Select the type of application - 1 - Applying for a brand new Driver's License 2 - Applicant already had an ID Card and is applying for a Driver's License 3 - Applicant is transferring his/her Driver's License from another state Your Choice: 3 First Name: Paulette Last Name: Gandt Sex(F=Female/M=Male): f - Driver's License Class - A - All Non-commercial vehicles except motorcycles B - Non-commercial vehicles up to and including 26,001/more lbs. C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs. K - Mopeds M - Motorcycles Your Choice: 0 Are you willing to be an Organ Donor(1=Yes/0=No)? 0 -=- Motor Vehicle Administration -=- --- Driver's License Information --- Type of Application: Transfer From Another State Full Name: Paulette Gandt Sex: Female Class: Unknown Organ Donor? No C:\VBasic\MVA2> |
Imagine you are in the middle of a Main procedure (or another of the procedure we will learn to create in the new few lessons). If a certain condition is met, you may need to get out of the procedure to condition the application (out of the current procedure). To do this, the Visual Basic language provides the Exit Sub expression. To use it, you simply type Exit Sub once the undesired condition is met. Consider the following example: Imports System Module Module1 Sub Main() Dim i As Integer For i = 5 To 18 Step 1 If i = 12 Then Exit Sub End If Console.WriteLine("Value: {0}", i) Next End Sub End Module In this case, the compiler starts counting at 5 and displays the corresponding value on the console. If the counter reaches 12, it gets out of Main, which causes it to stop. Therefore, this would produce: Value: 5 Value: 6 Value: 7 Value: 8 Value: 9 Value: 10 Value: 11 |
The Goto statement allows a program execution to jump to another section of a procedure in which it is being used. In order to use the Goto statement, insert a name on a particular section of your procedure so you can refer to that name. The name, also called a label, is made of one word and follows the rules we have learned about names (the name can be anything), then followed by a colon ":". The following program uses a for loop to count from 2 to 18, but when it encounters 10, it jumps to a designated section of the program: |
Imports System Module Module1 Sub Main() Dim i As Integer For i = 2 To 18 Step 1 If i = 10 Then GoTo StoppingHere End If Console.WriteLine("Value: {0}", i) Next StoppingHere: Console.WriteLine("The execution jumped here.") End Sub End Module
This would produce:
Value: 2 Value: 3 Value: 4 Value: 5 Value: 6 Value: 7 Value: 8 Value: 9 The execution jumped here.
In the same way, you can create as many labels as you judge them necessary in your code and refer to them when you want. Here is an example with two labels: Imports System Module Module1 Sub Main() Dim Answer As Byte Console.WriteLine(" -=- Multiple Choice Question -=-") Console.WriteLine("To create a constant in your code, you can use the Constant keyword") Console.Write("Your choice (1=True/2=False)? ") Answer = Console.ReadLine() If Answer = 1 Then GoTo Wrong If Answer = 2 Then GoTo Right Wrong: Console.WriteLine(vbCrLf & "Wrong: The keyword used to create a constant is Const") Exit Sub Right: Console.WriteLine(vbCrLf & "Right: Constant is not a keyword") End Sub End Module Here is an example of executing the program with Answer = 1: -=- Multiple Choice Question -=- To create a constant in your code, you can use the Constant keyword Your choice (1=True/2=False)? 1 Wrong: The keyword used to create a constant is Const Here is another example of executing the same program with Answer = 2: -=- Multiple Choice Question -=- To create a constant in your code, you can use the Constant keyword Your choice (1=True/2=False)? 2 Right: Constant is not a keyword |
Conditional Conjunctions and Disjunctions |
Introduction |
A logical operation is one that is performed on one or two expressions to check the truthfulness or falsity. The comparison is performed using one of three special keywords Not, And, or Or. |
When a variable is declared and receives a value (this could be done through initialization or a change of value) in a program, it becomes alive. When a variable is not being used or is not available for processing (in visual programming, it would be considered as disabled) to make a variable (temporarily) unusable, you can nullify its value. To render a variable unavailable during the evolution of a program, apply the logical not operator which is Not. Its syntax is: Not Value There are two main ways you can use the logical Not operator. The most classic way of using the logical Not operator is to check the state of a variable. When a variable holds a value, it is "alive". To make it not available, you can "not" it. When a variable has been "notted", its logical value has changed. If the logical value was True, it would be changed to False and vice versa. Therefore, you can inverse the logical value of a variable by "notting" or not "notting" it. Here is an example: Inports System Module Module1 Sub Main() Dim IsFullTime As Boolean Console.WriteLine("Is Employee Full Time? {0}", IsFullTime) Console.WriteLine("Is Employee Full Time? {0}", Not IsFullTime) End Sub End Module This would produce: Is Employee Full Time? False Is Employee Full Time? True |
A logical conjunction is an operation used to check two conditions for absolute truthfulness. This operation uses the And keyword. The formula to use the And operator is Condition1 And Condition2 The left condition, Condition1, is first checked. If it is False, the whole expression is rendered False and the checking process stopped. If the first condition, Condition1, is True, then the second condition, Condition2, is checked. If the right condition is False, the whole expression is False, even if the first is True. In the same way, if both conditions are false, the whole expression is False. Only if both conditions are True is the whole condition true. This can be resumed as follows: |
|
Here is an example: Module Module1 Sub Main() Dim SittingDown As Char Dim SitDown As String Dim WantToContinue As String Console.Write("Are you sitting down now(y/n)? ") SitDown = Console.ReadLine() SittingDown = CChar(SitDown) If (SittingDown <> "y") And (SittingDown <> "Y") Then Console.WriteLine("Could you please sit down for the next exercise? ") End If Console.WriteLine() End Sub End Module Here is one example of running the program: Are you sitting down now(y/n)? n Could you please sit down for the next exercise? Are you sitting down now(y/n)? N Could you please sit down for the next exercise? Are you sitting down now(y/n)? d Could you please sit down for the next exercise? Are you sitting down now(y/n)? y Good We will stop the session now. Thanks.
|
A logical disjunction is performed on two conditions for a single truthfulness. This operation uses the Or keyword on the following formula: Condition1 OR Condition2 The left condition, Condition1, is first checked. If Condition1 is True, then the whole expression is true, regardless of the outcome of the second. If Condition1 is False, then Condition2 is checked. If Condition2 is True, the whole expression is True even if Condition1 was False. If both conditions are True, the whole expression is True. The whole expression is false only if both Condition1 and Condition2 are False. This can be resumed as follows: |
|
Here is an example: Module Module1 Sub Main() Dim SittingDown As Char Dim SitDown As String Dim WantToContinue As String Console.Write("Are you sitting down now(y/n)? ") SitDown = Console.ReadLine() SittingDown = CChar(SitDown) If (SittingDown = "n") Or (SittingDown = "N") Then Console.WriteLine("Could you please sit down for the next exercise? ") End If Console.WriteLine() End Sub End Module
|
Practical Learning: Using Or |
Module Module1 Enum TypeOfApplication NewDriversLicense = 1 UpgradeFromIDCard TransferFromAnotherState End Enum Sub Main() Dim LastName As String, FirstName As String Dim OrganDonorAnswer As String, Gender As String Dim Sex As Char, DLClass As Char Dim iType As Integer Console.WriteLine(" -=- Motor Vehicle Administration -=-") Console.WriteLine(" --- Driver's License Application ---") Do Console.WriteLine(" - Select the type of application -") Console.WriteLine("1 - Applying for a brand new Driver's License") Console.WriteLine("2 - Applicant already had an ID Card and is applying for a Driver's License") Console.WriteLine("3 - Applicant is transferring his/her Driver's License from another state") Console.Write("Your Choice: ") iType = CInt(Console.ReadLine()) Console.WriteLine() If (iType < 1) Or (iType > 3) Then Console.WriteLine("Bad Selection") Loop While ((iType < 1) Or (iType > 3)) Console.Write("First Name: ") FirstName = Console.ReadLine() Console.Write("Last Name: ") LastName = Console.ReadLine() Console.Write("Sex(F=Female/M=Male): ") Sex = CChar(Console.ReadLine()) Console.WriteLine(" - Driver's License Class -") Console.WriteLine("A - All Non-commercial vehicles except motorcycles") Console.WriteLine("B - Non-commercial vehicles up to and including 26,001/more lbs.") Console.WriteLine("C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs.") Console.WriteLine("K - Mopeds") Console.WriteLine("M - Motorcycles") Console.Write("Your Choice: ") DLClass = CChar(Console.ReadLine()) Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? ") OrganDonorAnswer = Console.ReadLine() If (Sex = "f") Or (Sex = "F") Then Gender = "Female" ElseIf (Sex = "m") Or (Sex = "M") Then Gender = "Male" Else Gender = "N/A" End If Console.WriteLine() Console.WriteLine(" -=- Motor Vehicle Administration -=-") Console.WriteLine(" --- Driver's License Information ---") Console.Write("Type of Application: ") Select Case iType Case TypeOfApplication.NewDriversLicense Console.WriteLine("New Driver's License") Case TypeOfApplication.UpgradeFromIDCard Console.WriteLine("Upgrade From Identity Card") Case TypeOfApplication.TransferFromAnotherState Console.WriteLine("Transfer From Another State") Case Else Console.WriteLine("Not Specified") End Select Console.WriteLine("Full Name: {0} {1}", FirstName, LastName) Console.WriteLine("Sex: {0}", Gender) Select Case DLClass Case "a", "A" Console.WriteLine("Class: A") Case "b", "B" Console.WriteLine("Class: B") Case "c", "C" Console.WriteLine("Class: C") Case "k", "K" Console.WriteLine("Class: K") Case "m", "M" Console.WriteLine("Class: M") Case Else Console.WriteLine("Class: Unknown") End Select Console.Write("Organ Donor? ") If OrganDonorAnswer = "1" Then Console.WriteLine("Yes") Else Console.WriteLine("No") End If End Sub End Module |
-=- Motor Vehicle Administration -=- --- Driver's License Application --- - Select the type of application - 1 - Applying for a brand new Driver's License 2 - Applicant already had an ID Card and is applying for a Driver's License 3 - Applicant is transferring his/her Driver's License from another state Your Choice: 8 Bad Selection - Select the type of application - 1 - Applying for a brand new Driver's License 2 - Applicant already had an ID Card and is applying for a Driver's License 3 - Applicant is transferring his/her Driver's License from another state Your Choice: 0 Bad Selection - Select the type of application - 1 - Applying for a brand new Driver's License 2 - Applicant already had an ID Card and is applying for a Driver's License 3 - Applicant is transferring his/her Driver's License from another state Your Choice: 1 First Name: Pierrette Last Name: Lumm Sex(F=Female/M=Male): F - Driver's License Class - A - All Non-commercial vehicles except motorcycles B - Non-commercial vehicles up to and including 26,001/more lbs. C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs. K - Mopeds M - Motorcycles Your Choice: c Are you willing to be an Organ Donor(1=Yes/0=No)? 6 -=- Motor Vehicle Administration -=- --- Driver's License Information --- Type of Application: New Driver's License Full Name: Pierrette Lumm Sex: Female Class: C Organ Donor? No |
|
||
Previous | Copyright © 2004-2007 FunctionX, Inc. | Next |
|