Solution Review: if/else Statements

In this review, we provide a detailed analysis of the solution to this problem.

Solution: Using a Combination of if and else

Press + to interact
testVariable <- 45
if(testVariable %% 3 == 0 && testVariable %% 5 == 0)
{
cat("foo bar")
} else {
if(testVariable %% 3 == 0)
{
cat("foo")
}
if(testVariable %% 5 == 0)
{
cat("bar")
}
}

Explanation

We first check whether the testVariable is a multiple of both 33 and 55. For this, we use an if condition

testVariable %% 3 == 0 && testVariable %% 5 == 0

The modulus sign %% helps us figure out whether the testVariable is a multiple of the number. The remainder after division of testVariable with 33 would be 00 if it is a multiple of 33. The remainder after division of testVariable with 55 would also be 00 if it is a multiple of 55.

We then AND the results of both the tests.

If this condition is not satisfied, we move towards the else block. In the else block we have two more if conditions: one for only multiple of 33 and one for checking only multiple of 55.