The if Statement

The if statement is the basic building block of conditions. It's used when we want to execute some code only if a certain condition is met.

Basic syntax:

if (condition) {
    // code that executes when the condition is true
}

In conditions we can use various comparison operators:

  • == equals (note, two equal signs!)
  • != not equal
  • > greater than
  • < less than
  • >= greater than or equal
  • <= less than or equal

Usage examples:

int age = 15;

if (age >= 18) {
    std::cout << "You can drive a car" << std::endl;
}

int points = 85;

if (points > 50) {
    std::cout << "Test passed successfully" << std::endl;
}


// Prints: Test passed successfully

Notice that if the condition is not met, the code inside the block is skipped and the program continues.

Instructions

Write a condition that prints the text "Number is positive" only if the variable number is greater than 0.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

2/10

The if Statement | Start Coder