Tip:
Highlight text to annotate it
X
In this lesson, we will discuss If-Then-Else structures.
When you want your program to execute certain statements if a test condition is True, and other statements if the test condition is False, you
can use an If-Then-Else structure.
If the test condition is True, only the statements between the If and Else will be executed.
If the test condition is False, only the statements between the Else and End If will be executed.
In this example, an If-Then-Else structure is used to help the user decide whether he or she should buy a pizza.
After running the program, two message boxes will appear.
The first message box states: “The pizza is too expensive”
The second message box states: “x is 700”
Let’s examine why these messages appear.
The variables costpizza and x are given Double data types and costpizza is assigned the value 11.
costpizza is a variable that will store the price of the pizza and x is a variable that is used to help demonstrate how If-Then-Else structures
work.
There is a test condition at the beginning of the If-Then-Else structure.
Is costpizza greater than 10? Is 11 greater than 10?
True, so all statements between If and Else are executed.
A message box displays: “The pizza is too expensive” and x is assigned the value 700.
We reach Else and then jump to the End If statement.
The statements between Else and End If are ignored.
Finally, a message box displays “x is” and the current value of x, which is 700.
Let’s see what will happen if costpizza is assigned the value 9 instead of 11?
When we run this program, two message boxes will appear.
The first message box states: “Buy the pizza”
The second message box states: “x is 22”
As before, we create two Double variables named costpizza and x.
Now costpizza is assigned the value 9.
The test condition costpizza > 10 is evaluated.
Is 9 > 10?
This is False, so we skip the statements between If and Else, and only execute the statements between Else and End If.
A message box displays: “Buy the pizza” and x is assigned the value 22.
The If-Then-Else structure ends with the End If statement and a message box displays the current value of x, which is 22.
Notice how the use of indentation inside the If structure allows the user to quickly figure out which statements will be executed if the test
condition is True, and which statements will be executed if the test condition is False.