الانتقال إلى المحتوى الرئيسي
eLearner.app
الوحدة 2 · الدرس 1 من 34/18 في الدورة~10 min
دروس الوحدة (1/3)

العبارات الشرطية (إذا-إلا)

Conditional statements allow executing different blocks of code based on whether certain conditions are met.

In C++, the fundamental construct is if, optionally followed by else if and else.

The if-else Structure

The basic syntax requires enclosing the condition in parentheses () and the block of code in curly braces {}:

Code
int temperature = 25;

if (temperature > 30) {
    std::cout << "It's very hot!" << std::endl;
} else if (temperature >= 20) {
    std::cout << "The temperature is pleasant." << std::endl;
} else {
    std::cout << "It's cold." << std::endl;
}

Valid Conditional Expressions

Any expression that returns a value convertible to boolean can be used as a condition:

  • In C++, the value 0 or the pointer nullptr are considered false.
  • Any value other than 0 (positive or negative) is considered true.
Code
int activeUsers = 5;
if (activeUsers) {
    // This block runs because activeUsers is not 0 (true)
}

Try it yourself

تمرين#cpp.m2.l1.e1
المحاولات: 0جارٍ التحميل…

Given an integer number read from std::cin, if the number is greater than 0 print 'positivo', otherwise print 'negativo o zero'.

جارٍ تحميل المحرر…
إظهار التلميح

Usa la struttura `if (number > 0) { ... } else { ... }`.

الحل متاح بعد 3 من المحاولات

تمرين#cpp.m2.l1.e2
المحاولات: 0جارٍ التحميل…

Read two integers a and b from std::cin. If a is equal to b print 'uguali', otherwise print 'diversi'.

جارٍ تحميل المحرر…
إظهار التلميح

Use the comparison operator `==`and read both variables:`std::cin >> a >> b;`.

الحل متاح بعد 3 من المحاولات