CodeMIRAI
0 XP

if and else

2 min read 4 runnable examples Quiz included
C++
#include <iostream>
using namespace std;

int main() {
    int temp;
    cin >> temp;

    if (temp >= 35) {
        cout << "Heatwave: stay indoors" << endl;
    } else if (temp >= 25) {
        cout << "Warm day" << endl;
    } else if (temp >= 15) {
        cout << "Pleasant" << endl;
    } else {
        cout << "Bring a jacket" << endl;
    }
    return 0;
}

Combining conditions

OperatorMeaning
&&and
||or
!not
C++
#include <iostream>
using namespace std;

int main() {
    int age = 25;
    bool hasLicence = true;
    bool isBanned = false;

    if (age >= 18 && hasLicence && !isBanned) {
        cout << "You may drive" << endl;
    } else {
        cout << "You may not drive" << endl;
    }
    return 0;
}

The conditional operator

C++
#include <iostream>
using namespace std;

int main() {
    int a = 12, b = 30;
    int larger = (a > b) ? a : b;
    cout << "Larger: " << larger << endl;
    cout << a << " is " << (a % 2 == 0 ? "even" : "odd") << endl;
    return 0;
}

Leap years: nested logic

A year is a leap year if it is divisible by 4, except century years, which must also be divisible by 400:

C++
#include <iostream>
using namespace std;

int main() {
    int year;
    for (int i = 0; i < 4; i++) {
        cin >> year;
        bool leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
        cout << year << (leap ? " is" : " is not") << " a leap year" << endl;
    }
    return 0;
}
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.