if - else Statements
if - else Statements
Understanding if - else Statements
What are if - else Statements?
if - elsestatements are used in programming to perform different actions depending on certain conditions.- These conditions are commonly formed using Boolean expressions, which evaluate to either
trueorfalse.
Using if - else Statements
- An
ifstatement begins with the keywordif, followed by a Boolean expression in parentheses, and then a block of code in curly braces{}. if (condition) {code}- the code inside the curly braces is executed if the condition is true.- If the condition is false, the code in the
ifblock is skipped. - We can add an
elseclause after theifstatement. This contains a block of code that is executed if theifcondition is false. if (condition) {code1} else {code2}-code1is executed if the condition istrueandcode2is executed if the condition isfalse.
Multiple if - else if - else Statements
- You can chain
if - elsestatements together to check multiple conditions. - The
else ifkeyword allows for additional conditions to be tested in sequence. if (condition1) {code1} else if (condition2) {code2} else {code3}-code1is executed ifcondition1istrue,code2is executed ifcondition1isfalseandcondition2istrue, andcode3is executed if bothcondition1andcondition2arefalse.- Note that as soon as a true condition is found, its associated block of code is executed, and the rest of the conditions are not checked.
Nested if - else Statements
- Nested
if - elsestatements are those where anif - elsestatement is present inside anotherif - elsestatement. - This allows for more complex conditions to be evaluated.
- However, care should be taken when using nested
if - elsestatements as they can easily become difficult to understand and maintain.
Understanding Boolean Expressions
What are Boolean Expressions?
- A Boolean expression is an expression that can be either
trueorfalse. - It is often used as the condition in an
if - elsestatement.
Boolean Operators
- Boolean expressions often involve Boolean operators such as
&&(AND),||(OR), and!(NOT) to combine or invert conditions. - For example,
if (condition1 && condition2) {code}-codeis executed if bothcondition1andcondition2aretrue. - Keep in mind the order of precedence:
!is evaluated first, then&&, and finally||.
Comparison Operators
- Comparison operators such as
==(equal to),!=(not equal to),<(less than),<=(less than or equal to),>(greater than),>=(greater than or equal to) are used to compare values. - These operators return a Boolean value (
trueorfalse), so they are often used in the condition forif - elsestatements.