The IF Statement (advanced)

The IF statement allows make a comparison between two things (usually variables and numbers) and if that comparison is true then it allows you to execute a QBASIC statement (like PRINT or INPUT or do a calculation).

Here is what an IF-THEN-ELSE statement looks like

IF SomeComparisonIsTrue THEN
    doSomething
    doSomething
    doSomething
ELSE
    doSomething
    doSomething
ENDIF

Where:

  • SomeComparisonIsTrue = A comparison between two things
  • doSomething = is some QBASIC statement or calculation
  • ELSE = What to do if the Comparison is NOT true
  • ENDIF = The end of the IF statement

NOTE:

It is a good idea to indent the statements between the IF and the ELSE and between the ELSE and the ENDIF

Example uses of the IF-ELSE statement in Qbasic:

Sample#1:

LET PW$ =""
LET option = 0

PRINT "Enter the password";
INPUT PW$

IF PW$ = "TIK" THEN
   PRINT "You are correct!"
IF
   PRINT "What option would you like to choose";
   INPUT option
IF
ELSE
   PRINT "Access is denied!"
IF
END IF

Sample#2:

LET mark  = 0

PRINT "Enter Your mark please";
INPUT mark

IF mark >= 80 THEN
   PRINT "You are on the Honour Roll"
   IF mark >= 90 THEN
       PRINT "You are very smart"
   END IF
ELSE
   PRINT "You are NOT on the Honour Roll"
END IF

NOTE: It is a good idea to indent the statements between the IF and the END IF

Compound Checking Conditions & Logic Operators:

Use

The LOGIC involved

Example of Use

And

Both Conditions must be TRUE

IF (age >= 18) AND (age <=65) THEN
      PRINT "You are Hired"
 
END IF

Or

Either Condition may be true

IF (age < 18) OR (age >65) THEN
      PRINT "You are NOT Hired"
END IF

** The AND operator binds more strongly than the OR operator just like the multiplication (*) operator takes precedence over the addition (+) operator. If you keep this in mind, it will help you to debug logic errors in your code.

Sample#3:

LET PW$ = ""
LET USER$ = ""
LET option = 0

PRINT "Enter you user name";
INPUT USER$

PRINT "Enter the password";
INPUT PW$

IF USER$ = "TIK" AND PW$ = "cool" THEN
   PRINT "You are correct!"
IF
   PRINT "What option would you like to choose";
   INPUT option
   IF option = 1
      PRINT "Going to user menu ..."
   END IF
     
   IF option = 2
      PRINT "Logging off ..."
      QUIT
   END IF
      IF
IF
ELSE
   PRINT "Access is denied!"
IF
END IF


Sample#4:

LET mark  = 0

PRINT "Enter Your age please";
INPUT age

IF age <18  OR age > 65 THEN
   PRINT "You are NOT eligible for this game"
ELSE
   PRINT "Welcome to this game"
END IF