IF...THEN: Difference between revisions

From QB64 Phoenix Edition Wiki
Jump to navigation Jump to search
m (Removed protection from "IF...THEN")
No edit summary
 
(10 intermediate revisions by the same user not shown)
Line 1: Line 1:
[[IF...THEN]] statements make boolean (true or false) evaluations to automate program decision making.
[[IF...THEN]] statements make boolean (true or false) evaluations to automate program decision making.


{{PageSyntax}}
{{PageSyntax}}
===Single-line===
 
=== Single-line ===
: [[IF]] {{Parameter|conditionStatement}} [[THEN]] ''{code}'' [[ELSE]] ''{alternativeCode}''
: [[IF]] {{Parameter|conditionStatement}} [[THEN]] ''{code}'' [[ELSE]] ''{alternativeCode}''
: [[IF]] {{Parameter|conditionStatement}} [[GOTO]] ''lineLabel''
: [[IF]] {{Parameter|conditionStatement}} [[GOTO]] ''lineLabel''


 
=== Block ===
===Block===
: [[IF]] {{Parameter|conditionStatement}} [[THEN]]
: [[IF]] {{Parameter|conditionStatement}} [[THEN]]
:: ''{code}''
:: ''{code}''
Line 24: Line 25:
* Multiple conditional evaluations can be made using inclusive [[AND (boolean)|AND]] or alternative [[OR (boolean)|OR]] conditional expressions.
* Multiple conditional evaluations can be made using inclusive [[AND (boolean)|AND]] or alternative [[OR (boolean)|OR]] conditional expressions.
* [[THEN]] is not required when [[GOTO]] is used to send program flow to a line number or label.
* [[THEN]] is not required when [[GOTO]] is used to send program flow to a line number or label.
* [[IF]] statements can also have alternative evaluations using [[ELSEIF]] and [[ELSE]] conditions.  
* [[IF]] statements can also have alternative evaluations using [[ELSEIF]] and [[ELSE]] conditions.
* When the [[IF]] statement and/or code to be run is more than code line, an [[END IF]] statement must be used.
* When the [[IF]] statement and/or code to be run is more than code line, an [[END IF]] statement must be used.
* With multiple code lines to run, end the IF statement with THEN and place all of the code on lines below that line.
* With multiple code lines to run, end the IF statement with THEN and place all of the code on lines below that line.
Line 32: Line 33:
* Use [[colon]]s to execute multiple statements in a single-line IF statement.
* Use [[colon]]s to execute multiple statements in a single-line IF statement.
* An '''[[underscore]]''' can be used anywhere after the code on a single-line to continue it to the next line in '''QB64'''.
* An '''[[underscore]]''' can be used anywhere after the code on a single-line to continue it to the next line in '''QB64'''.
* '''NOTE:''' [[STRING]] values can only be evaluated in an IF statement if a value is compared to a literal or [[CHR$]] string value. '''QB64 may not compile literal IF string statements or indicate an IDE coding error.''' Use [[LEN]] or [[ASC]] to compare strings numerically.
* '''NOTE:''' [[STRING]] values can only be evaluated in an IF statement if a value is compared to a literal or [[CHR$]] string value. '''QB64 may not compile literal IF string statements or indicate an IDE coding error.''' Use [[LEN]] or [[ASC (function)|ASC]] to compare strings numerically.




 
{{RelationalOperationsPlugin}}
{{Template:RelationalTable}}
 
 
<center> When evaluating a number value, no IF value > 0 operation is necessary for values not 0. Use: IF value THEN </center>




Line 54: Line 51:




{{Template:LogicalTruthTable}}
{{LogicalTruthPlugin}}


<center>* '''Note that Basic returns -1 for True and 0 for False.'''</center>
<center>* '''Note that Basic returns -1 for True and 0 for False.'''</center>
Line 61: Line 58:
{{PageExamples}}
{{PageExamples}}
''Example 1:'' In a one line IF statement, only [[REM]] can be used to comment out the action without an [[END IF]] error:
''Example 1:'' In a one line IF statement, only [[REM]] can be used to comment out the action without an [[END IF]] error:
{{CodeStart}} '' ''
{{CodeStart}}
{{Cl|INPUT}} "Enter a number over or under 100: ", x
{{Cl|INPUT}} "Enter a number over or under 100: ", x
{{Cl|IF...THEN|IF}} x > 100 {{Cl|THEN}} {{Cl|PRINT}} x  
{{Cl|IF...THEN|IF}} x > 100 {{Cl|THEN}} {{Cl|PRINT}} x
{{Cl|IF...THEN|IF}} x > 100 {{Cl|THEN}} {{Cl|REM}} {{Cl|PRINT}} x '' '
{{Cl|IF...THEN|IF}} x > 100 {{Cl|THEN}} {{Cl|REM}} {{Cl|PRINT}} x '' '
{{CodeEnd}}
{{CodeEnd}}
Line 69: Line 66:


''Example 2:'' IF statement blocks require that the IF THEN and END IF statements be separate from the code executed.
''Example 2:'' IF statement blocks require that the IF THEN and END IF statements be separate from the code executed.
{{CodeStart}} '' ''
{{CodeStart}}
{{Cl|INPUT}} "Enter a number over or under 100: ", x
{{Cl|INPUT}} "Enter a number over or under 100: ", x
{{Cl|IF...THEN|IF}} x > 100 {{Cl|THEN}}
{{Cl|IF...THEN|IF}} x > 100 {{Cl|THEN}}
Line 75: Line 72:
   {{Cl|PRINT}} y
   {{Cl|PRINT}} y
   {{Cl|PRINT}} x
   {{Cl|PRINT}} x
{{Cl|END IF}} '' ''
{{Cl|END IF}}
{{CodeEnd}}
{{CodeEnd}}




''Example 3:'' True or False evaluation of a numerical value executes only when the value is not 0. '''Cannot evaluate [[STRING]] values.'''
''Example 3:'' True or False evaluation of a numerical value executes only when the value is not 0. '''Cannot evaluate [[STRING]] values.'''
{{CodeStart}} '' ''
{{CodeStart}}
{{Cl|INPUT}} "Enter a number or just hit Enter: ", x
{{Cl|INPUT}} "Enter a number or just hit Enter: ", x
{{Cl|IF...THEN|IF}} x {{Cl|THEN}} {{Cl|PRINT}} x '' ''
{{Cl|IF...THEN|IF}} x {{Cl|THEN}} {{Cl|PRINT}} x
{{CodeEnd}}
{{CodeEnd}}
:Example will only print if a numerical value is True (positive or negative). (Equivalent to: IF x > 0 OR x < 0 THEN evaluation)
:Example will only print if a numerical value is True (positive or negative). (Equivalent to: IF x > 0 OR x < 0 THEN evaluation)
Line 88: Line 85:


''Example 4:'' Multiple evaluations using parenthesis to determine the order.
''Example 4:'' Multiple evaluations using parenthesis to determine the order.
{{CodeStart}} '' ''
{{CodeStart}}
{{Cl|INPUT}} "Enter a number over or under 100 or 50: ", value
{{Cl|INPUT}} "Enter a number over or under 100 or 50: ", value
{{Cl|IF...THEN|IF}} (value% > 100 {{Cl|AND (boolean)|AND}} value% < 200) {{Cl|OR (boolean)|OR}} value% = 50 {{Cl|THEN}} {{Cl|PRINT}} "OK" '' ''
{{Cl|IF...THEN|IF}} (value% > 100 {{Cl|AND (boolean)|AND}} value% < 200) {{Cl|OR (boolean)|OR}} value% = 50 {{Cl|THEN}} {{Cl|PRINT}} "OK"
{{CodeEnd}}
{{CodeEnd}}




''Example 5:'' Using multiple IF options in a one line statement.
''Example 5:'' Using multiple IF options in a one line statement.
{{CodeStart}} '' ''
{{CodeStart}}
{{Cl|INPUT}} "Enter a number over or under 200: ", x
{{Cl|INPUT}} "Enter a number over or under 200: ", x
{{Cl|IF...THEN|IF}} x > 200 {{Cl|THEN}} {{Cl|PRINT}} "High" {{Cl|{{Cl|ELSEIF}}}} x < 0 {{Cl|THEN}} {{Cl|PRINT}} "Low" {{Cl|{{Cl|ELSE}}}} {{Cl|PRINT}} "OK"
{{Cl|IF...THEN|IF}} x > 200 {{Cl|THEN}} {{Cl|PRINT}} "High" {{Cl|{{Cl|ELSEIF}}}} x < 0 {{Cl|THEN}} {{Cl|PRINT}} "Low" {{Cl|{{Cl|ELSE}}}} {{Cl|PRINT}} "OK"
'' ''
 
{{CodeEnd}}
{{CodeEnd}}




''Example 6:'' [[STRING]] values can be compared using greater than, less than, not equal to or equal to operators only.
''Example 6:'' [[STRING]] values can be compared using greater than, less than, not equal to or equal to operators only.
{{CodeStart}} '' ''
{{CodeStart}}
PRINT "Press a letter key: ";
PRINT "Press a letter key: ";
Key$ = {{Cl|INPUT$}}(1)
Key$ = {{Cl|INPUT$}}(1)
PRINT Key$  
PRINT Key$
IF Key$ >= {{Cl|CHR$}}(65) AND Key$ <= {{Cl|CHR$}}(90) THEN PRINT "A to Z"
IF Key$ >= {{Cl|CHR$}}(65) AND Key$ <= {{Cl|CHR$}}(90) THEN PRINT "A to Z"
{{CodeEnd}}
{{CodeEnd}}
Line 115: Line 112:
* Floating decimal point numerical values may not be compared as exactly the same value. QB64 will compare them the same.
* Floating decimal point numerical values may not be compared as exactly the same value. QB64 will compare them the same.
:''Example:'' QBasic would print ''unequal'' in the IF comparison code below even though it is exactly the same value printed.
:''Example:'' QBasic would print ''unequal'' in the IF comparison code below even though it is exactly the same value printed.
{{CodeStart}} '' ''
{{CodeStart}}
x# = 5 / 10
x# = 5 / 10
y# = 6 / 10
y# = 6 / 10
z# = x# + y#
z# = x# + y#
{{Cl|PRINT}} x#, y#, z#
{{Cl|PRINT}} x#, y#, z#
{{Cl|IF...THEN|IF}} x# + y# = z# {{Cl|THEN}} {{Cl|PRINT}} "equal" {{Cl|ELSE}} {{Cl|PRINT}} "unequal" '' ''
{{Cl|IF...THEN|IF}} x# + y# = z# {{Cl|THEN}} {{Cl|PRINT}} "equal" {{Cl|ELSE}} {{Cl|PRINT}} "unequal"
{{CodeEnd}}
{{CodeEnd}}
: Note: QB64 will make the calculation correctly and print ''equal''. Change older program code that relies on the error accordingly.
: Note: QB64 will make the calculation correctly and print ''equal''. Change older program code that relies on the error accordingly.
Line 127: Line 124:
{{PageSeeAlso}}
{{PageSeeAlso}}
* [[ELSEIF]], [[ELSE]]
* [[ELSEIF]], [[ELSE]]
* [[AND (boolean)]], [[OR (boolean)]]  
* [[AND (boolean)]], [[OR (boolean)]]
* [[NOT]], [[GOTO]]
* [[NOT]], [[GOTO]]
* [[SELECT CASE]]
* [[SELECT CASE]]
* [[Boolean]] {{text|(numerical comparisons return a true or false value)}}
* [[Boolean]] {{Text|(numerical comparisons return a true or false value)}}




{{PageNavigation}}
{{PageNavigation}}

Latest revision as of 00:36, 26 February 2023

IF...THEN statements make boolean (true or false) evaluations to automate program decision making.


Syntax

Single-line

IF conditionStatement THEN {code} ELSE {alternativeCode}
IF conditionStatement GOTO lineLabel

Block

IF conditionStatement THEN
{code}
ELSEIF conditionStatement2 THEN
{code}
ELSE
{code}
END IF


Description

  • The conditionStatement evaluation by IF must be true (-1) or a non-zero numerical value for the THEN {code} to be executed.
  • Multiple conditional evaluations can be made using inclusive AND or alternative OR conditional expressions.
  • THEN is not required when GOTO is used to send program flow to a line number or label.
  • IF statements can also have alternative evaluations using ELSEIF and ELSE conditions.
  • When the IF statement and/or code to be run is more than code line, an END IF statement must be used.
  • With multiple code lines to run, end the IF statement with THEN and place all of the code on lines below that line.
  • Multiple code line block statements require that the IF...THEN, ELSEIF, ELSE and END IF be on separate lines.
  • The IDE may return an error of NEXT without FOR or LOOP without DO when END IF does not end a statement block.
  • The QB64 IDE will indicate an error in the IF statement line until END IF closes the statement block.
  • Use colons to execute multiple statements in a single-line IF statement.
  • An underscore can be used anywhere after the code on a single-line to continue it to the next line in QB64.
  • NOTE: STRING values can only be evaluated in an IF statement if a value is compared to a literal or CHR$ string value. QB64 may not compile literal IF string statements or indicate an IDE coding error. Use LEN or ASC to compare strings numerically.


         Table 3: The relational operations for condition checking.

 In this table, A and B are the Expressions to compare. Both must represent
 the same general type, i.e. they must result into either numerical values
 or STRING values. If a test succeeds, then true (-1) is returned, false (0)
     if it fails, which both can be used in further Boolean evaluations.
 ┌─────────────────────────────────────────────────────────────────────────┐
 │                          Relational Operations                          │
 ├────────────┬───────────────────────────────────────────┬────────────────┤
 │ OperationDescriptionExample usage  │
 ├────────────┼───────────────────────────────────────────┼────────────────┤
 │   A = B    │ Tests if A is equal to B.                 │ IF A = B THEN  │
 ├────────────┼───────────────────────────────────────────┼────────────────┤
 │   A <> B   │ Tests if A is not equal to B.             │ IF A <> B THEN │
 ├────────────┼───────────────────────────────────────────┼────────────────┤
 │   A < B    │ Tests if A is less than B.                │ IF A < B THEN  │
 ├────────────┼───────────────────────────────────────────┼────────────────┤
 │   A > B    │ Tests if A is greater than B.             │ IF A > B THEN  │
 ├────────────┼───────────────────────────────────────────┼────────────────┤
 │   A <= B   │ Tests if A is less than or equal to B.    │ IF A <= B THEN │
 ├────────────┼───────────────────────────────────────────┼────────────────┤
 │   A >= B   │ Tests if A is greater than or equal to B. │ IF A >= B THEN │
 └────────────┴───────────────────────────────────────────┴────────────────┘
   The operations should be very obvious for numerical values. For strings
   be aware that all checks are done case sensitive (i.e. "Foo" <> "foo").
   The equal/not equal check is pretty much straight forward, but for the
   less/greater checks the ASCII value of the first different character is
                          used for decision making:

   E.g. "abc" is less than "abd", because in the first difference (the 3rd
        character) the "c" has a lower ASCII value than the "d".

   This behavior may give you some subtle results, if you are not aware of
                   the ASCII values and the written case:

   E.g. "abc" is greater than "abD", because the small letters have higher
        ASCII values than the capital letters, hence "c" > "D". You may use
        LCASE$ or UCASE$ to make sure both strings have the same case.


Boolean Conditional Operators:


  • AND (boolean) can be used to add extra conditions to a boolean statement evaluation.
  • OR (boolean) can be used to add alternate conditions to a boolean statement evaluation.
  • Parenthesis are allowed inside of boolean statements to clarify an evaluation.


Mathematical Logical operators:
* Truth table of the 6 BASIC Logical Operators:


               Table 4: The logical operations and its results.

       In this table, A and B are the Expressions to invert or combine.
              Both may be results of former Boolean evaluations.
  ┌────────────────────────────────────────────────────────────────────────┐
  │                           Logical Operations                           │
  ├───────┬───────┬───────┬─────────┬────────┬─────────┬─────────┬─────────┤
  │   ABNOT BA AND BA OR BA XOR BA EQV BA IMP B │
  ├───────┼───────┼───────┼─────────┼────────┼─────────┼─────────┼─────────┤
  │ truetrue  │ false │  true   │ true   │  false  │  true   │  true   │
  ├───────┼───────┼───────┼─────────┼────────┼─────────┼─────────┼─────────┤
  │ truefalse │ true  │  false  │ true   │  true   │  false  │  false  │
  ├───────┼───────┼───────┼─────────┼────────┼─────────┼─────────┼─────────┤
  │ falsetrue  │ false │  false  │ true   │  true   │  false  │  true   │
  ├───────┼───────┼───────┼─────────┼────────┼─────────┼─────────┼─────────┤
  │ falsefalse │ true  │  false  │ false  │  false  │  true   │  true   │
  └───────┴───────┴───────┴─────────┴────────┴─────────┴─────────┴─────────┘
   Note: In most BASIC languages incl. QB64 these are bitwise operations,
         hence the logic is performed for each corresponding bit in both
         operators, where true or false indicates whether a bit is set or
         not set. The outcome of each bit is then placed into the respective
         position to build the bit pattern of the final result value.

   As all Relational Operations return negative one (-1, all bits set) for
    true and zero (0, no bits set) for false, this allows us to use these
    bitwise logical operations to invert or combine any relational checks,
    as the outcome is the same for each bit and so always results into a
            true (-1) or false (0) again for further evaluations.
* Note that Basic returns -1 for True and 0 for False.


Examples

Example 1: In a one line IF statement, only REM can be used to comment out the action without an END IF error:

INPUT "Enter a number over or under 100: ", x
IF x > 100 THEN PRINT x
IF x > 100 THEN REM PRINT x  '


Example 2: IF statement blocks require that the IF THEN and END IF statements be separate from the code executed.

INPUT "Enter a number over or under 100: ", x
IF x > 100 THEN
  y = 200
  PRINT y
  PRINT x
END IF


Example 3: True or False evaluation of a numerical value executes only when the value is not 0. Cannot evaluate STRING values.

INPUT "Enter a number or just hit Enter: ", x
IF x THEN PRINT x
Example will only print if a numerical value is True (positive or negative). (Equivalent to: IF x > 0 OR x < 0 THEN evaluation)


Example 4: Multiple evaluations using parenthesis to determine the order.

INPUT "Enter a number over or under 100 or 50: ", value
IF (value% > 100 AND value% < 200) OR value% = 50 THEN PRINT "OK"


Example 5: Using multiple IF options in a one line statement.

INPUT "Enter a number over or under 200: ", x
IF x > 200 THEN PRINT "High" [[ELSEIF|ELSEIF]] x < 0 THEN PRINT "Low" [[ELSE|ELSE]] PRINT "OK"


Example 6: STRING values can be compared using greater than, less than, not equal to or equal to operators only.

PRINT "Press a letter key: ";
Key$ = INPUT$(1)
PRINT Key$
IF Key$ >= CHR$(65) AND Key$ <= CHR$(90) THEN PRINT "A to Z"
Explanation: Long STRING expression values are compared by their cumulative ASCII code values.


QBasic decimal point value comparison errors
  • Floating decimal point numerical values may not be compared as exactly the same value. QB64 will compare them the same.
Example: QBasic would print unequal in the IF comparison code below even though it is exactly the same value printed.
x# = 5 / 10
y# = 6 / 10
z# = x# + y#
PRINT x#, y#, z#
IF x# + y# = z# THEN PRINT "equal" ELSE PRINT "unequal"
Note: QB64 will make the calculation correctly and print equal. Change older program code that relies on the error accordingly.


See also



Navigation:
Main Page with Articles and Tutorials
Keyword Reference - Alphabetical
Keyword Reference - By usage