← C++ tutorial

C++

Conditionals

if, else if, and else behave the same as in Java or JavaScript.

Example: a time-of-day greeting

#include <iostream>
using namespace std;

int main() {
    int hour = 14;
    string greeting;

    if (hour < 12) {
        greeting = "Good morning";
    } else if (hour < 18) {
        greeting = "Good afternoon";
    } else {
        greeting = "Good evening";
    }

    cout << greeting << endl;
    return 0;
}
Good afternoon

If you've already read the Java tutorial's conditionals lesson, this should look almost identical, that's exactly the point of a shared "C-family" syntax: once you know the pattern in one of these languages, recognizing it in another is mostly about spotting small syntax differences, not relearning the underlying logic from scratch.

Example
#include <iostream>
using namespace std;

int main() {
    int hour = 14;
    string greeting;

    if (hour < 12) {
        greeting = "Good morning";
    } else if (hour < 18) {
        greeting = "Good afternoon";
    } else {
        greeting = "Good evening";
    }

    cout << greeting << endl;
    return 0;
}
Output
Good afternoon
Ready to go further?

These free tutorials are a preview of what a Code Secure Academy cohort covers, project work and all.

Explore our tracks

Cookie preferences

Choose what you're comfortable with. You can change this any time from the footer.

Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account