Solution Review: while Loops

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

We'll cover the following

Solution: Using while Loop

Press + to interact
testVariable <- 1
while (testVariable <= 20) { # Ccheck whether testVariable is less than or equal to 20
if(testVariable %% 3 == 0 && testVariable %% 5 == 0)
{
cat(testVariable, "foo bar ")
} else
{
if(testVariable %% 3 == 0)
{
cat(testVariable, "foo ")
}
if(testVariable %% 5 == 0)
{
cat(testVariable, "bar ")
}
}
testVariable = testVariable + 1 # increment testVariable to move on to the next number to check
}

Explanation

One simple approach is to copy paste the condition block (line number 4 to 17 in the above code) 2020 times. However, this method is redundant and lengthy.

We can write a while loop that runs 2020 times and for each iteration checks the condition. For this, we make a variable testVariable whose value is 11. Then, in each iteration, we check whether testVariable is less than or equal to 2020, and also increment at the end of each iteration.