Callum Osborn
Callum Osborn

Reputation: 25

If statement for multiples of an variable

I know how to construct if statements that can take multiple conditions.

if ((condition1) || (condition2) || (conditionN))
    statements;

And I want to simply the expression I have at the moment.

if ((gameScore == 480) || (gameScore == 960) || (gameScore == 1440))

Basically I want to have a if statement or something similar the will execute code when gameScore is equal to any multiple of 480.

Upvotes: 0

Views: 934

Answers (2)

ryanyuyu
ryanyuyu

Reputation: 6486

Well if you only need to check multiples of 480, use a modulus-based check.

if (gameScore % 480 == 0) {}

To answer your first question, a switch statement is another option for combining if-statements for certain circumstances. So in this example, you could do something like

switch (number)
{
    // A switch section can have more than one case label. 
    case 480:
    case 960:
    case 1440:
        //do stuff for these three cases
    default:
        //else
        break;
}

See http://msdn.microsoft.com/en-us/library/06tc147t.aspx for more on switch statements in C#.

Upvotes: 3

itsme86
itsme86

Reputation: 19526

You can use the modulus (%) operator which is similar to division (/) but returns the remainder of the operation instead of the quotient. The remainder will be 0 after dividing by 480 if the number is a multiple of 480.

if ((gameScore % 480) == 0)

Upvotes: 7

Related Questions