Chuyển đến nội dung chính
eLearner.app
Mô-đun 2 · Bài học 1 trong tổng số 34/18 trong khóa học~10 min
Bài học theo mô-đun (1/3)

Câu lệnh có điều kiện (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

tập thể dục#cpp.m2.l1.e1
Nỗ lực: 0Đang tải…

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

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

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

Giải pháp khả dụng sau 3 lần thử

tập thể dục#cpp.m2.l1.e2
Nỗ lực: 0Đang tải…

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

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

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

Giải pháp khả dụng sau 3 lần thử