if - else Statements
if - else Statements
Understanding if - else
Statements
What are if - else
Statements?
if - else
statements are used in programming to perform different actions depending on certain conditions.- These conditions are commonly formed using Boolean expressions, which evaluate to either
true
orfalse
.
Using if - else
Statements
- An
if
statement 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
if
block is skipped. - We can add an
else
clause after theif
statement. This contains a block of code that is executed if theif
condition is false. if (condition) {code1} else {code2}
-code1
is executed if the condition istrue
andcode2
is executed if the condition isfalse
.
Multiple if - else if - else
Statements
- You can chain
if - else
statements together to check multiple conditions. - The
else if
keyword allows for additional conditions to be tested in sequence. if (condition1) {code1} else if (condition2) {code2} else {code3}
-code1
is executed ifcondition1
istrue
,code2
is executed ifcondition1
isfalse
andcondition2
istrue
, andcode3
is executed if bothcondition1
andcondition2
arefalse
.- 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 - else
statements are those where anif - else
statement is present inside anotherif - else
statement. - This allows for more complex conditions to be evaluated.
- However, care should be taken when using nested
if - else
statements 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
true
orfalse
. - It is often used as the condition in an
if - else
statement.
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}
-code
is executed if bothcondition1
andcondition2
aretrue
. - 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 (
true
orfalse
), so they are often used in the condition forif - else
statements.