Consider that a program is required to be able to handle multiple situations based upon the input that is given. For example, we get an input that is an integer and if the number is less than 50 we want to handle it one way, and if it is greater than 50 we want to handle it in another way. We don't want the integer given to run through all options of the program being made. With that in mind, an if statement is used to determine what methods should be used.
When utilizing an if statement, most programming languages will often have it so that if is first declared, then the statement that is being compared afterwards is shown. For example, when x is an integer we can do the following to check if it is under 50:
Now, based upon what x is, this statement will give one of two responses. If x is less than 50, then the statement will be true, and as a result x will be multiplied by 2 in the area best known as the then statement. If x is 50 or greater, then the statement will be false and nothing will be done with x. Also note that I use brackets for the task to be performed should the if statement be true. This should always be done even if it is only one line as most coding conventions state as the correct implementation. However, there may be times where multiple possibilities must be accounted for, this is where the else and else if statements come in. For example, in a program where we want to handle x when it's greater than 50 in addition to handling it when it's less than 50 the following would be done:
In the statement given, else is used when the if statement is false. There are also cases where else if has to be used to handle multiple situations. For example, say we want to handle numbers less than 50 one way, numbers between 50 to 100 another way, and numbers greater than 100 in yet another way. For that we would utilize the following:
For this example, you will notice that for the else if statement, I used two logic statements and connected them together. The first one checks to see if x is greater than 50, the second checks to see if x is less than 100. The two ampersand signs (&&) used to connect them is also known as the "AND operator" and requires that in order for the full statement to be true, both parts of the statement must be true. There is also an "OR operator" (This uses "||" in most programming languages) which essentially states that if only one part of a statement is true, then regardless of what the other part is, the entire statement is true. This is another way to define how a program handles different types of input.
Note: All of my Programming Concepts tutorials will be getting placed in the tutorials section of this site. The blog version of these tutorials will remain though.