Qbasic Tutorial for beginners and children (Under Construction)


Making Decisions

You may need to ask the user to choose between one or more options. The 

IF - THEN - ELSE statement and the 

SELECT CASE statement

are used to make decisions depending upon specified conditions.

The IF - THEN - ELSE statement

The syntax for the If then statement is as follows:

IF condition1 THEN

[ List of instructions to be executed if condition1 is met]

END IF

 

IF condition1 THEN

[ List of instructions to be executed if condition1 is met ]

ELSE

[ List of instructions to be executed if condition1 is not met ]

END IF

 

IF condition1 THEN

[ Do what if to do condition1 is met ]

ELSEIF condition2 THEN

[ Do what if to do condition1 is not met and condition2 is met]

ELSE

[ Do what if neither condition1 nor condition2 are met ]

END IF

 

Example: Telling whether you have passed the test

Write a program that will ask the user for his score in math and say whether he has passed the test. The pass mark is 40.

Algorithm Program Code

Clear the screen

Write message on screen

Get user score

Check whether the score is greater than 40 and print "You have passed the test"

CLS

PRINT "Enter your score in maths: ";

INPUT score

IF Score >= 40 THEN 

    PRINT "You have passed the test."

END IF

Test 1: Output on Screen

Enter your score in maths: 45

You have passed the test.

 

 

 

 

Test 2: Output on Screen

Enter your score in maths: 30

 

 

 

 

You will have noticed that in test 2 the program did not display any message because the condition was not met. You can use the ELSE statement to give a message when a condition is not met. Here's an illustration:

Program Code

CLS

PRINT "Enter your score in maths: ";

INPUT score

IF Score >= 40 THEN 

    PRINT "You have passed the test."

ELSE

    PRINT "You have failed the test."

END IF

Test 1: Output on Screen

Enter your score in maths: 45

You have passed the test.

 

 

 

 

Test 2: Output on Screen

Enter your score in maths: 30

You have failed the test.

 

 

 

 

 

Sometimes you may need to use nested IF - THEN - ELSE statement ie and IF-THEN-ELSE statement inside another IF-THEN-ELSE statement.

 

[ Previous Index Next ]


pages viewed since January  19 2002