The If…Then structure is a conditional statement, or sometimes referred to as a decision structure. It is used to perform a section of code if and only if the condition is true. The condition is checked by using a Boolean statement. If the condition is not true (meaning false), then the section of code is not performed it is just passed over. The form of an If…Then statement is:
The indentation (usually 4 spaces, NOT A TAB) used in the If…Then statement is a coding convention used in almost every language. It is there to make the statement easier to read. It has no effect on how the code works and could be ignored; however, it is REALLY BAD programming style not to have it. You will also notice that some programming languages like to place the Boolean expression in brackets, while others do not. It is just style, but you should follow the language’s style.
Here is a problem that can be solved using an If…Then statement. I have a class that can only hold 30 students because that is how many chairs I have. As the user to enter a number of students and tell me if I have too many students for chairs.
You top-down design will have a decision logic in it. You do not use a diamond in a top-down design, you still only use rectangles. Here is what a top-down design might look like for this problem:
Remember from the section on flowcharts, the diamond shape represented decisions. The If…Then statement is the translation of a decision in a flowchart to code. The above examples would look like the following in a flowchart:
You will also be using If…Then statements in pseudo-code. The above problem looks like this in pseudo-code. Note that you do indent when you are inside an If…Then statement in pseudo-code. Also note that “IF”, “THEN” and “ENDIF” are all bold and caps:
In the code examples below, if the variable numberOfStudents (or number_of_students) happens to be a number that is greater than 30 (say 32), the next line of code is performed (print(“Too many Students!”)). If the variable is not greater than 30 (say it is exactly 30), then the next line of code is skipped over and NOT performed.