<p>Okay… so this is programming in C.</p>
<p>Can someone tell me how to use a switch statement for a range of numbers? Like have a user enter some number and then have something printed depending on what number is entered. ie… for number 2-9 print x, for numbers 10-15 print y. I cannot simply use a ton of cases - I have to use the ranges… I didn’t think you could do ranges with switch statements but you must be able to if it is required in my program.</p>
<p>Thanks!</p>
Blobof
March 2, 2006, 2:32pm
2
<p>Something along the lines of (sorry but I only do pseudo code):</p>
<p>case ((x>2) && (x<=9)): print ("foo
"); break;
case ((x>9)): print("bar
"); break;</p>
<p>That would make sense but it won’t work…
I had tried that already. Maybe I’m just doing something wrong… let me go try again.</p>
Gleech
March 2, 2006, 3:09pm
4
<p>yeah, do </p>
<p>if (x>11) and (x<=15)
cout<<“x”;
else if (x>15) and (x<=21)
cout<<“r”;
else
cout<<“r”;</p>
<p>i think that’s proper C, i haven’t coded at all in a long time, and haven’'t coded in C in even longer.</p>
<p>edit: ooh, you need a switch statement… forget it then.</p>
<p>switch (x)
{
case ((x>2)&&(x<=9)):
etc</p>
<p>gleech… that’d be simple enough but I MUST use the switch to do it. </p>
<p>Thanks.</p>
<p>I get this error: “non-constant case expression”</p>
<p>when I do:</p>
<p>switch (x)
{
case ((x>2)&&(x<=9)):</p>
<p>I have my x declared as an integer… what do I do?</p>
<p>I don’t think case statements in C can be boolean logic expressions.</p>
<p>… thats what I said in my original topic. </p>
<p>Heres the deal: I have four different number ranges and have to use ONLY four cases in a switch statement to determine what to print.</p>
Blobof
March 3, 2006, 11:02am
10
<p>Oh yeah, silly me. First do something like</p>
<p>int foo(x) {
if ((x>2)&&(x<=9) return(1);
else return(2)
}</p>
<p>y=foo(x)</p>
<p>switch(y)…</p>
<p>or alternatively this works too but doesn’t fit the requirements</p>
<p>switch (x)
case 2:
case 3:
…
case 9: printf(“foo”);break;</p>
<p>I’ve never been a fan of the switch…</p>
<p>hmmm… none of those fit the requirements. Thanks for the thoughts! I will have to keep thinking about this one…</p>