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 or false.

Using if - else Statements

  • An if statement begins with the keyword if, 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 the if statement. This contains a block of code that is executed if the if condition is false.
  • if (condition) {code1} else {code2} - code1 is executed if the condition is true and code2 is executed if the condition is false.

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 if condition1 is true, code2 is executed if condition1 is false and condition2 is true, and code3 is executed if both condition1 and condition2 are false.
  • 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 an if - else statement is present inside another if - 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 or false.
  • 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 both condition1 and condition2 are true.
  • 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 or false), so they are often used in the condition for if - else statements.