a labour work in a factory if he works 40 hours he will pay 1000 for one hour, if he works more than one hour he will pay 1500 for above hours. How we do it without using if else condition in C++.
conditional program without if else
Collapse
X
-
Tags: None
-
You have to use an if-else. Now you can disguise this by using code that doesn't explicitly have "if else" in it. Look up the ternary operator:
x is what you are testing for. If x is true then a. If x is false then b.Code:(x) ? a : b;
So you could say:
Then if the hours are greater than 1, the pay rate is 1500. Otherwise the pay rate is 1000.Code:(hours > 1) ? 1500, 1000;
This is still if-else. The ternary operator is obsolete except in classroom problems like this one. It comes from the belief that the less code you write, the compiler will generate fewer instructions. This was OK back in the days of very tiny computers. With todays gigabyte world you never use this. -
You can rephrase the problem as:- Base pay is 1000 for each hour worked.
- Bonus pay is additional 500 (1500-1000) for each bonus hour (above 40) worked.
You are given total_hours.
You can compute bonus_hours with only one if (no else) to trap negative bonus_hours.
You can compute total_pay from these hours without any if statements.Comment
Comment