Nested If Statements: Comprehensive Notes

Nested If Statements

  • Nested if statements involve placing one if statement inside another.
  • They can be nested as deeply as required.
  • The syntax is similar to regular if statements, but within another if statement's code block.

Example: Weather Description

  • Problem: The Bureau of Meteorology wants a detailed weather description based on temperature and wind conditions.
  • Approach: Use a two-dimensional matrix with temperature on one axis and wind conditions on the other.
  • This combines temperature (warm/cold) and wind (windy/calm) to provide a detailed description.
Code Breakdown:
  1. Setting the Data:
    • Set today's temperature; threshold changed to 20 degrees.
    • Variable name changed.
  2. Checking Wind Conditions:
    • Asks the user if it is windy.
    • Reads the user's response.
    • Converts the input to a boolean (true or false).
    • The user must enter "true" or "false"; otherwise, a runtime error occurs.
Nested If Statement
  • The first if statement checks the temperature.
  • If the first statement is true, the nested if statement checks if it is windy.
  • If the first statement is false, the nested if statement still checks if it is windy.
  • Each nested if statement outputs a statement corresponding to the combined conditions (temperature and wind).
  • No operator is needed for the wind variable because it's already a boolean.

Testing Nested If Statements

  • Test cases should cover multiple conditions.
  • Change only one value per test to easily identify issues.
  • Test boundary cases for numeric values.

Nested If vs. Else If Statements

  • Both allow a program to follow multiple paths.
  • Deciding when to use each depends on:
    • Number of conditions
    • Likelihood of errors
    • Readability
Rewriting Nested If as Else If
  • Nested if statements can be rewritten using else if statements and boolean operators.
  • Example:
    if (temperature > 20 && isWindy) { ... } else if (temperature > 20 && !isWindy) { ... }
  • The temperature comparison often requires parentheses, while the wind comparison might not.
Rewriting Else If as Nested If
  • Code originally written as if-else if can be rewritten as nested if statements.
  • This can become very confusing, especially if the nesting is unnecessary.
  • Excessive use of nested if statements can reduce readability.
  • If all pathways depend on a single condition (e.g., temperature), an if-else if structure is more suitable.

Summary

  • Nested if statements are useful when multiple conditions need to be considered.
  • Well-written nested if statements produce clear and understandable code.
  • Poorly written nested if statements can be difficult to read.
  • Avoid nested if statements when only one condition needs to be checked; use an if-else statement instead.