Conditional Operators

Conditional Operator is another way of writing the if-else statement. It helps to simplifies the if-else statement and is compact . However, the conditional operator can only be used if there are 2 options which are either true or false. The format to code the conditional operators is shown below:

Condition ? expression1: expression2;

Example
marks > 50 ? “You passed the paper”: “You failed the paper”;

Condition – The conditions will give a Boolean expression
Expression1 – if the conditional is true, then expression1 will be executed.
Expression2 – if the conditional is false, then expression2 will be executed.
Expression1 and Expression2 must have the same data type.

The code snippet below shows how the conditional operator have been coded out:

conditionalStatements
Program with Conditional Statement

Leave a comment