2.3 if Statements

0 阅读1分钟

1. Exam Points

  • if (only if)
  • if...else
  • if...else-if...else
  • Note:
    • First check what a question asks (x or y, correct(√) or not correct(X)).
    • if an if or else block contains multiple statements, enclose them with {}
    • multiple if statements will be executed one after another.
    • in the if-else if statement, only one block will be executed (first match).

2. Knowledge Points

(1) if Statements

  • Selection statements change the sequential execution of statements.
  • An if statement is a type of selection statement.
  • Different code segments will be executed based on the value of a Boolean expression.
  • Types of if statements:
    • One way selection (if)
      image.png
      • Multiple if statements will be executed one after another.
        image.png
    • two-way selection (if-else)
      image.png
    • multiway selection (if...else if...ese)
      image.png
      • Only one block will be executed.
      • Rule: execute the first matched block.
      • Multiple else-if(optional) blocks are allowed
      • You may add an else(optional) block in the end or not.
  • A special case
    • In a multiway selection, if the first few conditions cover all the cases, then the remaining conditions are of no use.
    • Example:
      image.png
      • In this example, score >= 90 and score < 90 cover all the cases, so the remaining two conditions will never be executed.

3. Exercises