How to create if statements inside switch statement?
78 views (last 30 days)
I don't know if this is possible, but can you put an if statement inside a switch statement?
I am attempting to write this program: 'Write a script to calculate how much to tip a waiter/waitress based on quality of service. The script file should ask for the amount of the bill and whether the service was good (1), fair (2), or poor (3). If the service was good, the tip should be 15% with a minimum tip of £2. If the service was fair, the tip should be 10% with a minimum of £1. If the tip was poor, the tip should be zero. '
I can use the menu function to bring up the choice of service and then generate the tip value using the switch statement. But I am not sure how to get the tip to always be £2 or greater if service is good and £1 or greater if service is fair.
Also, how do I display "The tip is £'tip value'".. I take it I can't use the display function since I want to display a sentence and a variable?
dpb on 17 Oct 2013
a) sure...any coding construct contained within the switch clause can be part of the clause--
b) You may not actually need the if...end construct anyway. Look at min/max and think of the desired result within the switch block...
c) No reason you can't use disp() but it gets to be simpler for more complex output to use fprintf w/ the desired format since w/ disp() you have to build the string output anyway
disp(['The tip is ' num2str(tip)])
as opposed to
fprintf('The tip is %.2f\n', tip)
Note the \n newline character must be added explicitly w/ fprintf, though...
This looking suspiciously like homework, hints provided, not actual code... :)
More Answers (1)
Yatin on 17 Oct 2013
You can frame 3 different functions for rendering tips (good, fair, poor). Say the function names can be " tipGood ", " tipFair ", " tipPoor ". Then in your switch case based on the option that the user feels for giving the tip, you can call the appropriate function.
Inside the tipGood function you will need to pass the total bill value and calculate 15% of this value and compare this value with 2£ and return the larger of the the two values as a tip from the function. The scenario for the fair tip would also be the same and the tipPoor function would just return 0 as the tip value.