By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,203 Members | 1,392 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,203 IT Pros & Developers. It's quick & easy.

conditional program without if else

P: 1
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++.
Nov 11 '17 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 5K+
P: 9,197
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:

Expand|Select|Wrap|Line Numbers
  1. (x) ? a : b;
x is what you are testing for. If x is true then a. If x is false then b.

So you could say:

Expand|Select|Wrap|Line Numbers
  1. (hours > 1) ? 1500, 1000;
Then if the hours are greater than 1, the pay rate is 1500. Otherwise the pay rate is 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.
Nov 12 '17 #2

Expert 100+
P: 2,400
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.
Nov 13 '17 #3

Post your reply

Sign in to post your reply or Sign up for a free account.