Friday, March 29, 2024 12:21

Table of contents >> Introduction > Conditional (ternary) operator

Conditional (ternary) operator

Conditional operator is a bit harder to explain. It takes an expression which produces a Boolean result in order to determine which of two other expressions will be calculated and have its value returned as a result. Its sign is ?:. Because it uses three operands, it’s called a ternary operator. The ? sign is placed between the first and the second operands, while the : is placed between the second and the third.

The complete syntax of the ?: operator is the following:

In common English, it’s translated as “if operand1 is True, return the value of operand2; if operand1 is False, return operand3”.

As we will see later, conditional operator is similar to an “if…else…” comparison.

Finally, lets give a concrete example of using the conditional operator:

The output will be:

conditional operator

Reviewing the aftermath, what we did is, we declared two integers, x and y, with the values of 3, respectively 9. Then, we used the conditional operator to check if x is greater than y, and output some text if it’s True, and some other text if it’s False.

You can also combine this operator with assignment. For instance:

So, in the above example, first, the compiler checks if x is greater than y. If it is, it returns x, if not, returns y. The returned value is then assigned to the integer z.

The concepts explained in this lesson are also shown visually as part of the following video:

 

EXERCISES
1. Write an expression that checks for a given integer if its third digit (right to left) is 7.

Solution


Guidelines: Divide the number by 100 and save it in a new variable, which then divide by 10 and take the remainder. The remainder of the division by 10 is the third digit of the original number. Check if it is equal to 7.

2. You are given number n and position p. Write a sequence of operations that prints the value of the bit on the position p in the number (0 or 1). Example: n=35, p=5 -> 1. Another example: n=35, p=6 -> 0.

Solution


Guidelines: Use bitwise operations and display using conditional operator.

Tags: , ,

Leave a Reply



Follow the white rabbit