QBasic Tutorial 7 - IF Statements - QB64


If statements are used to check conditions in the program. The structure of the if statement is as follows:


If <condition> Then

    Do something

ElseIf <condition> Then

    Do something>

Else

    Do something

End If


The Expression Signs (Relational Operators) For If Statements Are:


<     Less than

<=   Less than or equal to

>     Greater than

>=   Greater than or equal to

=     Equal to

<>   Not Equal to


When the condition is met, the code associated with condition will trigger. For example, in a new file type:


CLS                  

IF 5 > 2 THEN

    PRINT “5 Is Greater Than 2”

END IF             



The output will be:


5 Is Greater Than 2


Code Download: QBT7_1.BAS


If the greater than changed to a less than, the computer will not output any information because the condition is not met:


CLS                  

IF 5 < 2 THEN

    PRINT “5 Is Less Than 2”

END IF             



Code Download: QBT7_2.BAS



In a new file type:



CLS  


IF 5 > 10 THEN

    PRINT “5 Is Greater Than 10”

ELSE      

    PRINT “5 Is Not Greater Than 10”

END IF  



Since 5 is not greater than 10, the output will be:



5 Is Not Greater Than 10



Code DownloadQBT7_3.BAS



The next example will prompt the user to enter two numbers. The program will check for the greatest number and give a report on its findings.



DIM Num1 AS INTEGER

DIM Num2 AS INTEGER


CLS

INPUT "Enter First Number: ", Num1    

INPUT "Enter Second Number: ", Num2   


IF Num1 > Num2 THEN

  PRINT Num1; "Is Greater Than"; Num2

ELSEIF Num2 > Num1 THEN       

  PRINT Num2; " Is Greater Than"; Num1

ELSE     

  PRINT “The Numbers Are The Same”

END IF



The output is dependent on the user input.



Code DownloadQBT7_4.BAS



Some things to try on your own:


Create a program that checks to see if one number is greater than or equal to the second number.



Video Tutorial: QBasic Tutorial 7 - IF Statements - QB64

Previous Tutorial                  Next Tutorial