Skip to main content
eLearner.app
Module 2 · Lesson 1 of 34/18 in the course~10 min
Module lessons (1/3)

Conditional statements (if-else)

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

Exercise#cpp.m2.l1.e1
Attempts: 0Loading…

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

Loading editor…
Show hint

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

Solution available after 3 attempts

Exercise#cpp.m2.l1.e2
Attempts: 0Loading…

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

Loading editor…
Show hint

Usa l'operatore di confronto `==`e leggi entrambe le variabili:`std::cin >> a >> b;`.

Solution available after 3 attempts