And Or Statements C++

3 min read Jul 03, 2024
And Or Statements C++

And and Or Statements in C++

In C++, and and or statements are logical operators used to combine conditions and evaluate them as a single boolean value (true or false).

The 'And' Operator (&&)

The and operator (&&) evaluates to true only if both conditions on either side of the operator are true. If any one of the conditions is false, the entire expression evaluates to false.

Syntax:

condition1 && condition2 

Example:

int age = 25;
int salary = 50000;

if (age >= 18 && salary > 40000) {
    cout << "You are eligible for the loan." << endl;
} else {
    cout << "You are not eligible for the loan." << endl;
}

In this example, the if statement will only execute if both conditions age >= 18 and salary > 40000 are true.

The 'Or' Operator (||)

The or operator (||) evaluates to true if at least one of the conditions on either side of the operator is true. The entire expression evaluates to false only if both conditions are false.

Syntax:

condition1 || condition2

Example:

int score = 75;

if (score >= 90 || score < 50) {
    cout << "Your score is either excellent or needs improvement." << endl;
} else {
    cout << "Your score is average." << endl;
}

In this example, the if statement will execute if either score >= 90 or score < 50 is true.

Combining 'And' and 'Or' Operators

You can combine and and or operators in a single expression using parentheses to define the order of evaluation.

Example:

int age = 20;
int height = 170;

if ((age >= 18 && height >= 160) || (age >= 21)) {
    cout << "You meet the requirements." << endl;
} else {
    cout << "You do not meet the requirements." << endl;
}

This example shows that someone can meet the requirements by being both at least 18 years old and 160 cm tall, or by being at least 21 years old.

Conclusion

And and Or statements are fundamental logical operators in C++ that allow you to create complex conditional expressions and control the flow of your programs. Understanding how they work is essential for writing effective and readable code.

Latest Posts


Featured Posts