Presentation is loading. Please wait.

Presentation is loading. Please wait.

Tutorial 4 The Selection Structure

Similar presentations


Presentation on theme: "Tutorial 4 The Selection Structure"— Presentation transcript:

1 Tutorial 4 The Selection Structure

2 The If…Then…Else Statement Lesson A Objectives
After completing this lesson, you will be able to: Write pseudocode for the selection structure Create a flowchart to help you plan an application’s code Write an If…Then…Else statement Write code that uses comparison operators and logical operators Use the UCase and LCase functions Tutorial 4: The Selection Structure

3 The Selection Structure
Use to make a decision or comparison and then, based on the result of that decision or comparison, to select one of two paths You use the selection structure, also called the decision structure, when you want a program to make a decision or comparison and then, based on the result of the decision or comparison, select a particular set of tasks to perform The condition must result in either a true (yes) or false (no) answer If the condition is true, the program performs one set of tasks. If the condition is false, there may or may not be a different set of tasks to perform. Tutorial 4: The Selection Structure

4 Writing Pseudocode for If and If/Else Selection Structures
An If structure contains only one set of instructions which are processed when the condition is true If condition is true Then perform these tasks End If Perform these tasks whether condition is true or false An If/Else structure contains two sets of instructions: one set is processed when the condition is true and the other set is processed when the condition is false If condition is true then perform these tasks Else End If Perform these tasks whether condition is true or false Tutorial 4: The Selection Structure

5 Flowchart Symbols start/stop oval process rectangle
input/output parallelogram selection/repetition diamond symbols are connected by flowlines Tutorial 4: The Selection Structure

6 Selection Structure Flowcharts
Tutorial 4: The Selection Structure

7 Coding the If and If/Else Selection Structures
The items in square brackets ([ ]) in the syntax are optional You do not need to always include the Else portion Words in bold, however, are essential components of the statement Items in italics indicate where the programmer must supply information pertaining to the current application The set of statements contained in the true path, as well as the set of statements contained in the false path, are referred to as a statement block Tutorial 4: The Selection Structure

8 Coding the If and If/Else Selection Structures
If condition Then instructions when the condition is true End If [instructions when the condition is true] [Else [instructions when the condition is false]] Tutorial 4: The Selection Structure

9 Comparison Operators = Is equal to > Is Greater Than >= Is Greater Than or Equal to < Is Less Than <= Is Less Than or Equal to <> Is Not Equal to Comparison operators are evaluated from left to right, and are evaluated after any mathematical operators Tutorial 4: The Selection Structure

10 Expressions Containing Relational Operators
< 5 * 2 5 * 2 is evaluated first, giving 10 is evaluated second, giving 13 13 < 10 is evaluated last, giving false 7 > 3 * 4 / 2 3 * 4 is evaluated first, giving 12 12 / 2 is evaluated second, giving 6 7 > 6 is evaluated last, giving true All expressions containing a relational operator will result in either a true or false answer only Tutorial 4: The Selection Structure

11 Using a Comparison Operator
Dim intFirst, intSecond As Integer If (intFirst > intSecond) Then Dim intTemp As Integer intTemp = intFirst intFirst = intSecond intFirst = intTemp End If Block-level Variable Tutorial 4: The Selection Structure

12 If the answer is False Dim strOperation As String
Dim intFirst, intSecond, intAnswer As Integer If strOperation = "A" Then intAnswer = intFirst + intSecond Else intAnswer = intFirst - intSecond End If Tutorial 4: The Selection Structure

13 Logical Operators Not Reverses the truth value of condition; false becomes true and true becomes false. 1 And All conditions connected by the And operator must be true for the compound condition to be true. 2 AndAlso All conditions connected by the AndAlso operator must be true for the compound condition to be true. Or Only one of the conditions connected by the Or operator needs to be true for the compound condition to be true. 3 OrElse Only one of the conditions connected by the OrElse operator needs to be true for the compound condition to be true. Xor Only when one and only one condition connected by Xor is true for the compound condition to be true. 4 Tutorial 4: The Selection Structure

14 Truth Table for Not Operator
Result = Not Condition If condition is Value of Result is True False Tutorial 4: The Selection Structure

15 Truth Table for And Operator
Result = condition1 And Condition2 If condition1 is And condition2 is Value of Result is True False Tutorial 4: The Selection Structure

16 Expressions Containing the And Logical Operator
3 > 2 is evaluated first, giving true 6 > 5 is evaluated second, giving true true And true is evaluated last, giving true 10 < 25 And 6 > 5 + 1 5 + 1 is evaluated first, giving 6 10 < 25 is evaluated second, giving true 6 > 6 is evaluated third, giving false true And false is evaluated last, giving false Tutorial 4: The Selection Structure

17 Truth Table for AndAlso Operator
Result = condition1 AndAlso Condition2 If condition1 is And condition2 is Value of Result is True False (not evaluated) Tutorial 4: The Selection Structure

18 Expressions Containing the AndAlso Logical Operator
3 < 2 is evaluated first, giving false 6 > 5 is not evaluated false 10 < 25 AndAlso 6 > 5 + 1 10 < 25 is evaluated first, giving true 5 + 1 is evaluated second, giving 6 6 > 6 is evaluated third, giving false true And false is evaluated last, giving false strSales = 12000 strRate = “A” strRate =“A” AndAlso sngSales > 10000 strRate =“A” is evaluated first, giving true sngSales > is evaluated second giving true true AndAlso true gives true Tutorial 4: The Selection Structure

19 Truth Table for Or Operator
Result = condition1 Or Condition2 If condition1 is And condition2 is Value of Result is True False Tutorial 4: The Selection Structure

20 Expressions Containing the Or Logical Operator
3 < 2 is evaluated first, giving false 6 > 5 is evaluated second giving true false or true gives true 10 < 25 Or 6 > 5 + 1 10 < 25 is evaluated first, giving true 5 + 1 is evaluated second, giving 6 6 > 6 is evaluated third, giving false true or false is evaluated last, giving true Tutorial 4: The Selection Structure

21 Truth Table for OrElse Operator
Result = condition1 OrElse Condition2 If condition1 is And condition2 is Value of Result is True (not evaluated) False Tutorial 4: The Selection Structure

22 Expressions Containing the OrElse Logical Operator
3 < 2 is evaluated first, giving false 6 > 5 is evaluated second giving true false or true gives true 10 < 25 OrElse 6 > 5 + 1 10 < 25 is evaluated first, giving true 6 > is not evaluated true strRate1 = “A” : strRate2 = “B”: strTest = “B” strRate1 = strTest OrElse strRate2 = strTest strRate1 = strTest is evaluated first, giving false strRate2 = strTest is evaluated second giving true false Or true gives true Tutorial 4: The Selection Structure

23 Truth Table for Xor Operator
Result = condition1 Xor Condition2 If condition1 is And condition2 is Value of Result is True False Tutorial 4: The Selection Structure

24 Operator Order of Precedence
Arithmetic Operators Exponentiation Negation Multiplication and division Integer division Modulus Addition and subtraction Concatenation Operators Comparison Operators Logical Operators Not And and AndAlse Or and OrElse Xor Tutorial 4: The Selection Structure

25 Using Logical Operators in an If…Then…Else Statement
‘ Using the AndAlso If sngHours >= 0 AndAlso sngHours <= 40 Then sngPay = sngHours * 10.65 Else MessageBox.Show("Input Error") End If ‘Using the OrElse If sngHours < 0 OrElse sngHours > 40 Then Tutorial 4: The Selection Structure

26 Another Example ‘Test for a character If strLetter = "p" OrElse strLetter = "P" Then ResultLabel .Text = “Pass" Else ResultLabel .Text = “Fail" End If Tutorial 4: The Selection Structure

27 The UCase and LCase Functions
In most programming languages, string comparisons are case sensitive--in other words, the letter “A” is not the same as the letter “a” UCase is a function that converts all characters to Upper Case strData = UCase(“New York”) strData now contains “NEW YORK” LCase is a function the converts all characters to Lower Case strData = LCase(“New York”) strData now contains “new york” Tutorial 4: The Selection Structure

28 The UCase and LCase Functions
Determine if the variable strState is California If strState =“CA” OrElse strState = “ca” OrElse strState = “cA” OrElse strState = “Ca” Then Or you can use the UCase function If UCase(strState) = “CA” Then Or you can use the ToUpper function If strState.ToUpper = “CA” Then Tutorial 4: The Selection Structure

29 The ToUpper and ToLower Methods
‘ An alternative way If strLetter.ToUpper = "P" Then ResultLabel .Text = "Pass" Else ResultLabel .Text = “Fail" End If strData = “New York” strData = strData.ToUpper ‘strData now contains “NEW YORK” strDate = strData.ToLower ‘strData now contains “new york” Tutorial 4: The Selection Structure

30 UCase Function Public Function UCase(ByVal Value As String) As String
Member of: Microsoft.VisualBasic.Strings Summary: Returns a String or Char containing the specified string converted to uppercase. Parameters: Value: Any valid String or Char expression. Remarks Only lowercase letters are converted to uppercase; all uppercase letters and nonletter characters remain unchanged. Tutorial 4: The Selection Structure

31 String.ToUpper Method Returns a copy of this String in uppercase.
(Object Browser) Public Function ToUpper() As String Member of: System.String Summary: Returns a copy of this System.String in uppercase, using the casing rules of the current culture. Return Values: A System.String in uppercase. Tutorial 4: The Selection Structure

32 The Monthly Payment Calculator Application Lesson B Objectives
After completing this lesson, you will be able to: Group objects using a GroupBox control Calculate a periodic payment using the Pmt function Create a message box using the MessageBox.Show method Determine the value returned by a message box Tutorial 4: The Selection Structure

33 Adding a GroupBox Control to the Form
You use the GroupBox tool in the Toolbox window to add a group box control to the interface A group box control serves as a container for other controls You can use a group box control to visually separate related controls from other controls on the form Place the GroupBox control on the form and drag other controls into it Page Page 249 Set TabIndex Tutorial 4: The Selection Structure

34 Coding the CalcPayButton Click Event Procedure
The CalcPayButton’s Click event procedure is responsible for calculating the monthly payment amount, and then displaying the result in the PaymentLabel control The pseudocode for the CalcPayButton’s Click event procedure is shown in Figure in the textbook Tutorial 4: The Selection Structure

35 Tutorial 4: The Selection Structure

36 The Pmt Function You can use the Visual Basic .NET Pmt function to calculate a periodic payment on either a loan or an investment (page ) Syntax: Function PMT(ByVal Rate As Double, ByVal NPer As Double, ByVal PV As Double, Optional ByVal FV As Double = 0, Optional ByVal Due As DueDate = DueDate.EndOfPeriod) As Double Example: Pmt(0.05, 3, 9000, 0, DueDate.EndOfPeriod) Pmt(0.06/12, 20 * 12, 0, 40000, DueDate.BegOfPeriod) -Pmt(sngRate / 12, intTerm * 12, sngPrincipal, 0, DueDate.BegOfPeriod) Tutorial 4: The Selection Structure

37 The MessageBox.Show Method
You can use the Message.Box.Show method to display a message box that contains text, one or more buttons, and an icon Overloads Public Shared Function Show( _ ByVal text As String, _ ByVal caption As String, _ ByVal buttons As MessageBoxButtons, _ ByVal icon As MessageBoxIcon, _ ByVal defaultButton As MessageBoxDefaultButton, _ ByVal options As MessageBoxOptions _ ) As DialogResult MessageBox.Show("Rate should be 1 or greater", _ "Interest rate", _ MessageBoxButtons.OK, _ MessageBoxIcon.Exclamation, _ MessageBoxDefaultButton.Button1) Tutorial 4: The Selection Structure

38 MessageBoxButtons Member Name Description AbortRetryIgnore
The message box contains Abort, Retry, and Ignore buttons OK The message box contains an OK button OKCancel The message box contains an OK and a Cancel button RetryCancel The message box contains Retry and Cancel buttons YesNo The message box contains Yes and No button YesNoCancel The message box contains Yes, No, and Cancel buttons Tutorial 4: The Selection Structure

39 MessageBoxIcons Member Name Description Asterisk or Information
a lowercase letter i in a circle Error or Hand or Stop a white X in a circle with a red background Exclamation an exclamation point in a triangle with a yellow background None no symbols Question a question mark in a circle Warning an exclamation-point in a triangle with a yellow background Tutorial 4: The Selection Structure

40 MessageBoxDefaultButton
Member Name Description Button1 The first button is the default Button2 The second button is the default Button3 The third button is the default Tutorial 4: The Selection Structure

41 MessageBoxOptions Member Name Description DefaultDesktopOnly
The MessageBox is displayed on the active desktop RightAlign The MessageBox is right-aligned RtlReading The MessageBox text is displayed in right to left order ServiceNotification Tutorial 4: The Selection Structure

42 DialogResult Member Name Description Abort
The Abort button was selected Cancel The Cancel button was selected Ignore The Ignore button was selected No The No button was selected OK The OK button was selected Retry The Retry button was selected Yes The Yes button was selected After displaying the message box, the MessageBox.Show method waits for the user to choose one of the buttons displayed in the message box. It then closes the message box and returns a number—an integer—that indicates which button the user chose. There is an enumeration that contains constant values for each return. While you can use the integer, it is generally better (and easier to read) to use these built-in constants. You can store the result of the message box in a variable, intRC (for result code) and then use If intRC = DialogResult.Yes Then ‘ do the yes code ElseIf intRC = DialogResult.No Then ‘ do the no code Tutorial 4: The Selection Structure

43 Completing the Monthly Payment Calculator Application Lesson C Objectives
After completing this lesson, you will be able to: Specify the keys that a text box will accept Display the ControlChars constants Align the text in a label control Tutorial 4: The Selection Structure

44 Coding the KeyPress Event
Template Private Sub PrincipalTextBox_KeyPress( _ ByVal sender As Object, _ ByVal e As System.Windows.Forms.KeyPressEventArgs) _ Handles PrincipalTextBox.KeyPress Setting e.Handled = True will cancel the key Page 268 Tutorial 4: The Selection Structure

45 ControlChars Class Field Meaning Back Backspace NewLine Same as CrLf
Carriage Return NullChar A null CrLf Carriage Return and Line Feed Quote Double quote FormFeed Form Feed Tab Lf Line Feed VerticalTab Vertical Tab strText = “Hello” & ControlChars.NewLine & “World” Tutorial 4: The Selection Structure

46 Aligning Text in a Label Using the TextAlign Property
Member Name Description BottomCenter Content is vertically aligned at the bottom, and horizontally aligned at the center BottomRight Content is vertically aligned at the bottom, and horizontally aligned on the right. MiddleCenter Content is vertically aligned in the middle, and horizontally aligned at the center. MiddleLeft Content is vertically aligned in the middle, and horizontally aligned on the left. MiddleRight Content is vertically aligned in the middle, and horizontally aligned on the right. TopCenter Content is vertically aligned at the top, and horizontally aligned at the center. TopLeft Content is vertically aligned at the top, and horizontally aligned on the left. TopRight Content is vertically aligned at the top, and horizontally aligned on the right. Tutorial 4: The Selection Structure


Download ppt "Tutorial 4 The Selection Structure"

Similar presentations


Ads by Google