110 likes | 246 Vues
This guide explores the functionality of If statements and the use of relational and logical operators in programming. An If statement allows a program to execute different actions based on whether a given condition is true or false. We cover basic structures such as If condition Then action1 Else action2 End If, and provide examples of relational operators like <, <=, and alphabetic comparisons. Logical operators like And, Or, and Not are also examined, showing how they evaluate multiple conditions. Practical examples with code snippets illustrate these concepts in action.
E N D
Selection Structures Relational and Logical Operators; If Statements
If Statements • An If statement allows a program to decide on a course of action based on whether a condition is true or false • If condition Then • action1 • Else • action2 • End If
Relational Operator Examples • 1 <= 1 • 1 < 1 • “car” < “cat” • “Dog” < “dog”
Logical Operators • And • condition1 And condition2 • is true if both condition1 and condition2 are true • otherwise it evaluates to false • Or • condition1 Or condition2 • is true if either condition1 or condition2 (or both) are true • otherwise it evaluates to false • Not • Not condition1 • is true if condition1 is false, and is false if condition1 is true
Logical Operator Examples • Assume n = 4 and answ = “Y” • (2 < n) And (n < 6) • (2 < n) Or (n = 6) • Not (n < 6) • (answ = “Y”) And (answ = “y”) • (answ = “Y”) Or (answ = “y”) • Not (answ = “y”)
If Statements • An If statement allows a program to decide on a course of action based on whether a condition is true or false • If condition Then • action1 • Else • action2 • End If
If Statement Example Private Sub cmdComputeTip_Click() Dim cost As Single, tip As Single cost = Val(InputBox("Enter cost of meal:")) tip = cost * 0.15 If tip < 1 Then tip = 1 End If picTip.Print "Leave "; FormatCurrency(tip); " for the tip." End Sub
If Statement Example Private Sub cmdQuestion_Click() Dim name As String 'Ask for first Ronald McDonald name = UCase(InputBox("Who was the first Ronald McDonald?")) picAnswer.Cls If name = "WILLARD SCOTT" Then picAnswer.Print "Correct." Else picAnswer.Print "Nice try." End If End Sub
Nested If Example Private Sub cmdComputeBalance_Click() Dim balance As Single, amount As Single balance = Val(InputBox("Current balance:")) amount = Val(InputBox("Amount of withdrawal:")) If (balance >= amount) Then balance = balance - amount picBalance.Print "New balance is "; FormatCurrency(balance) If balance < 150 Then picBalance.Print "Balance below $150" End If Else picBalance.Print "Withdrawal denied." End If End Sub
ElseIf Example Private Sub cmdFindLarger_Click() Dim Num1 As Integer Dim Num2 As Integer Num1 = Val(txtFirstNumber.Text) Num2 = Val(TxtSecondNumber.Text) If Num1 > Num2 Then picResult.Print "The larger number is"; Num1 ElseIf Num2 > Num1 Then picResult.Print "The larger number is"; Num2 Else picResult.Print "The two numbers are equal" End If End Sub