Conditional Branching
Conditional branching helps you build programming logic. When you run a code, the compiler starts at the beginning of the statement list and makes its way to the bottom. This would be very straight forward and extremely limiting, were it not for branching. When you build code, you will often want to branch depending on a condition that you evaluate while the program is running. This is known as conditional branching and allows you to write logic such as "If you are 18 years old, you can rent a car." IF THEN ELSE
The most commonly used conditional branching statement is the IF THEN ELSE statement.
Syntax of IF THEN ELSE: IF (condition(s)) THEN
(statements)
ELSE
(statements)
END IFThe 'IF' statement is very straight forward. To explain in simple english, if a particular condition is satisfied, then do something; if not, then do something else.
An example of IF THEN ELSE: IF X > 0 THEN
Msgbox "X is positive"
ELSE
Msgbox "X is not positive"
END IFIF ELSEIF ELSE
Now, if you ponder over the above example of IF THEN ELSE you will realize that the message displayed through Msgbox is not very convincing. You can further evaluate the value of X to provide the user with a more accurate message. In simple words, after checking whether X is positive, you can also check whether X is negative or zero and give an appropriate message. To do this, IF ELSEIF ELSE comes handy.IF X > 0 THEN
Msgbox "X is positive"
ELSEIF X < 0 THEN
Msgbox "X is negative"
ELSE
Msgbox "X is zero"
END IFNested IF THEN ELSE
A Nested IF statement is when you use one or more IF statements inside another. You can build complex logic through nested IF statements. An example of a basic Nested IF statement is given below.
Suppose there are two variables 'CountryName' and 'Gender' that are taken as inputs from the user. The input for country given by the user could be India or America and the gender of course would be Male or Female. Now, assuming the user would give any of the above inputs, let's write a Nested IF statement and display an appropriate Msgbox.IF CountryName = "India" THEN
IF Gender = "Male" THEN
Msgbox "You are an Indian gentleman!"
ELSE
Msgbox "You are an Indian lady!"
END IF
ELSE
IF Gender = "Male" THEN
Msgbox "You are an American gentleman!"
ELSE
Msgbox "You are an American lady!"
END IF
END IFConditional branching is one of the basics of writing programs and using IF THEN ELSE and IF ELSEIF ELSE is an easy and efficient way to build programming logic.
Back to Visual Basic for Beginners
(statements)
ELSE
(statements)
END IF
Msgbox "X is positive"
ELSE
Msgbox "X is not positive"
END IF
Msgbox "X is positive"
ELSEIF X < 0 THEN
Msgbox "X is negative"
ELSE
Msgbox "X is zero"
END IF
IF Gender = "Male" THEN
Msgbox "You are an Indian gentleman!"
ELSE
Msgbox "You are an Indian lady!"
END IF
ELSE
IF Gender = "Male" THEN
Msgbox "You are an American gentleman!"
ELSE
Msgbox "You are an American lady!"
END IF
END IF
