मुख्य सामग्री पर जाएं
eLearner.app
मॉड्यूल 2 · पाठ 1 का 3पाठ्यक्रम में 4/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 प्रयासों के बाद समाधान उपलब्ध है