440 likes | 616 Views
Chapter 5. Controlling Program Flow with Decision Structures. The If…Then Statement. If…Then statement is a decision structure that executes code when a condition is true. Example: If intGuess = 10 Then lblGuessCheckedMessage.Caption = “You guessed it!” End If
E N D
Chapter 5 Controlling Program Flow with Decision Structures
The If…Then Statement • If…Then statement is a decision structure that executes code when a condition is true. • Example: If intGuess = 10 Then lblGuessCheckedMessage.Caption = “You guessed it!” End If • If the value of intGuess is 10, the caption property of the label object is executed. • If the value of intGuess in not equal to 10, then the assignment statement is not executed and program flow continue on to the next line after the End If. • You can have multiple lines of code between the Then and End If
Equal Symbol Has two purposes: • Comparison – compare two values and return true or false. (If Statements) • Assignment – Takes the value on the right side and set the left side memory location to the value.
Boolean Expression & Relational Operators • The condition of the If condition Then statement is a Boolean expression. • Boolean expression – evaluates to either True or False. • A Boolean variable may also be used as the condition of the If…Then statement. • Example: Dim blnAns As Boolean blnAns = True If blnAns Then Some type of code goes here End If
Relational Operators Six relational operators: • = equal sign • < less than • <= less than or equal to • > Greater than • >= Greater than or equal to • <> Not equal to
Round off Error • If…Then statement should never make an equality (=) comparison between floating point numbers (numbers with decimals) because of the possibility of a round off error.
The If…Then…Else Statement • Optional to an If…Then statement • Executed when the If condition evaluates to False. • If…Then…Else form: If condition Then statement Else statement End If
Example of an If…Then…Else Statement Private Sub cmdCheckGuess_Click() Const intNum As Integer = 10 Dim intGuess As Integer intGuess = txtGuess.Text If intGuess = intNum Then lblGuessMessage.Caption = “You guessed it” Else lblGuessMessage.Caption = “Try again” End If End Sub Typing a number other than 10 will display “Try again”
Indentation • Indentation helps readability • Indentation has no effect on the execution of the statement. • For an If…Then…Else all executable code inside the statement should be indented. Example: If condition Then executable code Else executable code End If
Nested If…Then…Else • Nested If…Then…Else Statement - is an If statement inside another If statement or an Else statement. • There are many combinations that you can use with nested If statements that you can not cover all of them.
Examples If Boolean Condition Then Code1 Statement If Boolean Condition Then Code2 Statement ‘ nested if statement End If Else Code3 Statement End If
Example Continued • If intGuess = intSecretNumber Then lblGuessCheckedMessage.caption = “you guessed it!” Else If intGuess < intSecretNumber Then lblGuessCheckedMessage.caption = “too low” Else lblGuessCheckedMessage.caption = “too high” End If End If (nested statements should be indented for good programming style)
Examples If condition1 Then Code1 Else If condition2 Then Code2 Else Code3 End If End If When conditional1 is false, the else portion will run and check condition2. If codition2 is false then Code3 will run. If condition1 is true, Code1 will run and everything else is skipped. If condition1 is false and condition2 is true then Code2 will run.
Example If condition1 Then If condition2 Then If condition3 Then Code1 Else Code2 End If Else Code3 End If Else Code4 End If
The If…Then…ElseIf Statement • Is used to decide among three or more actions where only the first If or ElseIf condition that is true runs and all others are skipped. • Notice there is no space in the ElseIf • An ElseIf can contain an If statement • The Else statement is optional
Example If condition1 Then Code1 ElseIf condition2 Then Code2 ElseIf condition3 Then Code3 ElseIf condition4 Then Code4 Else Code5 End If
Example Continued (ElseIf) • Used to decide among 3, 4, or more actions • This example includes three possible decisions in the IF..Then…ElseIf: If intGuess = intSecretNumber Then lblGuessCheckedMessage.caption= “you guessed it” ElseIf intGuess < intSecretNumber Then lblGuessedCheckedMessage.catpion=“too low” Else lblGuessCheckedMessage.caption= “too high” End If
Programming Style • The use of If…Then… ElseIf is better and easier to read then the nested If…Then…Else • Beware of the range of the conditions in an If…Then…ElseIf because the first condition that evaluates true will run and then the rest of the ElseIf statements are skipped.
Generating Random Numbers • Built-in function – Built-in meaning that Visual Basic already has it and it doesn’t need to be coded. • Rnd function – generates a random number greater than or equal to 0 and less than 1.
Functions • Visual Basic has many built-in functions. • Function – is a procedure that performs a task and returns a value. • Predefined functions are used by including the function name in a statement. • When the line of code containing the function name is executed, the statements that make up the function are executed.
Function Arguments • Arguments are data that functions requires to perform its task. • The data is “passed” to the function as arguments enclosed in parentheses after the function name. • Example: Int(-5.4) which will return –6.
RND function • Using Rnd alone generates random numbers greater than or equal to 0 and less than 1. • If you want to generate numbers in a greater range, simply multiply Rnd by the upper number of the range you want. • Example: lblRanNum.Caption = Rnd * 10 • Generate numbers in a range with an upper and lower limt do the following. • (HighNumber – LowNumber + 1) * Rnd + LowNumber • Where HighNumber and LowNumber represents the limits of the range.
Int function • Returns the Integer portion of a number without rounding. • Example: Int(21 * Rnd + 10) ‘will return the integer portion only Again, This number is found by using the equation (High Number – Low Number + 1) * Rnd + Low Number
Fix Function • Very similar to the Int function • Both will work the same for positive numbers by returning the Integer portion only. • Negative numbers Integer function returns the Integer less than or equal to its negative argument. • Fix Function returns the first integer greater than or equal to its negative argument • Example: Fix(- 5.4) would return (– 5). • Int(- 5.4) would return (– 6).
Randomize • Programs that uses Rnd function should include a Randomize statement. • The Randomize statement initializes the Visual Basic Rnd function so different random numbers are generated in a program from run to run. • Best place for the Randomize statement is in the Form_Load() procedure because it occurs only once. • Example: Private Sub Form_Load() Randomize End Sub
How Random Numbers are Generated • Uses the computer’s clock to generate a seed value. • A seed is a value used by the Rnd function to generate a pseudorandom (not truly random) sequence of numbers. • Each time the Rnd is used, the next number in the sequence is returned.
Scope • Scope of a variable or constant – refers to its accessibility among procedures. Is where the variable or constant can be accessed or used. • Example: the scope of a variable declared in an event procedure is limited to that procedure. No other procedure can refer to that variable or change its value. • Variables declared in procedures are considered “local” variables of that procedure.
Global Variables • Global variables declared in the General section of a form module are accessible to every procedure. This is known as “Global” variables. • Global variable declaration should use the keyword Private in place of the keyword Dim. • Global Constants declarations should use the keyword Private in front of the keyword Const. • Global variables are declared right after the Option Explicit statement outside of any procedures.
Programming Style • Local variables should be used whenever possible because they don’t interfere with other procedures. • Two procedures can contain the same variable names and each has their own values. • Global variables that are not declared as constant can cause debugging problems because any procedure can change the global variable value. You can do it without a constant but you must make sure errors do not occur—Check Code
Logical Operators • 3 types of logical operators • And • Or • Not • A logical operator joins two expressions to create an expression that evaluates to either true or false • Example: dblnum > 0 And dblnum <= 10 will evaluate to true if dblNum is in the range 0<dblnum<=10. It would evaluate false otherwise.
And • Expression1 And Expression2 • True And True = True • False And True = False • True And False = False • False And False = False • So the only time an And operator evaluates to true is when both expressions are true.
Or • Expression1 Or Expression2 • True Or True = True • False Or True = True • True Or False = True • False Or False = False • So if one or both expressions evaluates to true than it equals true. The only time it evaluates to false if both expressions are false.
Not • Expression Result • Not True False • Not False True • Note that the Not changes it to the opposite.
Operator Precedence • Not is evaluated before an And • An And is evaluated before an Or • Or is evaluated last • You can use parentheses to change the order.
Algorithms • Algorithm – is a series of steps that tell how to solve a problem. • Pseudocode – half English and half code of instructions to solve a problem. • Flow Chart – use of symbols to show the flow of code.
Errors • Compile Error –Syntax Errors • Run Time errors – occurs at runtime. Dividing a variable by zero. • Logic errors – programs runs but the output is incorrect. Usually bad formula.
Message Boxes • Predefined dialog box that is used to provide information to the user. • To display a Message Box use MsgBox “message”. • Example: MsgBox “Hello World”
PasswordChar Property in a Text Box • If you go to the text box property box, find PasswordChar and type (*)
Using Counters • Counter is a numeric variable used to store a value that is incremented (usually increased by one) during run time. • The form of a counter: • Identifier = indentifier + constant • intNum = intNum + 1 • Each time the statement above is executed, intNum is increased by one. • Counters are usually Global and initialized in the Form_Load procedure.
Check Boxes • Used to obtain input from the user. • Unlike option buttons, more than one check box can be selected at a time.
Check Boxes Properties of a CheckBox control Name – identifies the object with the prefix “chk” Caption – changes the text displayed as the check box label. Value – can be set to vbunchecked, vbchecked, or grayed. The value can be changed during run time.
Click Event A click event procedure is usually coded for each check box. The click event procedure is executed when the user clicks on a check box and should include an If..Then statement.
Print Form • Methods – is used to perform an action. • Predefined methods are like predefine properties in that the method already exists and all you have to do is to invoke it. • The Form object have a method called PrintForm that is used to print a form at run time. • Example: FormName.PrintForm or Me.PrintForm if it is the same Form.
Visual Basic Programming Guidelines • Use the program specification or description to design the application interface. • Create the application interface and appropriately name all objects before writing any code • Develop an algorithm for objects with complex tasks. Pseudocode may need to be written for several objects. • Code at least one kind of event procedure for each object in an application, excluding label and frames objects.