C++: If, Else If, Else
If, Else If, Else
Reference page for this video tutorial: Branch Statements.
In this C++ tutorial, we cover the use of if statements. An if statement is a type of conditional statement, since it selects portions of code to be executed based on certain conditions.
Simple if statements designate a piece of code that is only executed only when a condition is true. Using a simple if, we can designate, for example, that an auto insurance premium should increase if the policyholder had an accident recently.
In this example, the insurance premium only increases if there was an accident. Otherwise, nothing happens and the payment remains the same.
We can add a second alternate to the main branch, where the two branches cover all cases. In this case, we add an else statement. Building on the insurance premium, we would want to decrease the premium if the policyholder was accident-free.
In this example, the policyholder is rewarded for good behavioras we would expect.
Suppose that we need more than two branches. We can handle that case with else if statements. For example, if we are determining the price of an automobile based on the type, we might have a program that looks like this:
In this case, we select a price based on whether the vehicle is a pickup truck, sedan, sports car, SUV, or something else. Each vehicle type corresponds to a different branch. The final branch sets the vehicle price to zero, since we did not find a match for the vehicle type.