ITCS 103 | Programming Fundamentals | Lab 6
More on Decision Making in C++
المزيد عن اتخاذ القرارات في سي بلس بلس
Ternary Operator ? : switch Statement if/else vs switch Boiling Points · Wavelength

Bilingual Lab Booklet | Full Color Code (VS Code Theme)

✔️ Complete Solutions + Extra Practice
🎯 Objectives:
✓ 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
❓ 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؟
switchif-else-if
Discrete integer/char valuesRanges, floating-point, complex conditions
Faster for many constant casesSlower if many cascading conditions
Cannot use relational operators (>, <, &&)Can use any logical/relational expression
🔢 Ex1: Even/Odd (ternary)تمرين 1: زوجي/فردي باستخدام المعامل الثلاثي
#include <iostream>
using namespace std;

int main() {
    int N;
    cout << "Enter integer: ";
    cin >> N;
    (N % 2 == 0) ? cout << N << " is even\n" : cout << N << " is odd\n";
    return 0;
}
📐 Ex2: Piecewise function y = x+1 if x>0 else x²+2x+10تمرين 2: دالة قطعية باستخدام المعامل الثلاثي
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    double x, y;
    cout << "Enter x: ";
    cin >> x;
    y = (x > 0) ? (x + 1) : (pow(x,2) + 2*x + 10);
    cout << "y = " << y << endl;
    return 0;
}
🔄 Ex3: Convert if/else-if to switch (choice 1-3)تمرين 3: تحويل if/else-if إلى switch
#include <iostream>
using namespace std;

int main() {
    int choice;
    cout << "Enter choice (1-3): ";
    cin >> choice;
    switch(choice) {
        case 1: cout << "You have chosen one\n"; break;
        case 2: cout << "You have chosen two\n"; break;
        case 3: cout << "You have chosen three\n"; break;
        default: cout << "Invalid choice\n";
    }
    return 0;
}
⚠️ Ex4: Can we convert pH (double) to switch?تمرين 4: هل يمكن تحويل pH (double) إلى switch؟
❌ No! switch works only with integral types. pH uses double and range comparisons → keep if-else-if.
#include <iostream>
using namespace std;
int main() {
    double pH;
    cout << "Enter pH: "; cin >> pH;
    if (pH < 3) cout << "very acidic";
    else if (pH >= 3 && pH < 7) cout << "acidic";
    else cout << "alkaline";
    return 0;
}
✅ Ex5: Pass/Fail using ternaryتمرين 5: نجاح/رسوب باستخدام المعامل الثلاثي
int grade;
cin >> grade;
(grade >= 60) ? cout << "You passed\n" : cout << "You failed\n";
🌡️ Boiling Points (5% tolerance)درجات الغليان مع هامش 5%
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    double bp;
    cout << "Enter boiling point (°C): ";
    cin >> bp;
    if (abs(bp - 100) <= 100*0.05) cout << "Water";
    else if (abs(bp - 357) <= 357*0.05) cout << "Mercury";
    else if (abs(bp - 1187) <= 1187*0.05) cout << "Copper";
    else if (abs(bp - 2193) <= 2193*0.05) cout << "Silver";
    else if (abs(bp - 2660) <= 2660*0.05) cout << "Gold";
    else cout << "Substance unknown";
    return 0;
}
🧮 Extra 1: Math Tutor (ternary + loop 3x)مدرس رياضيات باستخدام المعامل الثلاثي وحلقة
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    srand(time(0));
    char ans;
    cout << "You want to multiply? (Y/N): ";
    cin >> ans;
    if(ans == 'Y' || ans == 'y') {
        for(int i = 0; i < 3; i++) {
            int a = rand() % 10 + 1;
            int b = rand() % 10 + 1;
            int userRes, correct = a * b;
            cout << "Generated: " << a << " and " << b << "\n";
            cout << a << " x " << b << " ? ";
            cin >> userRes;
            (userRes == correct) ? cout << "Great! Correct answer\n" :
                                   cout << "Wrong answer. Correct is " << correct << "\n";
        }
        cout << "Bye\n";
    }
    return 0;
}
💡 Extra 2: Lumens using switchاللمعان باستخدام switch
#include <iostream>
using namespace std;

int main() {
    int watts, lumens;
    cout << "Enter wattage: ";
    cin >> watts;
    switch(watts) {
        case 15: lumens = 125; break;
        case 25: lumens = 215; break;
        case 40: lumens = 500; break;
        case 60: lumens = 880; break;
        case 75: lumens = 1000; break;
        case 100: lumens = 1675; break;
        default: lumens = -1;
    }
    if(lumens == -1) cout << "Wattage not in table.\n";
    else cout << "Brightness: " << lumens << " lumens\n";
    return 0;
}
🌈 Extra 3: Wavelength to Visible Colorالطول الموجي إلى اللون المرئي
#include <iostream>
using namespace std;

int main() {
    int wavelength;
    cout << "Enter wavelength (nm): ";
    cin >> wavelength;
    if (wavelength < 400 || wavelength > 700)
        cout << "Wavelength outside visual range\n";
    else if (wavelength <= 424) cout << "Violet\n";
    else if (wavelength <= 491) cout << "Blue\n";
    else if (wavelength <= 575) cout << "Green\n";
    else if (wavelength <= 585) cout << "Yellow\n";
    else if (wavelength <= 647) cout << "Orange\n";
    else cout << "Red\n";
    return 0;
}
📌 Boundary rule: 424 nm classified as Violet (lower-wavelength color).
📌 Key Takeaways – Don't Forget!📌 نقاط مهمة تذكرها
  • ✔ Ternary operator (?:) is a compact if-else replacement, but avoid nesting for readability.
  • ✔ switch statement works only with integral types (int, char, enum) – not double or ranges.
  • ✔ Always include break in each case to prevent fall-through (unless intentional).
  • ✔ default case handles unexpected values – highly recommended.
  • ✔ Use if-else-if for floating-point conditions, ranges, or complex logical expressions.
  • ✔ Convert if-else-if to switch when checking equality against many discrete constants.
  • ✔ 5% tolerance problems: use abs(observed - expected) <= expected * 0.05.
  • ✔ Wavelength boundary rule: classify boundary as lower-wavelength color.
💡 Final Advice: Ternary operator is great for simple assignments; switch is perfect for menu-driven programs. Always validate user input.
⭐ Summary: Ternary operator simplifies short if-else. Switch provides efficient multi-way branching for discrete values. Choose the right tool: ternary for expressions, switch for constant integral cases, if-else-if for complex conditions.
⭐ الخلاصة: المعامل الثلاثي يبسط if-else القصير. Switch يوفر تفرعاً فعالاً للقيم المتقطعة. اختر الأداة المناسبة: ternary للتعابير، switch للحالات الثابتة، if-else-if للشروط المعقدة.
📖 Common Mistakes to Avoid⚠️ أخطاء شائعة تجنبها
  • Forgetting break in switch → causes fall-through (executes next cases).
  • Using switch with floating-point or range conditions (compiler error).
  • Over-nesting ternary operators → reduces readability.
  • Not handling default case in switch → missing invalid inputs.
  • Misunderstanding tolerance: 5% of boiling point = expected * 0.05, not 5 degrees.
✅ All lab exercises + extra practice fully solved & explained.