Hello there, so basically im trying to do a small program that let the user enter a value then if the value equal or greater than x make discount something like 12%
here is an example
1 2 3 4
15% discount, if sales are greater than or equal to 1000
10% discount, if sales are greater than or equal to 500
5% discount, if sales are greater than or equal to 250
0, otherwise.
i know how to do it using if statement, but in switch i have no idea, there could be million cases about the entered value, so i need help if its possible
switch expects an exact number to compare like ==, so you cannot use it for values >=.
Why do you want to use switch?
It is limited in its use but might be a little bit faster than the according if(...) else if(...) ... cascade. But the gain is not overwhelming. So it's not worth any 'acrobatics' just for having switch.
is this a cheesy example or your actual problem? It looks like percent can be directly computed here with some math equation, but if this problem is just a quick example, that may not help.
regardless, you can chain ifs or convert it to a small set of cases.
eg if you can process sales into a number 0,1,2,3 or 1,2,3,4 etc with a simple equation you can use switch or lookup table.
the brute force way is
pct = 0;
pct += (sales>=1000)*15+ (sales >=500 && sales <1000)*10 + ....
this exploits the fact that comparisons become 0 or 1.
Given the current situation, it's a rather tacky question, with a not-very-good strategy for solving. I should go back to your lecturer and ask whether "switch" was intended as the actual c++ statement of that name or as a somewhat misleading indication of a choice of options (if ... else if ... else, or, with more generality, looping through parallel arrays).
It makes no sense to use a c++ switch statement here. That is for a small number of discrete options.
int swkey = sales /250; //0-250 gives 0. 250-499 gives 1. 500-749 gives 2. 750-999 gives 3. 1000+ gives 4,5,6.... forever.
swkey = min(4, swkey); // it can't be bigger than 4.
switch (swkey)
{
case 4:
code;
break;
case 3: //do you understand what this does?
case 2:
code
break;
case 1:
code;
break;
default:
code;
}
OR, you can default it to the 1000+ case and have zero be a case too. then you would not need to force the key to be 4 or less. Why not try it that way for fun?
Remember: this works because the question has nice, easy to work with numbers. If the cutoffs were not easily related, its a chore to force fit a switch here.
#include <iostream>
usingnamespace std;
int main()
{
int trigger[] = { 250, 500, 1000 };
int value [] = { 5, 10, 15 };
int N = sizeof value / sizeof value[0];
int sales;
cout << "Enter sales: "; cin >> sales;
int discount = 0;
for ( int i = 0; i < N && sales >= trigger[i]; i++ ) discount = value[i];
cout << "Discount is " << discount << "%\n";
}