If Statements

Lesson 16
Author : Afrixi
Last Updated : November, 2022
C++ - Programming Language
This course covers the basics of programming in C++.

In C++, if statements are used to control the flow of a program based on whether a certain condition is true or false. Here’s an example:

#include <iostream>

int main() {
    int x = 5;
    int y = 10;
    
    if (x < y) {
        std::cout << "x is less than y" << std::endl;
    }
    
    return 0;
}

In this example, the if statement checks if x is less than y. If the condition is true, the code inside the if statement is executed, which in this case is printing the string “x is less than y” to the console using std::cout.

if statements can also include an else block that is executed when the condition is false. Here’s an example:

#include <iostream>

int main() {
    int x = 10;
    int y = 5;
    
    if (x < y) {
        std::cout << "x is less than y" << std::endl;
    }
    else {
        std::cout << "x is greater than or equal to y" << std::endl;
    }
    
    return 0;
}

In this example, the if statement checks if x is less than y. If the condition is true, the code inside the if statement is executed. If the condition is false, the code inside the else block is executed, which in this case is printing the string “x is greater than or equal to y” to the console using std::cout.

Multiple conditions can be checked using logical operators such as && (and) and || (or). Here’s an example:

#include <iostream>

int main() {
    int x = 5;
    int y = 10;
    int z = 15;
    
    if (x < y && y < z) {
        std::cout << "x is less than y and y is less than z" << std::endl;
    }
    
    return 0;
}

In this example, the if statement checks if x is less than y and if y is less than z. If both conditions are true, the code inside the if statement is executed, which in this case is printing the string “x is less than y and y is less than z” to the console using std::cout.

You can also chain multiple if and else statements together to create more complex conditional logic:

#include <iostream>

int main() {
    int x = 5;
    
    if (x < 0) {
        std::cout << "x is negative" << std::endl;
    }
    else if (x == 0) {
        std::cout << "x is zero" << std::endl;
    }
    else {
        std::cout << "x is positive" << std::endl;
    }
    
    return 0;
}

In this example, the if statement checks if x is negative. If the condition is true, the code inside the first block is executed, which prints “x is negative” to the console using std::cout. If the condition is false, the else if statement checks if x is equal to 0. If the condition is true, the code inside the second block is executed, which prints “x is zero” to the console. Finally, if both conditions are false, the code inside the else block is executed, which prints “x is positive” to the console.