|
|
 |
|
|
|
|
|
|
|
|
Visual Basic 2008 9.0 .NET Examples and Ebook
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Making Decisions or Selections
| So far, all instructions were executions in sequence. After the first instruction was executed, the second was executed, and so on. In this sequential technique all instructions are executed in the same order as they are defined.
Besides this sequence technique, other techniques are required to form more complex algorithms. Suppose we need a program that outputs half of a numeric value when an even number is entered, and double of that value when an odd number is entered.
In this case are algorithm needs to make a decision. The algorithm needs to decide whether to output the half or the double of the entered value.
We can code this decision/selection with a decision structure. This structure is centered around a specific conditional, formed by a conditional expression. Conditional expressions ( also called "boolean expressions" ) can only evaluate to True or False. |
Up
If ... Else ... End If
| Module Example
Sub Main()
Console.WriteLine("Value ?")
Dim value As Integer = Console.ReadLine()
If value Mod 2 = 0 Then
Console.WriteLine("Half of " & value & " is " & value / 2 & ".")
Else
Console.WriteLine("Double of " & value & " is " & value * 2 & ".")
End If
Console.ReadLine()
End Sub
End Module Download Broncode |
| Output : Value ?
5
Double of 5 is 10. |
| Output : Value ?
10
Half of 10 is 5. |
Up
Comparison Operators
| In the above example the decision is coded with an If ... End If. The If is followed with the condition. When the condition evaluated as true, the instruction in the If part are executed. When the condition is not fulfilled the instructions and there is an Else part present, the instructions in the Else part are executed.
Comparison operator = can be used to check for equality. The same symbol is used for the assignment operator, don't confuse the two. Other comparison operators are : <> ( not equal to ), > ( more than ), > ( less than ), >= ( more than or equal to ) and <= ( less than or equal to ). |
Up
Exercise
| Task :
Make a program based on the following output ( input is in italic ). |
| Output : Value ?
123
Value 123 is not equal to zero. |
| Module ExerciseSolution
Sub Main()
Dim value As Integer
Console.WriteLine("Value ?")
value = Console.ReadLine()
If value = 0 Then
Console.WriteLine("Zero.")
Else
Console.WriteLine("Value " & value & " is not equal to zero.")
End If
Console.ReadLine()
End Sub
End Module Download Broncode |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|