Reputation: 349
I have three if-else statements. Something like this:
int Group1 = 1;
int Group2 = 3;
int Group3 = 6;
if (Group1 < Group2 && Group1 < Group3)
{
Group1 += 5;
}
else if (Group2 < Group1 && Group2 < Group3)
{
Group2 += 5;
}
else
{
Group3 += 5;
}
Now, I believe the code above will go through the first if statement as the Group1 is the smallest, but then the value changes so second if will be processed as well. How to stop on the first if statement and break from the loop when the smallest Group integer is found? or maybe I'm wrong and only first if statement will be calculated?
Upvotes: 0
Views: 922
Reputation: 44285
if
statements accept a boolean expression. In this case it doesn't matter what the expression is only the resultant value produced by evaluating the expression. All you really need is to create a minimal, compile-able example. In other words, remove the noise created by all that boolean logic. Once you add this skill to your toolbox you can begin to answer these types and even more complex questions yourself.
void Main()
{
bool first = true;
bool second = false;
if(first){
second = true;
Console.WriteLine("One true");
}else if(second){
Console.WriteLine("Two trues");
}else{
//more like default, but you don't see this which is what matters
Console.WriteLine("Three trues");
}
}
//Result: One True
Upvotes: 1
Reputation: 61349
Only the first if statement will be evaluated.
There is no loop here; only a set of conditionals. Because you used else if
that block can only be entered if the original if
evaluated to false. If instead you had written
if (Group1 < Group2 && Group1 < Group3)
{
Group1 += 5;
}
// No else
if (Group2 < Group1 && Group2 < Group3)
{
Then both would execute.
Upvotes: 4