ZX BASIC:IF

From BorielWiki
Jump to: navigation, search

Contents

IF ... END IF

IF is a very powerful control flow sentence that allows you to make decisions under specified contitions.

Syntax

IF expression THEN sentences
[ELSEIF expression THEN sentences]
[ELSEIF expression THEN sentences]
 ...
[ELSE sentences]
END IF

Examples

IF a < 5 THEN PRINT "A is less than five"
ELSE PRINT "A is greater than five"
END IF

Sentences might be in multiple lines:

IF a < 5 THEN
    PRINT "A is less than five"
    a = a + 5 
ELSE
    PRINT "A is greater than five"
END IF

Since IF is a sentence, it can be nested; however, remember that every IF must be closed with END IF:

IF a < 5 THEN
    PRINT "A is less than five"
    IF a > 2 THEN
        PRINT "A is less than five but greater than 2"
    END IF
ELSE IF a < 7 THEN
        PRINT "A is greater or equal to five, but lower than 7"
    ELSE
        PRINT "A is greater than five"
    END IF
END IF

Using ELSEIF

In the example above, you see that nesting an IF inside another one could be somewhat verbose and error prone. It's better to use the ELSEIF construct. So the previous example could be rewritten as:

IF a < 5 THEN
    PRINT "A is less than five"
    IF a > 2 THEN
        PRINT "A is less than five but greater than 2"
    END IF
ELSEIF a < 7 THEN
    PRINT "A is greater or equal to five, but lower than 7"
ELSE
    PRINT "A is greater than five"
END IF

Remarks

  • This sentence is extended and not compatible with the Sinclair BASIC version: Every IF must be closed with END IF

See Also

Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox
Translate
Google AdSense