. Conditional or Ternary Operator
The conditional operator consists of 2 symbols the question mark (?) and the colon (:)The syntax for a ternary operator is as follows .
exp1 ? exp2 : exp3
The ternary operator works as follows
exp1 is evaluated first. If the expression is true then exp2 is evaluated & its value becomes the value of the expression. If exp1 is false, exp3 is evaluated and its value becomes the value of the expression. Note that only one of the expression is evaluated.
For example
a = 10;
b = 15;
x = (a > b) ? a : b
Here x will be assigned to the value of b. The condition follows that the expression is false therefore b is assigned to x.
.
/* Example : to find the maximum value using conditional operator) #include void main() //start of the program { int i,j,larger; //declaration of variables printf (“Input 2 integers : ”); //ask the user to input 2 numbers scanf(“%d %d”,&i, &j); //take the number from standard input and store it larger = i > j ? i : j; //evaluation using ternary operator printf(“The largest of two numbers is %d \n”, larger); // print the largest number } // end of the program . |
Output
The largest of two numbers is 45
No comments:
Post a Comment