🎯 Objectives:
✓ Learn & use ternary operator (? :)
✓ Learn & use switch statement
✓ Convert if/else-if to switch
✓ Differentiate when to use switch vs if/else-if
✓ Learn & use ternary operator (? :)
✓ Learn & use switch statement
✓ Convert if/else-if to switch
✓ Differentiate when to use switch vs if/else-if
🎯 أهداف التعلم:
✓ تعلم واستخدام المعامل الثلاثي
✓ تعلم واستخدام جملة switch
✓ التحويل من if/else-if إلى switch
✓ التمييز بين استخدام switch و if/else-if
✓ تعلم واستخدام المعامل الثلاثي
✓ تعلم واستخدام جملة switch
✓ التحويل من if/else-if إلى switch
✓ التمييز بين استخدام switch و if/else-if
❓ Ternary Operator (Conditional Operator)❓ المعامل الثلاثي
variable = (condition) ? value_if_true : value_if_false; // OR: condition ? statement1 : statement2;
📌 Syntax: condition ? expression1 : expression2; → If condition true, expression1 evaluated; else expression2. Shorter form of if-else.
🔁 switch Statement🔁 جملة switch
switch(expression) { case constant1: statements; break; case constant2: statements; break; default: statements; }
✔ Works with integral types (int, char, enum). Each case must be unique. break prevents fall-through. default handles unmatched values.
⚖️ When to use switch vs if-else-if?متى تستخدم switch ومتى if-else-if؟
| switch | if-else-if |
|---|---|
| Discrete integer/char values | Ranges, floating-point, complex conditions |
| Faster for many constant cases | Slower if many cascading conditions |
| Cannot use relational operators (>, <, &&) | Can use any logical/relational expression |