...

/

Solution Review: for Loops

Solution Review: for Loops

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

Solution #1: Using for Loop

Press + to interact
R
testVariable <- c(3, 5, 15)
for (element in testVariable) {
if(element %% 3 == 0 && element %% 5 == 0)
{
cat(element, "foo bar ")
} else
{
if(element %% 3 == 0)
{
cat(element, "foo ")
}
if(element %% 5 == 0)
{
cat(element, "bar ")
}
}
}

Explanation

We have a vector testVariable that contains all the numbers.

We initiate a for loop for all the elements in the vector (line number 2) and check whether that element is a multiple of 33 ...