BASIC Programming/Beginning BASIC/Control Structures/IF...THEN...ELSEIF...ELSE

From Wikibooks, open books for an open world
< BASIC Programming
Jump to navigation Jump to search

The IF...THEN...ELSEIF...ELSE control statement allows identifying if a certain condition is true, and executes a block of code if it is the case.

10 CLS
20 IF number<0 THEN
30   PRINT "Number is negative"
40 ELSEIF number>0 THEN
50   PRINT "Number is positive"
60 ELSE
70   PRINT "Number is zero"
80 END IF

In some implementations of BASIC (but permitted by most versions), the IF statement may need to be contained in one line. However, ELSEIF may not be available in this case, and there is no need for an explicit END IF:

10 CLS
20 IF number<0 THEN PRINT "Number is negative" ELSE PRINT "Number is non-negative"

This carries over into some implementations of BASIC where if the "IF...THEN" statement is followed by code on the same line then it is fully contained. That is, the compiler assumes the lines ends with "ENDIF", even if it not stated. This is important when dealing with nested "IF...THEN" clauses:

10 CLS
20 IF X<2 THEN
30   IF 2<3 THEN PRINT "This is printed if X is 1"
40 ELSE
50   IF 3<4 THEN PRINT "This is printed if X is 3"
60 END IF

The ELSE clause, while following the "IF 2<3" statement, is associated with the "IF X<2" statement, because the "IF 2<3" statement has a PRINT statement on the same line.

Let me give some more examples of "if-then-else" programs:

Q1)Input the age of a person and check whether he/she is voter or not?

Ans1) 10 CLS 20 INPUT AGE 30 IF AGE>=18 THEN 40 PRINT "VOTER" 50 ELSE 60 PRINT "NON VOTER" 70 END IF 80 END

Q2)Input the age of a person to check if he/she is a senior citizen or not a senior citizen?

Ans2) 10 CLS 20 INPUT AGE 30 IF AGE>=60 THEN 40 PRINT "SENIOR CITIZEN" 50 ELSE 60 PRINT "NOT A SENIOR CITIZEN" 70 END IF 80 END