C++ 'and' Keyword with Example

C++ | 'and' keyword: Here, we are going to learn about the 'and' keyword which is an alternative to Logical AND operator.
Submitted by IncludeHelp, on May 16, 2020

"and" is an inbuilt keyword that has been around since at least C++98. It is an alternative to && (Logical AND) operator and it mostly uses with the conditions.

The and keyword returns 1 if the result of all operands is 1, and it returns 0 if the result of any condition is 0.

Syntax:

    operand_1 and operand_2;

Here, operand_1 and operand_2 are the operands.

Example:

    Input:
    a = 10;
    b = 20;
    
    result = (a==10 and b==20);

    Output:
    result = 1

C++ example to demonstrate the use of "and" keyword

Example 1:

// C++ example to demonstrate the use of 
// 'and' operator.

#include <iostream>
using namespace std;

int main()
{
    int num = 20;

    if (num >= 10 and num <= 50)
        cout << "true\n";
    else
        cout << "false\n";

    if (num >= 20 and num <= 50)
        cout << "true\n";
    else
        cout << "false\n";

    if (num > 50 and num <= 100)
        cout << "true\n";
    else
        cout << "false\n";

    return 0;
}

Output:

true
true
false

Example 2:

// Input name, age, height and weight
// check you are eligible for the 
// army selection or not?

#include <iostream>
using namespace std;

int main()
{

    string name;
    int age;
    float height, weight;

    cout << "Enter name: ";
    cin >> name;

    cout << "Enter age: ";
    cin >> age;

    cout << "Enter height (in cm): ";
    cin >> height;

    cout << "Enter weight (in kg): ";
    cin >> weight;

    if (age >= 18 and height >= 165 and weight >= 55)
        cout << name << " , you're selected.";
    else
        cout << name << " , you're not selected.";

    return 0;
}

Output:

RUN 1:
Enter name: Shivang
Enter age: 23
Enter height (in cm): 172
Enter weight (in kg): 67
Shivang , you're selected.

RUN 2:
Enter name: Akash
Enter age: 19
Enter height (in cm): 157
Enter weight (in kg): 70
Akash , you're not selected.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.