דילוג לתוכן המרכזי
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 ניסיונות