Describe the functions of the following operators:

  • Relational Operators

Relational operators are used to compare two values and return a boolean result (true or false). These operators compare the values based on the relationship between them.

Here are the most common relational operators:

  • ==: Equality operator. Returns true if both operands are equal.

    a == b // returns true if a equals b
  • !=: Not equal operator. Returns true if both operands are not equal.

    a != b // returns true if a is not equal to b
  • >: Greater than operator. Returns true if the left operand is greater than the right operand.

    a > b // returns true if a is greater than b
  • <: Less than operator. Returns true if the left operand is less than the right operand.

    a < b // returns true if a is less than b
  • >=: Greater than or equal to operator. Returns true if the left operand is greater than or equal to the right operand.

    a >= b // returns true if a is greater than or equal to b
  • <=: Less than or equal to operator. Returns true if the left operand is less than or equal to the right operand.

    a <= b // returns true if a is less than or equal to b
  • Logical Operators

Logical operators are used to perform logical operations on boolean values and return boolean results. They are mainly used in control flow and conditional statements.

  • &&: Logical AND operator. Returns true if both operands are true.

    if (a > 0 && b > 0) { // evaluates to true if both a and b are positive
  • ||: Logical OR operator. Returns true if at least one operand is true.

    if (a > 0 || b > 0) { // evaluates to true if either a or b is positive
  • !: Logical NOT operator. Reverses the boolean value of the operand.

    if (!(a > 0)) { // evaluates to true if a is not greater than 0
  • Conditional Operator

The conditional operator, also known as the ternary operator, is a shorthand for an if-else statement. It evaluates a condition and returns one value if the condition is true and another value if the condition is false.

The syntax for the conditional operator is:

condition ? expression_if_true : expression_if_false;

For example:

int a = (x > y) ? 5 : 10; // if x is greater than y, a is set to 5, otherwise to 10