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
testVariable <- 1while (testVariable <= 20) { # Ccheck whether testVariable is less than or equal to 20if(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) times. However, this method is redundant and lengthy.
We can write a while
loop that runs times and for each iteration checks the condition. For this, we make a variable testVariable
whose value is . Then, in each iteration, we check whether testVariable
is less than or equal to , and also increment at the end of each iteration.