Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 The If…Then Statement

Similar presentations


Presentation on theme: "Chapter 4 The If…Then Statement"— Presentation transcript:

1 Chapter 4 The If…Then Statement
4/22/2017 5:29 AM Chapter 4 The If…Then Statement Conditional control structure, also called a decision structure Executes a set of statements when a condition is true The condition is a Boolean expression For example, the statement If x = 5 Then y = 20 End If assigns the value 20 to y only if x is equal to 5. The ( = )is used as a relational operator to compare x to a certain value ( 5 in this case ) The general statement is: If condition Then statements End If The condition of an If…Then should never make an equality comparison between floating point numbers because of the possibility of round off error. © 2012 EMC Publishing, LLC

2 Chapter 4 Relational Operators
4/22/2017 5:29 AM Chapter 4 Relational Operators Operator Meaning = equal to < less than <= less than or equal to > greater than >= greater than or equal to <> not equal to Relational operators are used to form Boolean expressions. Boolean expressions evaluate to True or False. Note that the equal sign is used as both an assignment operator and a relational operator. © 2012 EMC Publishing, LLC

3 Chapter 4 The If…Then…Else Statement
4/22/2017 5:29 AM Chapter 4 The If…Then…Else Statement Contains an Else clause that is executed when the If condition evaluates to false. For example, the statement If x = 5 Then y = 20 Else y = 10 End If assigns the value 20 to y if x is equal to 5 or the value 10 if x is not equal to 5. If condition Then statements Else End if GPS: indentation © 2012 EMC Publishing, LLC

4 Chapter 4 Nested If…Then…Else Statements
4/22/2017 5:29 AM Chapter 4 Nested If…Then…Else Statements Should be indented to make the logic clear. Nested statement executed only when the branch it is in is executed. For example, the statement If x = 5 Then y = 20 Else If x > 5 Then y = 10 Else y = 0 End If End If evaluates the nested If…Then…Else only when x is not equal to 5. Second is “nested” GPS: indentation TIP: when you click a keyword in a control structure all of the keywords in the structure are highlighted. © 2012 EMC Publishing, LLC

5 Chapter 4 The If…Then…ElseIf Statement
4/22/2017 5:29 AM Chapter 4 The If…Then…ElseIf Statement Used to decide among three or more actions. Conditions must be properly ordered for the statement to evaluate as expected. For example, the statement If x < 5 Then y = 20 ElseIf x < 10 Then y = 40 ElseIf x < 15 Then y = 80 End If would give very different results if the conditions were ordered differently. Used to decide among 3 or more courses of action.Syntax: If condition Then statements ElseIf condition Then Else Statements End If. There can be multiple ElseIf clauses, and the last Else is optional GPS: Decision structures with many branches can become difficult to understand so brief inline comments help Write TestGrade and keep modifying it: Private Sub btnCheckGrade_Click(sender As Object, e As System.EventArgs) Handles btnCheckGrade.Click Dim grade As Integer grade = Val(Me.txtTestScore.Text) If grade >= 70 Then Me.lblComment.Text = "Great Job" End If End Sub © 2012 EMC Publishing, LLC

6 Chapter 4 The Select…Case Statement
4/22/2017 5:29 AM Chapter 4 The Select…Case Statement The result of an expression determines which statements to execute. The Case Else code is optional and is executed when none of the previous cases are met: Select Case numLegs Case 2 Me.lblMessage.Text = "human" Case 4 Me.lblMessage.Text = "beast" Case 8 Me.lblMessage.Text = "insect" Case Else Me.lblMessage.Text = "???" End Select Syntax: Select expression Case value statements Case Else End Select The expression must evaluate to a built-in data type. Else clause is optional. Value type should match the expression type and can be: a single value, a list separated by commas or a range separated by the keyword” To” Another Example: Select Case score Case 0, 10 Me.lblMessage.Text = “Nice try” ‘score is 0 or 10 Case 20 To 23 Me.lblMessage.Text = “Great!” ‘score is 20, 21, 22 or 23 Me.lblMessage.Text = “Invalid score.” ‘score not, 0, 10, 20 © 2012 EMC Publishing, LLC

7 Chapter 4 The Select…Case Is Statement
4/22/2017 5:29 AM Chapter 4 The Select…Case Is Statement Compares the result of an expression to a range of values to determine which statements to execute. For example: Select Case score Case Is < 10 Me.lblMessage.Text = "Nice try." Case Is < Me.lblMessage.Text = "Good." Case Is >= Me.lblMessage.Text = "Great!" End Select Compares the result of an expression to a range of values when a relational operator is part of the value. Write TestGrade using case © 2012 EMC Publishing, LLC

8 Chapter 4 The Rnd() Function
4/22/2017 5:29 AM Chapter 4 The Rnd() Function Uses a formula to generate a sequence of numbers that are each greater than 0 and less than 1 and then returns one number from the sequence. A random integer in a range is generated by using the formula: Int(highNum – lowNum + 1) * Rnd() + lowNum) Random integers are produced by using the Int() function along with the Rnd() function: Int(21 * Rnd() + 10) '10 to 30 The Randomize() statement initializes the random number generator. Int() requires a numeric value and returns the integer part of that number without rounding. Fix() works the same as Int() for positive numbers. - For negative numbers Int() returns the first negative integer less than or equal to its argument. Int(-5.4)->6 Fix() returns the first negative integer that is greater than or equal to its argument Fix(-5.4)->5 Randomize() uses a value based on the computer’s clock as a seed for the random generator. The seed is a starting value for calculating the sequence of pseudorandom numbers Write RandomNumbers © 2012 EMC Publishing, LLC

9 A set of steps that outline how to solve a problem.
4/22/2017 5:29 AM Chapter 4 Algorithms A set of steps that outline how to solve a problem. Can be implemented in plain English or in a mix of English and program code called pseudocode. Flowcharts are another option Algorithms allow a programmer to think through a program before actually typing code, which may reduce errors in logic. Pseudo code is a mix of English and program code without syntax rules to follow. It helps reducing logic errors. © 2012 EMC Publishing, LLC

10 Chapter 4 Static Variables
4/22/2017 5:29 AM Chapter 4 Static Variables Declared with the keyword Static instead of Dim. Have a lifetime the duration of the program's running time. Used to extend the lifetime of local variables in a procedure. Should be explicitly initialized when declared. A better choice than a global variable because the scope of the variable can be limited. The lifetime of a local variable is the duration of the procedure in which it was declared. The lifetime of a global variable is the duration of the program Static variables are necessary in event procedures with variables that should be retained in memory throughout program execution. The scope of a static variable is local to the procedure it is declared but its lifetime is the duration of the program. !!! A variable declared in a Click event procedure is redeclared and reinitialized each time the Click event occurs unless it is declared as Static. Unless the the variable is assigned a new value, the value is retained throughout program execution. © 2012 EMC Publishing, LLC

11 Chapter 4 Compound Boolean Expressions
4/22/2017 5:29 AM Chapter 4 Compound Boolean Expressions More than one Boolean expression in a single condition. Formed using the And, Or, or Not operators. Order of operations: Not evaluated first, And second, Or last. Compound Boolean expressions use more than one Boolean expression to determine if a condition is true or false. © 2012 EMC Publishing, LLC

12 Chapter 4 And Truth Table
4/22/2017 5:29 AM Chapter 4 And Truth Table And Exp1 Exp2 Result True False © 2012 EMC Publishing, LLC

13 Or Exp1 Exp2 Result True False Chapter 4 Or Truth Table
4/22/2017 5:29 AM Chapter 4 Or Truth Table Or Exp1 Exp2 Result True False © 2012 EMC Publishing, LLC

14 Chapter 4 Not Truth Table
4/22/2017 5:29 AM Chapter 4 Not Truth Table Not Exp Result True False Write GuessingGame. © 2012 EMC Publishing, LLC

15 Chapter 4 The MessageBox Class
4/22/2017 5:29 AM Chapter 4 The MessageBox Class A predefined dialog box that displays a message to the user. Includes the Show() method for displaying the dialog box. For example: MessageBox.Show(message) A message box can display text in the title bar by including a string as second parameter. Ex: MessageBox.Show(“Good guess!”, “Game”) will display a message box with Game in the title bar © 2012 EMC Publishing, LLC

16 Chapter 4 Counter Variables
4/22/2017 5:29 AM Chapter 4 Counter Variables A variable that is incremented by a constant value. Used for counting guesses, the numbers of values entered, the number of times a button was clicked, and so on. The value of a counter is updated in a statement similar to: counter = counter + CONSTANT Should be initialized when declared and updated by an unchanging amount. Many algorithms involve counting. Applications written for algorithms that involve counting use a counter variable for storing a number that is incremented by a constant value. CONSTANT is defined globally, as Const numTries = numTries + 1 can be written as numTries += 1 Counters are sometimes counted backwards: numTries -= 1 Counter should be initialized and then updated by an unchanged amount ( STEP is a good identifier ) A counter in an event procedure should be declared as Static variable so it is initialized only once. © 2012 EMC Publishing, LLC

17 Chapter 4 Assignment Operators
4/22/2017 5:29 AM Chapter 4 Assignment Operators Operator Operation += addition and then assignment -= subtraction and then assignment © 2012 EMC Publishing, LLC

18 Chapter 4 The CheckBox Control
4/22/2017 5:29 AM Chapter 4 The CheckBox Control Check boxes allow the user to select options.. Unlike Radio buttons, more than one can be selected. (Name) should begin with chk. Text is the text displayed next to the box. Checked is set to True if the box should be displayed as checked. An If…Then statement is often used to determine if a check box is checked or cleared. Related Check boxes are grouped together in a GroupBox. A Click event is sometimes coded for a check box. This procedure executes when a check box is clicked and usually includes code to determine the state of the check box and then performs actions depending on whether the check box was selected or cleared. Write: MorningToDo © 2012 EMC Publishing, LLC

19 Chapter 4 Implicit Line Continuation
4/22/2017 5:29 AM Chapter 4 Implicit Line Continuation A statement typically fits on one line, but can be continued onto the next line using a line-continuation sequence: If Not (Me.chkBed.Checked And Me.chkLunch.Checked _ And Me.chkHomework.Checked And Me.chkTeeth.Checked) Then ... In many cases, you can continue a statement on the next consecutive line without using the underscore character (_): after a comma (,) after an open parenthesis (() or before a closing parenthesis ()) after an open curly brace ({) or before a closing curly brace (}) after assignment operators (=, &=, :=, +=, -=, *=, /=, \=, ^=) after binary operators (+, -, /, *, Mod, <>, <, >, <=, >=, And, Or) A line of code can be about 65,000 characters in length. It is easier to work with lines of 80 characters or less. © 2012 EMC Publishing, LLC


Download ppt "Chapter 4 The If…Then Statement"

Similar presentations


Ads by Google