Age based discount using ternary operator
Solving age based discount problem with ternary (three operands) operator.
Learning Objectives
- Learning the age based discount problem using the ternary operator based condition check.
Source Code
|
Related (?) : |
Run Output
Code Understanding
int age=63;
Here some test value has been stored in integer variable age.
int disc=age >= 60 ? 10 : 5; //The ternary operator conditional syntax
If you study the right hand side there are three parts
age >=60 //Operand 1
10 //operand 2
5 //operand 3
The first part is before the ?. This is the test condition, In this example this would be true.
The second part is between ? and : symbol. In the ternary operator combination like this value is returned when the condition is true. So in this example the int disc will be set equal to 10 (the second part) as the condition checked in the first part is true.
The third part is returned if the first part condition is not true. So in this case this will not execute.
cout<<“The discount rate is “<<disc<<” %”<<endl;
Here the final display as above condition will come for 10%
Notes
- Ternary operators are handy for quick calculations like this, but most programmers prefer if-else constructs. However for quick condition based arithmetic operations they will find use in making complex arithmetic formulas.
Common Errors
- Care is required to build this operator to put right value for true condition and false condition and ultimately these values have to be equated to the right hand side so data type of both sides should be definitely same both for true and false logic.
Suggested Filename(s): age-ter.cpp
sunmitra| Created: 6-Jan-2018 | Updated: 31-Aug-2018|