Search⌘ K
AI Features

Solution Review: for Loops

Learn how to implement and solve problems using for and while loops in R. This lesson demonstrates iterating through vector elements with practical code examples, helping you grasp loop constructs and vector indexing in R programming.

Solution #1: Using for Loop

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, 55 or both.

Solution #2: Using while Loop

R
testVariable <- c(3, 5, 15)
index <- 1 # variable to iterate over the whole vector
n <- length(testVariable) # length of the vector
while (index <= n) {
if(testVariable[index] %% 3 == 0 && testVariable[index] %% 5 == 0)
{
cat(testVariable[index], "foo bar ")
} else
{
if(testVariable[index] %% 3 == 0)
{
cat(testVariable[index], "foo ")
}
if(testVariable[index] %% 5 == 0)
{
cat(testVariable[index], "bar ")
}
}
index = index + 1 # increment the index
}

Explanation

Here, we are using a while loop to solve this problem.

Remember we could fetch an element in a vector using square brackets [].

We have fetched all elements of the vector using their indexes, for example, testVariable[1], testVariable[2]testVariable[n]. Here, n is the last element (placed at length(testVariable)). We iterate over all these indexes starting from 11 to nn using the while loop.


There is another method to make loops using repeat.