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 {}:
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
0or the pointernullptrare consideredfalse. - Any value other than
0(positive or negative) is consideredtrue.
int activeUsers = 5;
if (activeUsers) {
// This block runs because activeUsers is not 0 (true)
}
Try it yourself
Given an integer number read from std::cin, if the number is greater than 0 print 'positivo', otherwise print 'negativo o zero'.
Show hint
Usa la struttura `if (number > 0) { ... } else { ... }`.
Solution available after 3 attempts
Read two integers a and b from std::cin. If a is equal to b print 'uguali', otherwise print 'diversi'.
Show hint
Usa l'operatore di confronto `==`e leggi entrambe le variabili:`std::cin >> a >> b;`.
Solution available after 3 attempts