C
C#3mo ago
Melton

if statements with more than once condition

Hi, I'm struggling a bit with figuring out how to add ranges as conditions in my if/else if statements. Rather than having conditions being above, below, or equal to X, I want to be able to find whether or not a statement fits a very specific condition. How would you proceed with this problem? This is where I get stuck:
c#
int a = 10;
int b = 10;
int c = 10;
int d = 10;

int x = a + b + c + d;

Random random = new Random();
int numberFinder = random.Next(0, x);

string 1 = "The number is 10 or lower";
string 2 = "The number is between 11 and 20";
string 3 = "The number is between 21 and 30";
string 4 = "The number is 31 or higher";

if ( numberFinder <= a )
{
Console.Writeline(1);
}
else if ( numberFinder ????????????????????
c#
int a = 10;
int b = 10;
int c = 10;
int d = 10;

int x = a + b + c + d;

Random random = new Random();
int numberFinder = random.Next(0, x);

string 1 = "The number is 10 or lower";
string 2 = "The number is between 11 and 20";
string 3 = "The number is between 21 and 30";
string 4 = "The number is 31 or higher";

if ( numberFinder <= a )
{
Console.Writeline(1);
}
else if ( numberFinder ????????????????????
9 Replies
maxmahem
maxmahem3mo ago
perfect place for switch
Angius
Angius3mo ago
Just FYI, variable names cannot start with a number
maxmahem
maxmahem3mo ago
var result = numberFinder switch {
<= 10 => "The number is 10 or lower.",
<= 20 => "The number is between 11 and 20.",
<= 30 => "The number is between 21 and 30.",
_ => "The number is 31 or higher.",
}
var result = numberFinder switch {
<= 10 => "The number is 10 or lower.",
<= 20 => "The number is between 11 and 20.",
<= 30 => "The number is between 21 and 30.",
_ => "The number is 31 or higher.",
}
Angius
Angius3mo ago
But if you wanted to use a chain of if-else, you certainly can First check <= 10, then <= 20, then <=30 Then an else
Melton
Melton3mo ago
I apologize, I just had to put up an example really quick
Melton
Melton3mo ago
I actually didn't think of that. That's a pretty good idea Thank you. I will look more into switch. I'll very likely use it at some point. Many thanks!
maxmahem
maxmahem3mo ago
not only is switch clearer in these cases, the compiler (may) build it into a binary if tree, so its slightly faster.
Melton
Melton3mo ago
I will write that down in my notes