Conditional Operators
Using if, else, and else if statements
Conditional Operators
Now we know how to input numbers and are familiar with several arithmetic operations. Today we will look at something different: conditional operators.
Conditional operators allow you to perform different actions depending on conditions. They are used when you need to execute code only in certain situations.
The if Operator
The if operator is used to execute code if a specified condition is true. Here is its general syntax:
For example, if we have a variable a, and we want to check if it is greater than 100:
If the value of variable a is greater than 100, then "Greater than 100" will be displayed.
The else if Operator
The else if operator allows you to execute code if the previous condition is false, but the current condition is true. This is useful when you have multiple conditions to check.
Example of using else if:
If the value of variable a is less than 100, "Less than 100" will be displayed.
The else if operator can only be used as a subsequent check after the if operator, meaning in the hierarchy of checks there should always be an if first followed by several else ifs.
The else Operator
The else operator is executed if all previous conditions are false. It allows you to handle all other cases and does not require checking any additional condition.
Example of using else:
If the value of variable a is neither greater nor less than 100, "Equal to 100" will be displayed.
The else operator can be used either after the if operator or after the else if operator, but in the hierarchy it should always be last.
Logical Operators and and or
Now let's look at two other operations called logical operators and and or. These operators can be used inside our conditional if operator.
The and Operator - &&
The and operator allows you to check if both conditions are met simultaneously. Here's an example:
In this example, we check if the value of variable a is even (a % 2 == 0) and if it is greater than 100 (a > 100). If both conditions are true, then the code inside if is executed. The and operator simplifies performing such checks where both conditions need to be met.